Dyalog APL - 河内塔 - 无法正常循环

Dyalog APL - Towers of Hanoi - does not loop properly

我无法在 Dyalog APL

中使用它
 solve←{
     n a c b←⍵
     n≤0:⍬
     solve(n-1)a b c
     ⎕←'Move disk from' a 'to' c
     solve(n-1)b c a
 }

 solve 4 'A' 'C' 'B'

它从第一个 solve (n-1) a b c 开始循环,但永远不会转到第 4 行。

相同的代码在 JavaSCript 中有效:

solve = (n, a, c, b) => {
    if (n <= 0) return
    solve(n-1, a, b, c)
    console.log(`Move disk from ${a} to ${c}`)
    solve(n-1, b, c, a)
}

solve(4, 'A', 'C', 'B')

当我打印输入参数时,它显示:

 solve←{
     n a c b←⍵
     ⎕←n a c b
     n≤0:⍬
     solve(n-1)a b c
     ⎕←'Move disk from' a 'to' c
     solve(n-1)b c a
 }

4 ACB
3 ABC
2 ACB
1 ABC
0 ACB

有什么想法吗?

dfn 将 return 用于第一个非赋值。您的两个递归调用都是非赋值,因此该函数不会 return 您认为的那样。您可以像这样稍微调整一下:

solve←{
    (n a c b)←⍵
    n≤0:⍬
    _←∇(n-1)a b c                 ⍝ Capture and ignore result
    ⎕←'Move disk from' a 'to' c
    _←∇(n-1)b c a                 ⍝ Capture and ignore result
    ⍬                             ⍝ Return empty vector
}

请注意 用于递归——这是当前 dfn 的 shorthand。如果我 运行 这个修改后的版本,我得到:

     solve 4 'A' 'C' 'B'
 Move disk from A to B
 Move disk from A to C
 Move disk from B to C
 Move disk from A to B
 Move disk from C to A
 Move disk from C to B
 Move disk from A to B
 Move disk from A to C
 Move disk from B to C
 Move disk from B to A
 Move disk from C to A
 Move disk from B to C
 Move disk from A to B
 Move disk from A to C
 Move disk from B to C

Roger Hui 写了一篇关于这个问题的论文,值得一读:https://www.jsoftware.com/papers/50/50_38.htm