A Collatz sequence in Haskell

WordPress.com does not always render Markadown properly, so a copy of this post resides here.

I am coninuing my adventure in Haskell. In order to make it a bit more fun, I decided to code a simple yet very intriguing problem, I first heard of when I read AI Memo 239: The Collatz conjecture.

Item 133
Item 133. The Collatz conjecture in AIM 239

Construct a sequence of integers where given an arbitrary interger the value of the next is:
* If the number is even, divide it by two.
* If the number is odd, triple it and add one.

This can easily be coded in Haskell as follows:

collatz :: Int -> Int
collatz 1 = 1
collatz n =
  if (even n)
    then (n `div` 2)
    else (3 * n + 1)

But how can one obtain a sequence of numbers from this? A very clever solution is here where the author implements a variation of takeWhile which includes also the first list item that fails the test the first time. So my question became, can it be done in another way? Yes it can:

collatzSequence :: Int -> [Int]
collatzSequence n =
  if n == 1
    then [1]
    else [n] ++ collatzSequence (collatz n)

Let's see some test runs:

*Main> collatzSequence 5
*Main> collatzSequence 50
*Main> collatzSequence 500
*Main> collatzSequence 512
*Main> collatzSequence 513

You may have observed we only run it on positive integers. When we run it with negative integers, there are a few more cycles that we need to take into account. Here is the updated sequence function, written with guards:

collatzSequence :: Int -> [Int]
collatzSequence n
  | n == 1 = [1]
  | n == (-2) = [(-2)]
  | n == (-5) = [(-5)]
  | n == (-17) = [(-17)]
  | otherwise = [n] ++ collatzSequence (collatz n)


*Main> collatzSequence (-50)

Now if there was also a way to prove the conjecture…

Please note that in Haskell the unary minus is a function and not an operator, hence, you need to parenthesize. This also works:

*Main> collatzSequence $ -50

Update: A friend posted me his own elegant version of the Collatz sequence:

collatz :: Int -> [Int]
collatz 1 = [1]
collatz n
    | even n =  n : collatz (n `div` 2)
    | odd n  =  n : collatz (n * 3 + 1)

main = do
  putStrLn $ show $ collatz 1
  putStrLn $ show $ collatz 6
  putStrLn $ show $ collatz 23

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s