从SML中的列表中获取最大值

时间:2013-12-29 08:20:06

标签: list recursion sml

我目前正在学习SML,而我很难理解下面的代码

fun good_max (xs : int list) =
  if null xs
  then 0
  else if null (tl xs)
  then hd xs
  else
    (* for style, could also use a let-binding for (hd xs) *)
    let val tl_ans = good_max(tl xs)
    in
      if hd xs > tl_ans
      then hd xs
      else tl_ans
    end

hd xs的类型为inttl_ans,我认为类型为list。 为什么这段代码有效?系统如何评估递归? 如果您可以使用xs = [3, 4, 5]向我展示这是如何工作的,那就太好了。

1 个答案:

答案 0 :(得分:4)

让我首先将此代码重写为等效但更易读的版本:

fun max(x,y) = if x > y then x else y

fun goodMax(nil) = 0
  | goodMax(x::nil) = x
  | goodMax(x::xs) = let val y = goodMax(xs) in max(x,y) end

现在我们可以考虑goodMax([3,4,5])的评估是如何进行的:从概念上讲,通过反复替换函数定义的相应分支,简化为

  goodMax([3,4,5])
= goodMax(3::[4,5])
= let val y = goodMax([4,5]) in max(3, y) end
= let val y = goodMax(4::[5]) in max(3, y) end
= let val y = (let val y' = goodMax([5]) in max(4, y') end) in max(3, y) end
= let val y = (let val y' = goodMax(5::nil) in max(4, y') end) in max(3, y) end
= let val y = (let val y' = 5 in max(4, y') end) in max(3, y) end
= let val y = max(4, 5) in max(3, y) end
= let val y = (if 4 > 5 then 4 else 5) in max(3, y) end
= let val y = 5 in max(3, y) end
= max(3, 5)
= if 3 > 5 then 3 else 5
= 5

为了清楚起见,我已将内部调用中的y重命名为y'