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

pi day today

I was looking for some trivia to write for today since it is Pi Day. Like for example, how to calculate the n-th digit of Pi (in base16).  Or how to locate your birthdate in a π sequence. Here is an example for Georgios Papanikolaou and one for Albert Einstein. I found a book on category theory. Or how from searching how to calculate π digits you end up through random clicking to the PSLQ Algorithm (I do not even remember how now). Interesting stuff one rarely gets the chance to get exposed to. Or why tau trumps pi. But I really lack the energy for a proper post today. So it is just links and a piece of art:

6 répartitions aléatoires de 4 carrés noirs et blancs d'après les chiffres pairs et impairs du nombre Pi
François Morellet, 6 répartitions aléatoires de 4 carrés noirs et blancs d’après les chiffres pairs et impairs du nombre Pi, 1958

a newbie does list comprehensions

Formatting this post in WordPress.com was a great pain. It does not render correctly on some browser / device combinations, despite my rewrite efforts. So a Markdown copy of this post can be found as a gist here.

The year is 1998 and @mtheofy then at Glasgow tells me about a relatively new (then) language called Haskell. I’m intrigued but do not do much. A few years later I buy The Haskell School of Expression since The Craft of Functional Programming did not seem enough to motivate me. Time passes and around 2007 I try yet another start. Nothing. I promised my self yet another restart for a 2017 new year’s resolution. Still nothing. So when the current employer offered Haskell classes I could not say no. Armed with the weekly classes and a Safari Learning Path I am trying to correct this. And I am having some fun with list comprehensions. Because as a friend says, if it makes you feel good, go.

So how do you write an infinite list? Let’s say you want list x to include all numbers from 0 to infinity. stack ghci is my friend. Others might try repl.it:

x = [ n | n <- [0..]]

Now you can have the first 20 items of x:

Prelude> x = [ n | n <- [0..]]
Prelude> take 20 x

So next I wanted to make an infinite list of the same character. Enter the underscore variable:

Prelude> x = [ 'a' | _ <- [0..]]
Prelude> take 20 x

OK, so now let’s try to cycle infinitely characters from a string. I end up with:

Prelude> x = [ c | i  take 20 x

I am kind of unsure why the let statements are needed since I am ~10 days into typing stuff and posted my creation to twitter. What my expression says is that x is comprised of characters from string “abcd”, where given a sequence of numbers, each time a character is chosen based on the sequence number modulo 4. Strings are lists of characters in Haskell and list indexing starts from zero.  Helpful comments come my way. Like the obvious cycle (there is a cycle function? Yes ):

Prelude> take 20 (cycle "abcd")
Prelude> take 20 $ cycle "abcd"

Is not the dollar operator nice to get rid of parentheses? Here is another suggestion about cycling a string:

Prelude> x = [ "abcd" !! (i `mod` 4) | i  take 20 x

This one is more concise and does the same thing, always picking a character from "abcd". If the infix notation for mod confuses you, you can:

Prelude> x = [ "abcd" !! (mod i 4) | i  take 20 x

But the Internet does not stop there. It comes back with more helpful suggestions:

Welcome! A little feedback then if I may: the !! operator should be used VERY cautiously it is not typesafe and lists are not random access anyway. Opt for a function returning Maybe x and for a random access datastructure (strings are by default lists).

Which made me think: How about an infinite string randomly chosen from “abcd”?

$ stack install random
$ stack ghci
Prelude> import System.Random
Prelude System.Random> g <- newStdGen 
Prelude System.Random> x = [ "abcd" !! i | i <- randomRs (0,3) g ]
Prelude System.Random> take 10 x
Prelude System.Random>

If you want a sequence with a different order, you need to reinitialise both g and x. I will figure out a better way some other time when …I have time.

Adventures with Maybe maybe in another post.

Formatting this post in WordPress.com was a great pain.


These days I am reading Autonomous in which humans and autonomous robots coexist (there are also indentured humans and robots) and at one point a remark is made about a robotic research assistant that does not need to sleep, implied as an advantage.

This is not something new.  In Beggars in Spain (the first book) there are also genetically engineered people who do not sleep with this being a competitive advantage and causing friction among sleepers and non-sleepers.

And then I remember Marissa Mayer talking about being “strategic about when you sleep, when you shower, and how often you go to the bathroom”.

I think Age of Em deals with this in a better way having Ems slow down their CPUs (making it a matter of energy cost, but I have not finished that book, so I am not sure how this idea gets developed).

Which is why I want to leave you with the 6-2-1 rule that popped into my twitter stream: 6 hours of sleep, 2 meals per day, 1 shower. Analytics from my Nokia Go say that I am not really following this.

Happy New Year.


Last year I promised myself that I would revisit Haskell. Well I did not, so I did not escape the new year’s resolutions cliche. It was an interesting year though, considering that I left my country, worked for Intel, resigned and returned back to Greece and to my previous work.

So for this year I will promise myself something simpler, as a continuation of things I still do in 2017: simply improve my Go-fu. And yes, I also tried to learn Go and miserably failed. Let’s see about that too.

Locations of Ancient Woolworths Stores follow Precise Geometrical Pattern

It has been a while since I last blogged, so here is something funny that I learned today while listening to Relatively Prime:

Matt Parker took it upon himself to debunk junk science related to precise geometry choices by Ancient People. The particular junk piece that triggered his analysis was the assertion of a prehistoric navigation system. However, you may not be familiar with it, but you may have heard terms like “holy geometry” and the like to prove that some Ancient tribe either held some technology now long gone or was in contact with some alien race. But do they really stand?

So Matt, took it upon himself to analyse the locations of the Woolworths in order to figure out whether they had some “outer” help in choosing their store locations:

The results revealed an exact and precise geometric placement of the Woolworths locations. Three stores around Birmingham formed an exact equilateral triangle (Wolverhampton, Lichfield and Birmingham stores) and if the base of the triangle is extended, it forms a 173.8 mile line linking the Conwy and Luton stores. Despite the 173.8 mile distance involved, the Conway Woolworths store is only 40 feet off the exact line and the Luton site is within 30 feet.  All four stores align with an accuracy of 0.05%

So there, proof! Aliens helped them :) Plus, sometimes you need to remind people that 3 points always make a triangle, no coincidence there.

You can read the whole analysis here thanks to the Internet Archive. Given enough data, if you’re looking for a pattern, you’re going to find it I guess.