Towers of Hanoi in Haskell

November 4, 2009

I went to Vietnam a few months ago, and a friend asked on Twitter if that made me think of the classic “Towers of Hanoi” problem. Well, it has!

Rice noodle factory in Vietnam

Rice noodle factory in Vietnam

Here it is in Haskell, using the Writer monad. This code is a very basic example of how to use tell to report data.
The Writer monad provides a kind of logger, that will record data as values are computed. This algorithm is O(2n), as the structure of the move function clearly shows.