Gangmax Blog

Hanoi in Clojure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(defn hanoi "The classical recursive example implementation in Clojure language." [n move from to temp]
(if (<= n 0)
(print "n should be a positive integer.")
(if (= n 1)
(move n from to)
(do
(hanoi (- n 1) move from temp to)
(move n from to)
(hanoi (- n 1) move temp to from)))))

(def counter (atom 0))

(hanoi
5
#(do
(swap! counter (partial + 1))
(print (str @counter ": Move No." %1 " disk from '" %2 "' to '" %3 "'.\n")))
"Star" "Fini" "Temp")

The output is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1: Move No.1 disk from 'Star' to 'Fini'.
2: Move No.2 disk from 'Star' to 'Temp'.
3: Move No.1 disk from 'Fini' to 'Temp'.
4: Move No.3 disk from 'Star' to 'Fini'.
5: Move No.1 disk from 'Temp' to 'Star'.
6: Move No.2 disk from 'Temp' to 'Fini'.
7: Move No.1 disk from 'Star' to 'Fini'.
8: Move No.4 disk from 'Star' to 'Temp'.
9: Move No.1 disk from 'Fini' to 'Temp'.
10: Move No.2 disk from 'Fini' to 'Star'.
11: Move No.1 disk from 'Temp' to 'Star'.
12: Move No.3 disk from 'Fini' to 'Temp'.
13: Move No.1 disk from 'Star' to 'Fini'.
14: Move No.2 disk from 'Star' to 'Temp'.
15: Move No.1 disk from 'Fini' to 'Temp'.
16: Move No.5 disk from 'Star' to 'Fini'.
17: Move No.1 disk from 'Temp' to 'Star'.
18: Move No.2 disk from 'Temp' to 'Fini'.
19: Move No.1 disk from 'Star' to 'Fini'.
20: Move No.3 disk from 'Temp' to 'Star'.
21: Move No.1 disk from 'Fini' to 'Temp'.
22: Move No.2 disk from 'Fini' to 'Star'.
23: Move No.1 disk from 'Temp' to 'Star'.
24: Move No.4 disk from 'Temp' to 'Fini'.
25: Move No.1 disk from 'Star' to 'Fini'.
26: Move No.2 disk from 'Star' to 'Temp'.
27: Move No.1 disk from 'Fini' to 'Temp'.
28: Move No.3 disk from 'Star' to 'Fini'.
29: Move No.1 disk from 'Temp' to 'Star'.
30: Move No.2 disk from 'Temp' to 'Fini'.
31: Move No.1 disk from 'Star' to 'Fini'.
nil

Comments