很痛,在這裏問一下。它確實如此。每次我徒勞地尋找解決問題的答案時,我都會看到它。嘲弄我。 Stack Overflow。延續傳球風格讓事情尾巴遞歸?
無論如何,一些地獄般的影響使我試圖解決河內的塔。我的第一個解決方案是不完整的,因爲它導致了memory error如果有太多的磁盤上運行:
(define hanoi
(lambda (n from to other)
(cond ((< n 0)
(error `(Error! Number of disks ,n cannot be less than 0!)))
((= n 0)
'())
(else
(append (hanoi (- n 1)
from
other
to)
`((,from ,to))
(hanoi (- n 1)
other
to
from))))))
我讀的地方,延續傳遞風格,將解決這個問題。然而,這didn't help either:
(define hanoi_cps
(lambda (n from to other c)
(cond ((< n 0)
(error `(Error! Number of disks ,n cannot be less than 0!)))
((= n 0)
(c '()))
(else
(hanoi_cps (- n 1)
from
other
to
(lambda (x)
((lambda (w)
(w `((,from ,to))))
(lambda (y)
(hanoi_cps (- n 1)
other
to
from
(lambda (z)
(c (append x y z))))))))))))
出於好奇,有多少塊硬盤太多? – dyoo
@ haooi的@dyoo:19個磁盤;對於'hanoi_cps':15個磁盤 – ikdc