Parentheses in the pattern matching in a function declaration Haskell

人走茶凉 提交于 2019-12-04 03:28:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20311918/parentheses-in-the-pattern-matching-in-a-function-declaration-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!