Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parentheses in the pattern matching in a function declaration Haskell

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.

like image 896
MC2DX Avatar asked Dec 01 '13 12:12

MC2DX


1 Answers

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.

like image 122
Ingo Avatar answered Sep 30 '22 14:09

Ingo