Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the parentheses signify in (x:xs) when pattern matching?

Tags:

syntax

haskell

when you split a list using x:xs syntax why is it wrapped in a parentheses? what is the significance of the parentheses? why not [x:xs] or just x:xs?

like image 864
Pradeep Avatar asked Feb 03 '10 10:02

Pradeep


People also ask

What does X XS mean?

(x:xs) is a pattern that matches a non-empty list which is formed by something (which gets bound to the x variable) which was cons'd (by the (:) function) onto something else (which gets bound to xs ). [] is a pattern that matches the empty list. It doesn't bind any variables.

How does pattern matching work in Haskell?

Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.

What is a pattern in Haskell?

We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.


1 Answers

The cons cell doesn't have to be parenthesized in every context, but in most contexts it is because

Function application binds tighter than any infix operator.

Burn this into your brain in letters of fire.

Example:

length [] = 0 length (x:xs) = 1 + length xs 

If parentheses were omitted the compiler would think you had an argument x followed by an ill-placed infix operator, and it would complain bitterly. On the other hand this is OK

length l = case l of [] -> 0                      x:xs -> 1 + length xs 

In this case neither x nor xs can possibly be construed as part of a function application so no parentheses are needed.

Note that the same wonderful rule function application binds tighter than any infix operator is what allows us to write length xs in 1 + length xs without any parentheses. The infix rule giveth and the infix rule taketh away.

like image 110
Norman Ramsey Avatar answered Oct 03 '22 18:10

Norman Ramsey