Why do I get exception in my own implementation of and function?

Viewed 91

I'm trying to write my own and function in Haskell. It looks like:

and' :: [Bool] -> Bool
and' (x:xs) = x && and' xs

When I use and' [True, True, True] it gives me exception:

*** Exception: 6.hs:27:1-26: Non-exhaustive patterns in function and'

I figured out that adding: and' _ = True fixes my problem, but actually why do I have to add this line? If my way of thinking is correct function should return me True && True && True and when I use this combination in ghci it returns True. Could you explain me it please? Is there a way to see implementation of function and in ghci?

1 Answers

If my way of thinking is correct function should return me True && True && True and when I use this combination in ghci it returns True.

Your and' [True, True, True] will boil down to True && True && True && and' []. Since you did not write a clause for the empty list, it will thus fail. If there was a False in your list, then it would never really make that call to and' [], since False && _ will return False, but a list that contains only Trues will thus eventually make a call with the empty list.

You thus can fix the problem by handling the empty list case as well:

and' :: [Bool] -> Bool
and' [] = True
and' (x:xs) = x && and' xs

If you turn on the -Wincomplete-patterns warning [ghc-doc], it will list the patterns you did not implement.

Related