函数声明Haskell中的模式匹配括号 [英] Parentheses in the pattern matching in a function declaration Haskell
问题描述
在下面的例子中,我有一个 x:xs
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屋!