函数声明Haskell中的模式匹配括号 [英] Parentheses in the pattern matching in a function declaration Haskell

查看:188
本文介绍了函数声明Haskell中的模式匹配括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在下面的例子中,我有一个 x:xs

的模式,在模式匹配中我们必须使用圆括号吗? code>其中 x 从列表中取第一个元素,其余元素包含 xs



我想问一下括号是否是这种模式匹配的必要组成部分。

  head':: [a]  - >一个
头'[] =错误不能在空列表上打头!
head'(x:_)= x

我试着不用大括号它会导致加载到ghci期间出错。

解决方案

圆括号不是模式匹配的一部分,就像它们不是表达评估。这就是说,圆括号当然是模式和表达式语法的一部分。



看,如果你写了

  hx:xs 

这看起来像

 (hx):xs 

到解析器。因此,我们写出

  h(x:xs)

都在等号的左侧和右侧。作为表达式,它意味着函数h应用于由x和xs构成的列表,并且在左侧定义了该应用程序的等式。

Do we have to use parentheses in pattern matching in function declarations ?

In example below, I have a pattern x:xs where x takes first element from the list and xs contains the rest.

I would like to ask whether parentheses are a necessary part of this pattern matching.

head' :: [a] -> a  
head' [] = error "Can't call head on an empty list!"  
head' (x:_) = x  

I tried to use it without braces but it causes error during loading into ghci.

解决方案

Parentheses are not part of pattern matching, in the same sense that they are not part of expression evaluation. That being said, parentheses are certainly part of pattern and expression syntax.

Look, if you write

h x:xs

this looks like

(h x) : xs

to the parser. Hence we write

h (x:xs)

both on the left hand side and on the right hand side of the equal sign. As expression, it means "function h applied to a list constructed of x and xs", and on the left hand side it defines an equation for that application.

这篇关于函数声明Haskell中的模式匹配括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆