[Haskell-cafe] Trouble with non-exhaustive patterns

Austin Seipp mad.one at gmail.com
Mon Jul 21 08:14:06 EDT 2008


Hi Fernando,

> final []  = [] - I consider that the end of an empty list is the empty list
> final [a] = a
> final (_:t) = final t
> 
> Suddenly, the function stoped working with a rather cryptic (for a newbie 
> at least) error message:
> 
> *Temp> final [4,5]
> 
> <interactive>:1:9:
>     No instance for (Num [a])
>       arising from the literal `5' at <interactive>:1:9
>     Possible fix: add an instance declaration for (Num [a])
>     In the expr*Temp> ession: 5
>     In the first argument of `final', namely `[4, 5]'
>     In the expression: final [4, 5]


The problem is that final has the type [a] -> a, so you cannot have a
pattern match that simply returns the empty list; this makes the
function partial because taking the tail of an empty list is
undefined.

If you wish to avoid it, you can wrap it in a Maybe:

final :: [a] -> Maybe a
final []    = Nothing
final [a]   = Just a
final (_:t) = final t

$ cat > final.hs
final :: [a] ->	Maybe a
final []    = Nothing
final [a]   = Just a
final (_:t) = final t
$ ghci final.hs 
GHCi, version 6.8.3: http://www.haskell.org/ghc/  :? for help
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( final.hs, interpreted )
Ok, modules loaded: Main.
*Main> final [1,2]
Just 2
*Main> final []
Nothing
*Main> 

Austin


More information about the Haskell-Cafe mailing list