从SML中的列表中获取最大值 [英] Getting max value from a list in SML

查看:116
本文介绍了从SML中的列表中获取最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently studying SML and I'm having a hard time understanding the code below

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 xsinttl_ans类型. 为什么此代码有效?系统如何评估递归? 如果您可以使用xs = [3, 4, 5]向我展示这是如何工作的,那将是很好的.

hd xs is of type int and tl_ans, I think is of type list. Why does this code work? How does the system evaluate the recursion? It would be great if you could use xs = [3, 4, 5] to show me how this works.

推荐答案

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

Let me first rewrite this code to an equivalent but more readable version:

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])的评估如何进行:从概念上讲,通过重复替换函数定义的各个分支,可以将其简化为:

Now we can consider how evaluation of goodMax([3,4,5]) proceeds: conceptually, it will be reduced to an answer by repeatedly substituting the respective branch of the function definition(s):

  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'.

I have renamed the y in the inner invocation to y' for clarity.

这篇关于从SML中的列表中获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆