I’m haskell beginner. I try to write function that’s will return penultimate list element.
I start so:
lastButOne :: [a] -> a
lastButOne list = if null list
then
0
else
length list
0 string i get error:
Couldn't match type `a' with `Int'
`a' is a rigid type variable bound by
the type signature for lastButOne :: [a] -> a
I understand it. But what can i do here? I don’t know list type. What can i put here?
Thank you.
0 is of type int, so it won’t work for all
a. I would suggest instead to useMaybe alike so:Using guards:
Using the MonadPlus instance of Maybe:
In general, for any instance of MonadPlus:
Although somewhere you will have to specify to the compiler that you want the result as a Maybe. Usually this will be type inferred because it will be passed to a function expecting a Maybe.
Please keep in mind that this runs in O(n). You probably don’t want to be finding the penultimate element of a list… Why do you need to do this? At least consider using an array instead.