Search code examples
haskellghci

Haskell patterns code failing with error "Non-exhaustive patterns in function"


I am using ghci. I have a simple function that double's every element in a list. When I tried pattern matching it double's the elements in list but eventually fails with error below:

*Main> let double [] = []
*Main> let double (x:xs) = (2*x) : double xs
*Main> double [10,2,0,5]
[20,4,0,10*** Exception: <interactive>:52:5-37: Non-exhaustive patterns in function double

I got the same function working with guards and patterns. Not sure what I am doing wrong when using patterns alone. Please advise.

*Main> let double (x:xs) | null xs  = [2* x] | otherwise = (2*x) : (double xs)
*Main> double [10,2,0,5]
[20,4,0,10]

Solution

  • Your second let is defining a new double. You can define multi-line functions in GHCi like this.

    λ :{
    | let
    | double :: Num a => [a] -> [a]
    | double [] = []
    | double (x:xs) = 2 * x : double xs
    | :}
    λ double [1,2,3]
    [2,4,6]
    

    Note, this is equivalent to map (2*) though.