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)
The complete solution can be find in the following link:
Top comments (0)