[Haskell-beginners] matching the output of a standard function
to my function definition (non-exhaustive pattern problem)
Martin Tomko
martin.tomko at geo.uzh.ch
Mon Sep 27 12:15:22 EDT 2010
Dear Daniel
that worked perfectly, thanks for the suggestion!
One more question: how do you use null to check for empty lists?
something like [] == null did not work ... just chekcing, I got my
orignal code to work, thanks again!
Martin
On 9/27/2010 5:56 PM, Daniel Fischer wrote:
> 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