Solution of Collatz conjecture on Exercism with Haskell
I solved the Collatz conjecture exercise from the Haskell track on Exercism and would like feedback on my solution. But first, let's see what I did.
Firstly, I made a function to take care of the operation if the number n given to the collatz function was an odd number.
oddNumber :: Integer -> Integer
oddNumber n = (3 * n) + 1
Then I did the same for the even numbers.
evenNumber :: Integer -> Integer
evenNumber n = n `div` 2
I stumbled to find a way to save the number of operations before getting to 1. But finally, I decided to use the original collatz function as an initializer for the collatz' function that would resolve the problem.
collatz' :: Integer -> Integer -> Maybe Integer
collatz' n i
| n <= 0 = Nothing
| n == 1 = Just i
| odd n = collatz' (oddNumber n) (i + 1)
| otherwise = collatz' (evenNumber n) (i + 1)
Update [24.11.2022]
After some mentoring inside exercism I summit a new iteration of my solution in which I in-lined my functions oddNumber and evenNumber, use pattern matching for n = 1, and recursion with <$> for the rest.
This is how it looks now:
collatz :: Integer -> Maybe Integer
collatz 1 = Just 0
collatz n
| n <= 0 = Nothing
| odd n = (+ 1) <$> collatz (3 * n + 1)
| otherwise = (+ 1) <$> collatz (n `div` 2)
You can find this and the old iteration here: