Non-exhaustive template in GHCi function
I want to create a function that displays the last item in a list. This is my code:
ghci> let myLast :: [a] -> a
ghci> let myLast [] = error
ghci> let myLast [x] = x
ghci> let myLast (x:xs) = myLast xs
And I am getting the following error:
***Exception: Non-exhaustive patterns in function myLast
I realized that you are getting this error when you are missing a case, but I think I have included all the possibilities. Any ideas?
source to share
If you use let
on each line, each definition will create a new function named myLast
, overshadowing all previous definitions. So what do you end up equivalent to
GHCi> let myLast (x: xs) = myLast xs
one.
You might want to make a haskell file say MyLast.hs
containing
module MyLast where
myLast :: [a] -> a
myLast [] = error
myLast [x] = x
myLast (x:xs) = myLast xs
you can load this file into GHCi with ghci MyLast.hs
.
The keyword let
is only required when you are already in GHCi (or in some monads like IO
or in another function) and want to make a local definition. But then you only have to use let
once eg.
GHCi> let myLast :: [a] → a; myLast [] = error; myLast [x] = x; myLast (x: xs) = myLast xs
or
twiceLast :: [Int] -> [Int]
twiceLast = let myLast [] = error
myLast [x] = x
myLast (x:xs) = myLast xs
in \xs -> 2 * last xs
which I would however prefer to write as
twiceLast = (2*) . myLast
where myLast [] = error
myLast [x] = x
myLast (x:xs) = myLast xs
source to share
In ghci, each use let
introduces a new definition, so you override your function multiple times instead of adding cases.
Two alternatives:
- put the definition in a file and load it with the command
:r
- use
:{ ... :}
to input multiple lines:
eg:.
*Main> :{
*Main| let foo [] = True
*Main| foo _ = False
*Main| :}
*Main>
source to share