Skip to main content

Command Palette

Search for a command to run...

Solution of Collatz conjecture on Exercism with Haskell

Updated
2 min read
Solution of Collatz conjecture on Exercism with Haskell
U

I'm a software engineer from Mexico, I've been coding in Python for around 3 years, mostly in personal and college projects. Currently, I'm focusing more in learn and develop in Haskell, one of my current projects is the design and coding of a library to help in the development of book related software.

My hobbies are: listening to music, watching anime and series; reading manga, webtoons, webcomics, and books; programming, traveling when possible, going to the movies, going out for a walk.

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:

Exercism: Haskell

Part 1 of 1

Series of articles talking about my Haskell solution to exercises in Exercism