Towers of Hanoi

お次は、Haskell言語版の「Towers of Hanoi」:

-- hanoi_v1.1.hs
-- Haskell function to compute the Towers of Hanoi problem recursively
-- 
-- Usage: putStr (hanoi_shower (hanoi 1 2 3 n)), or 
--        putStr (hanoi_shower (hanoi 'a' 'b' 'c' n)), 
--        where the first three arguments of hanoi may be polymorphic types
--        (i.e., Chars, Ints, or any other suitable type), and n is the number
--        of discs to move from the source peg to the destination peg
-- 
-- Copyright(c) April 16, 2008, at 14:17, 
-- by Benjamin L. Russell
-- 
-- Update History:
-- 
-- Version 1.0.1
-- Changed program name in comments:
-- "Hanoi.hs" -> "hanoi.hs"
-- 
-- Version 1.0.2
-- Corrected copyright date: April 17 -> April 16
-- 
-- Update History:
-- 
-- Version 1.1
-- Added usage information.
-- October 17, 2008, at 14:45

hanoi :: a -> a -> a -> Int -> [(a, a)]
hanoi source using dest n
    | n == 0 = []
    | n == 1 = [(source, dest)]
    | otherwise = hanoi source dest using (n-1) 
                  ++ hanoi source using dest 1
                         ++ hanoi using source dest (n-1)

hanoi_shower :: Show a => [(a, a)] -> String
hanoi_shower [] = ""
hanoi_shower ((a, b):moves) = unlines ["Move " ++ show a ++ " to "++ show b ++ "."] ++ hanoi_shower moves

上記のHaskellソースコードを実行するには、先ず、Haskellの主流コンパイラGHChttp://www.f13g.com/%a5%d7%a5%ed%a5%b0%a5%e9%a5%df%a5%f3%a5%b0/Haskell/%bd%e8%cd%fd%b7%cf%a4%ce%a5%a4%a5%f3%a5%b9%a5%c8%a1%bc%a5%eb/#content_1_5http://www.haskell.org/ghc/ 参照)をダウンロード・インストールし、その後、例えば、

putStr (hanoi_shower (hanoi 'a' 'b' 'c' 3))

と入力すればいいのです。そうすれば、

Move 'a' to 'c'.
Move 'a' to 'b'.
Move 'c' to 'b'.
Move 'a' to 'c'.
Move 'b' to 'a'.
Move 'b' to 'c'.
Move 'a' to 'c'.

と返ってきます。

どうです?これも簡単だが、またまた美しいでしょう!

では、今回はこの辺で・・・・・・。次回までお楽しみに。

あくまで、アマチュア関数型プログラミング研究者ですから・・・・・・。