I'm working on learning Haskell, and I've implemented a solution to the first of the 99 Haskell problems. Here is my code:
import Data.Int
import Test.QuickCheck
myLast :: [a] -> Either String a
myLast [] = Left "Empty lists have no last element."
myLast xs = Right ((reverse xs) !! 0)
testMyLast :: [Int] -> Bool
testMyLast xs =
case myLast xs of
Left err -> null xs
Right x -> x == last xs
main = quickCheck testMyLast
Now, I realize that my implementation of myLast
is not the most efficient one. I'm not particularly interested in that type of feedback. Rather, I'm more curious about whether or not I'm following reasonable Haskell code style practices (the naming of things, indentation, etc.), as well as how I'm dealing with errors.
It's my understanding that using Either
(or Maybe
) when an error occurs is, in general, to be preferred over error "..."
, since dealing with exceptions is really only cleanly done in an IO
context. Is my understanding correct? If it is, why do basic library functions (like List
's last
, for example) use error
instead?