I'm working through exercises in Graham Hutton's book "Programming in Haskell" and as part of one exercise I've re-implemented Haskell's last function like so:
lasst xs = drop (length xs - 1) xs
Now this works nicely for a non-empty list:
> lasst [1,2,3,4,5]
[5]
But, surprisingly to me, for an empty list it returns an empty list:
> lasst []
[]
I'm surprised by this because I would expect (length []) - 1 to be evaluated into -1 and the subsequent evaluation of drop -1 [] to throw.
Why does my implementation return an empty list for an empty list, rather than throw an exception?
-1, sodrop (-1) [], since otherwise you perform adrop - 1 [], which does not make much sense. - Willem Van Onsemdrop -1 []was due to the missing parentheses. When I add them,drop (-1) []returns[]as per spec. - urigdrop (length xs - 1) xsis horribly inefficient: it will walk the list once to get its length; then again to drop the prefix. Better is to codelasstdirectly using pattern matching. (You could then code it to throw an exception on an empty list.) - AntC