Fastest way to get the last element of a list in Haskell
To remove first and last:
take (len(l)-2) (drop 1 l)
or maybe
init (drop 1 l)
This also results in almost optimal code.
last
and init
will do the job just fine for a one-off. However they are both O(n), so if you need to manipulate both ends of a list often, as you seem to imply, you might want to consider using Data.Sequence
instead, which supports O(1) insertion and removal of items at both ends.
I'll post the Prelude implementation since it hasn't been posted yet:
listLast :: [a] -> a
listLast [x] = x --base case is when there's just one element remaining
listLast (_:xs) = listLast xs --if there's anything in the head, continue until there's one element left
listLast [] = error "Can't do last of an empty list!"
Note that I changed the function name to listLast
so that it can be run without conflicting with normal Prelude. You could, of course, do import Prelude hiding(last)
.
You can use the last
function to get the last element of a list.
As for how to remove the first and last elements, you could use (init . tail)
, but I don't know how efficient that is.
I think this image from Learn You A Haskell shows the list functions fairly well: