【问题标题】:Tail Recursion and Iteration SML尾递归和迭代 SML
【发布时间】:2016-06-14 17:36:05
【问题描述】:

这是我的任务。

(http://prnt.sc/aa3gwd)

我一直在和一位导师一起研究这个,这就是我们迄今为止想出的。

fun mult(a,b) =
  let
    val product = 0
in
    if (a = 0) then 
0
   else
     while a > 0 do
     (                  
       product := product + b;  
       if (a = 1) then 
  product
else
          a:= a -1
     );       
end;
; //the function did not run at end;, so we added these two semicolons below
;

这个输出是:

stdIn:102.11-103.6 Error: syntax error: deleting  SEMICOLON END SEMICOLON

我在过去 2 周内才被介绍到 SML,但我无法理解它。非常感谢任何帮助。

【问题讨论】:

  • 这个练习对我来说没有多大意义——非递归 while 循环版本在任何意义上都“等效于”尾递归方法意味着什么?无论如何——product := product + b 在 SML 中没有意义,因为 int 变量是不可变的。这样的事情需要int ref。你研究过这些吗?

标签: iteration translation sml translate tail-recursion


【解决方案1】:

你需要两个(可变的)引用变量;一个用于产品,一个用于柜台。

类似这样的:

fun mult(a, b) =
  let val product = ref 0
      val counter = ref a
  in
      while !counter > 0 do (
          product := !product + b;
          counter := !counter - 1
      );
      !product
  end;

(这并不完全是您链接到的递归代码的翻译,因为该代码过于复杂。您可能需要根据您的教授进行调整。)

(我会写递归版本更像这样:

fun mult (0, _) = 0
  | mult (_, 0) = 0
  | mult (a, b) = b + mult(a - 1, b);

目前尚不清楚为什么该练习对a = 1 有特殊情况。)

【讨论】:

    猜你喜欢
    • 2011-11-14
    • 2021-05-26
    • 2016-05-09
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多