[Haskell-beginners] matching the output of a standard function to my function definition (non-exhaustive pattern problem)

Daniel Fischer daniel.is.fischer at web.de
Mon Sep 27 11:56:46 EDT 2010


On Monday 27 September 2010 17:41:24, Martin Tomko wrote:
> Dear all
>
> I am sure this is a very beginner problem, but I am not sure how to
> solve it:
> I have a myFunct function:
> myFunct :: Int -> [a] -> a
>
> defined as:
> myFunct _ [] = error "empty list provided as arg"
> myFunct a [b] | length [x|x<-[b],fid x == a] == 0 = error "no match"
>                        |    otherwise = head [x|x<-[b],fid x == a]

The pattern `[b]' matches only lists of length 1.
[b] is syntactic sugar for (b : [])

So when you pass a longer list to the function, no pattern matches.

Presumably you wanted the second equation to treat all nonempty lists, n 
which case you simply have to replace all three occurrences of `[b]' with a 
generic variable, e.g. b.

Since you test for empty lists first, no empty list ever reaches that 
equation.

Also, don't use length list == 0 to check for empty lists, if list is long, 
that needs a long time (and possibly a lot of space).

To check for empty lists, use null.

Or pattern match. That would also improve the style in the second equation:

myFunct _ [] = error ".."
myFunct a xs = case [x | x <- xs, fid x == a] of
                [] -> error "no match"
                (y:_) -> y

Cheers,
Daniel


More information about the Beginners mailing list