下面的代码使用预定义的函数 moveLOD、swapLOI 和 swapLID 解决了 hanoi 返回移动列表的问题。
MoveLOD:将 1 个圆盘从第一个位置移动到三联体第三个位置的第三个销。此外,包含有关移动信息的字符串正在字符串列表中堆积。
type Pin = (Char, Int) -- Represents a rod, named for a character and the number of disks in it.
type Plate = (Pin, Pin, Pin) -- Represents the configuration of the three rods.(Origin,Intermediate,Destination
type Log = (Plate, [String]) -- Represents a state formed by the configuration of rods and a list of strings that will record the movements made by the algorithm.
moveLOD :: Log -> Log
moveLOD (((o,n), i ,(d,k)),s) = (((o,n-1), i ,(d,k+1)), (o:" -> " ++ [d]):s)
-- swapLOI: Change the positions of the origin rods and intermediate rods.
swapLOI:: Log->Log
swapLOI ((o,i,d),s) = ((i,o,d),s)
-- swapoLID : Change the positions of the intermediate rods and destination rods.
swapLID:: Log->Log
swapLID ((o,i,d),s) = ((o,d,i),s)
hanoi :: Log -> Log
hanoi:: Int->Log->[String]
hanoi 1 log = transformaLista(moveLOD log)
hanoi n log = hanoi (n-1) (swapLID log) ++ hanoi 1 log ++ hanoi (n-1) (swapLOI(log))
changeToList::Log->[String]
changeToList(p,s) = s
callHanoi:: Int->[String]
callHanoi n = hanoi n ((('O',n),('I',0),('D',0)),[])