Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

haskell - Non exhaustive pattern in function in GHCi

I want to make a function that displays the last element of 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 get the following error:

***Exception: Non-exhaustive patterns in function myLast

I understood that you get this error when you're missing a case, but I think I have included all the possibilities. Any ideas?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use a let in each line, each definition will make a new function named myLast, shadowing all the previous definitions. So what you end up with is equivalent to

GHCi> let myLast (x:xs) = myLast xs

alone.

What you probably want is 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 then load that file into GHCi with ghci MyLast.hs.

The keyword let is only needed when you're already in GHCi (or, in some monad like IO, or in another function) and want to make a local definition. But then you must only use the let once, e.g.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...