[Haskell-cafe] Pattern match failure

Ariel J. Birnbaum valgarv at gmx.net
Thu Apr 10 17:36:08 EDT 2008

I think you were having a similar problem in an earlier thread.
Others have given answers, but I'll try to drive the point home further.

In a pattern match like this:

  f a = case a of
    [Rule x y] -> ...

the pattern is *NOT* matched against each element of the list, but against the 
list as a whole.
Say we have an expression like:

  let f [x] = True
    l = [1,2,3]
  in f l

In the third line we attempt to match the list [1,2,3] against the pattern 
[x]. This cannot possibly work -- [x] can only match a list with a single 

I hope it's more clear now -- and that I answered the right question at all! 
There's more detail below if you're interested.

{-# nitty-gritty on #-}
In more detail, recall that [x] is nothing but syntactic sugar for x:[]. That 
is, the (:) constructor applied to x and []. [1,2,3] in turn stands for 
1:2:3:[]. Pattern matching then proceeds:

Match 1:2:3:[] against x:[]
	(:) matched -> match 1 against x; 2:3:[] against []

Match 1 against x
	x is a variable, bind it to 1

Match 2:3:[] against []
	Match failed!
{-# nitty-gritty off #-}

Have fun =)

Jealous 'cause I never had any homework in Haskell,
Ariel J. Birnbaum

More information about the Haskell-Cafe mailing list