5
head' :: [a] -> a
head' [] = error "No head for empty lists!"
head' (x:_) = x

head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
                      (x:_) -> x

I am asking for a fairly easy question which I don't understand. In the code above, I see that it takes a list for an input. But on the third line, it says (x:_) which confuses me. Can anyone explain to me why they wrote (x:_) instead of [x:_]?

And plus, I don't understand what (x:_) means.

Thank you.

Petr
  • 62,528
  • 13
  • 153
  • 317
tpark
  • 59
  • 1
  • 2

2 Answers2

16

: is a constructor for lists, which takes the head of the new list as its left argument and the tail as its right argument. If you use it as a pattern like here that means that the head of the list you match is given to the left pattern and the tail to the right.

So in this case the head of the list is stored in the variable x and the tail is not used (_ means that you don't care about the value).

And yes, you can also use [] to pattern match against lists, but only lists of fixed size. For example the pattern [x] matches a list with exactly one element, which is then stored in the variable x. Likewise [x,y] would match a list with two elements.

Your proposed pattern [x:y] would thus match a list with one element, which matches the pattern x:y. In other words, it would match a list of lists which contains exactly one list.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • thanks for your comment. I wonder is there a book or a site you migh recommend for haskell newbie? – tpark Dec 19 '10 at 12:03
  • @tpark: This very site contains a lot of advice on learning Haskell. It seems to be a question that pops up every other week. These two questions provide some useful answers: ["How to learn Haskell"](http://stackoverflow.com/questions/1012573/how-to-learn-haskell) and ["Beginners guide to Haskell"](http://stackoverflow.com/questions/16918/beginners-guide-to-haskell). This search might give you more useful resources: ["learn haskell"](http://stackoverflow.com/search?q=learn+haskell). I enjoyed [Learn You a Haskell](http://learnyouahaskell.com/). – ase Dec 19 '10 at 23:34
5

This is a concept called pattern matching. : is an infix constructor, just like + is an infix function. In Haskell you pattern match with constructors.

(1 : 2 : 3 : [])

Is the same as [1, 2, 3], the square bracket notation is just syntactic sugar for creating lists.

Your pattern (x : _) means that you want to bind the first element of the list to x and that you do not care about the rest of the list _.

ase
  • 13,231
  • 4
  • 34
  • 46
  • thanks Adamse. I also wonder what does syntatic sugar means. English is not my first language so. – tpark Dec 19 '10 at 11:46