DEV Community

Cover image for Solution of Collatz conjecture on Exercism with Haskell
Ulises Alexander Arguelles Monjaraz
Ulises Alexander Arguelles Monjaraz

Posted on • Originally published at uaam.hashnode.dev

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
Enter fullscreen mode Exit fullscreen mode

Then I did the same for the even numbers.

evenNumber :: Integer -> Integer
evenNumber n = n `div` 2
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

The complete solution can be find in the following link:

UlisesAlexanderAM's solution for Collatz Conjecture in Haskell on Exercism

Learn from how UlisesAlexanderAM solved Collatz Conjecture in Haskell, and learn how others have solved the exercise.

favicon exercism.org

Top comments (0)