I am brand new to Haskell and am working on a practice Collatz conjecture problem. The required output is the number of steps needed to get to 1 from a given integer. This is the first time I've had to use the Maybe
type, which may be contributing to my confusion.
I have this working solution based on another solution I found to the same problem:
collatz :: Integer -> Maybe Integer
collatz n
| n <= 0 = Nothing
| n == 1 = Just 0
| even n = fmap succ . collatz $ n `div` 2
| otherwise = fmap succ . collatz $ 3 * n + 1
What is unclear to me is why it is necessary to use fmap succ
in this situation. Based on my current understanding, I would expect to just be able to call succ
on the output of the recursive call to collatz
in order to increment it; however, this throws an error:
> No instance for (Enum (Maybe Integer))
arising from a use of `succ'
It looks like the error has something to do with calling succ
on a Maybe Integer
type instead of an Integer
. Is the error because a Maybe Integer
isn't considered enumerable in Haskell? If so why does calling fmap succ
solve this problem?