Perl 6汉诺塔函数调用报错:位置参数数量不足问题咨询
Perl 6汉诺塔函数调用报错:位置参数数量不足问题咨询
嘿,这个问题我之前碰到过!咱们先拆解下报错原因,再给你搞定它~
首先看你遇到的错误信息:
Too few positionals passed; expected 3 arguments but got 0
in sub print_instruction atline 15
in blockat
问题核心出在调用hanoi时传递的print_instruction参数上。在Perl 6里,如果你直接写子例程名而不加&符号,解释器会立刻执行这个子例程,而不是把它作为代码引用传递给hanoi函数。这时候执行print_instruction没传任何参数,自然就触发了“参数不足”的错误。
修复方案
只需要在传递的子例程名前加上&符号,告诉Perl 6你要传递的是这个子例程的引用,而非立即执行它:
sub hanoi(Int:D $n, Str:D $start, Str:D $end, Str:D $extra, &move_disk:(Int:D, Str:D, Str:D --> Nil) --> Nil) { if $n == 1 { move_disk(1, $start, $end); # Step 1 } else { hanoi($n - 1, $start, $extra, $end); # Step 2 move_disk($n, $start, $end); # Step 3 hanoi($n - 1, $extra, $end, $start); # Step 4 } } sub print_instruction(Int:D $n, Str:D $start, Str:D $end --> Nil) { say "Move disk #$n from $start to $end"; } # 这里加上&符号传递子例程引用 hanoi(3, 'A', 'B', 'C', &print_instruction);
运行后的正确输出
执行修正后的代码,你会得到预期的汉诺塔移动步骤:
Move disk #1 from A to B Move disk #2 from A to C Move disk #1 from B to C Move disk #3 from A to B Move disk #1 from C to A Move disk #2 from C to B Move disk #1 from A to B
另外补充个小技巧:如果你想用匿名子例程包裹逻辑传递,也可以这么写,效果完全一致:
hanoi(3, 'A', 'B', 'C', -> $n, $s, $e { print_instruction($n, $s, $e) });
不过显然直接传递&print_instruction更简洁直观。
备注:内容来源于stack exchange,提问作者vonbrand
相关产品推荐
相关产品推荐

