I'm learning list operations in Haskell and now I'm trying out various list operations on Maybe list type. Currently, I have this implementation of sum of elements in list in Haskell
sum :: Num a => [a] -> a sum [] = 0 sum (a:t) = a + sum t Now I want to do the same thing but instead of returning the value, I want to return a Maybe type instead. And when the list given is empty it should return Nothing.
I've come up with this
sum :: Num a => [a] -> Maybe a sum [] = Nothing sum (a:t) = fmap (a+) (sum t) But the result of all non empty list given results in Nothing.
From what I understand, the list given will eventually pattern match with the empty list therefore returning Nothing.
How do I fix this so that it returns the expected value and of Maybe type. I can't figure out how to make it work recursively as the normal sum implementation above, so I guess there should be another way. Would prefer if only Prelude module is imported as I'm still trying to absorb stuff inside the Prelude module.