Let's review another programming problem called Towers of Hanoi and solve it using F#. The puzzle was invented by a French mathematician, Édouard Lucas, in 1883 and has been heavily cited in programming literature including Ralf Hinze's Functional Pearl: La Tour D'Hanoi (http://www.comlab.ox.ac.uk/ralf.hinze/publications/ICFP09.pdf). The objective of the puzzle is to move the tower from the starting pole to the target pole in the minimum number of steps following two simple rules:
Only one top disk is allowed to move to a different pole during an action.
A large disk cannot be placed on top of a smaller disk.
A simple Pascal implementation by Daniel W. Palmer, TOWERS OF HANOI in JCSC 12, can easily be implemented in F#. The procedure's pseudo code with the Start
, Target
(finish) and the Aux
(temp) variables is given as follows:
The F# recursive version, similar to the approach described in the preceding screenshot, will result in following non-idiomatic code, and is shown here...