libra
libra

Reputation: 683

trying hard to take the last element from a list (Haskell)

Here is my code, however, i've got no idea how is it wrong, here is my codes:

ll :: [a] ->  a
ll lis = case lis of
  (_:xs) -> ll xs
  [] -> error"xx"

and there is no error message from terminal: but when i run "ll [1, 2, 3]", i suppose to get "3", however, i get the result of "* Exception: xx".

Who likes to tell me what is wrong with it? Thanks XD

Upvotes: 3

Views: 526

Answers (3)

md2perpe
md2perpe

Reputation: 3081

The simplest implementation using predefined functions:

ll = head . reverse

Upvotes: 1

Landei
Landei

Reputation: 54584

I find it helpful to start with the base case of the recursion:

ll [x] = x

Then the recursion:

ll (_:xs) = ll xs

Of course giving a helpful error message is good style. It's often convenient to do this last, when no case matches:

ll _ = error "empty list"

And as a bonus the WTF!?! version:

import Data.List

ll = foldl' (flip const) (error "empty list")

You could call flip const the "Alzheimer's function", it simply forgets its first argument and returns the second, and as foldl' digs through the list from left to right, it will give you the last element.

Upvotes: 6

tom
tom

Reputation: 19163

You're never returning the last element of the list. The first case clause drops the first element of a non-empty list then recursively calls ll. Eventually, you'll hit the empty list case and hence the error gets raised.

Upvotes: 12

Related Questions