[ACCEPTED]-Implementing the last function-haskell

Accepted answer
Score: 31

The problem -- like so many others when 22 you're learning Haskell -- is one of typing. Type 21 the following into GHCi

:t mylast

and you'll see that 20 the type signature is

mylast :: [[a]] -> [a]

which expects a list 19 of lists and will return a list. So if you 18 put in a list of strings ["bob", "fence", "house"] the 17 function will work as you've written it.

The 16 problem is your base case: mylast [] = [], which 15 tells the compiler that you want to return 14 a list. You want to return an element, not 13 a list. But there is no empty element in 12 Haskell (very much by design), so you need 11 to use the Maybe monad.

mylast :: [a] -> Maybe a
mylast [] = Nothing
mylast (x:[]) = Just x
mylast (x:xs) = mylast xs

Monads are a somewhat 10 abstract topic, but you need the Maybe monad 9 when you're starting out. All you need to 8 know about it is it's a type declaration 7 that tells the compiler to expect two possibilities: "Nothing," or 6 "Just x". The returning code can then take 5 x and run with it, but if you leave off 4 the "Just," the compiler will complain.

The 3 alternative is to throw an error when an 2 empty list is encountered, like so:

mynextlast [] = error "no empty lists allowed"
mynextlast (x:[])  = x
mynextlast (x:xs) = mynextlast xs

But my 1 suspicion is that Maybe is the way to go.

Score: 9

Try mylast [] = error "Empty list!" instead. Otherwise Haskell cannot infer 1 the type of your function.

Score: 6

EFraim's solution should work (up-voted). But 3 I think this is a little more "Haskell-like":

mylast [] = Nothing
mylast (x:[]) = Just x
mylast (x:xs) = mylast xs

Disclaimer: I 2 haven't actually tried this. I may have 1 made syntax errors.

Score: 2
myLast' [] = error "no empty lists allowed"
myLast' [a] = a
myLast' xs = xs !! (length xs - 1)

0

Score: 0

Thanks for the answers everyone. I have 5 tried...

mylast :: [a] -> Maybe a 
mylast [] = Nothing 
mylast (x:[]) = Just x 
mylast (x:xs) = mylast xs 

and I get eg...

Main> mylast3 [2,4,66,5,4,33] 
Just 33 :: Maybe Integer 

Is there anyway 4 of making it not print the 'just' in the 3 answer?

[EDIT: Jörg W Mittag] (Comments are 2 awful for posting code ...)

Here's how the 1 entire code looks in context:

mylast []     = Nothing
mylast [x]    = Just x
mylast (x:xs) = mylast xs

mylook (Just a) = do print a
mylook Nothing  = do error "Nothing to see here, move along!"

mylook $ mylast [2,4,66,5,4,33]
Score: 0
mylast [x] = x
mylast (x:xs) = mylast xs

recursive call solution

0

More Related questions