简单机器学习标准中的递归

时间:2021-06-17 19:41:42

标签: functional-programming ml

fun max (xs : int list)=
    if null xs
    then NONE 
    else
    let val tl_ans = max(tl xs)
    in
        if isSome tl_ans andalso valOf tl_ans > hd xs
        then
        tl_ans
        else
        SOME (hd xs)
    end

根据我的理解,我无法弄清楚这个程序是如何工作的: 我们输入 else 然后我们递归地调用 max(tl xs) 直到它没有命中,所以当我们没有时,我们检查 in 中的 if 并且它将是假的,然后我们返回 SOME(hd xs)。 问题是我无法理解这个程序是如何逐行工作的,我觉得我错过了一些东西。

1 个答案:

答案 0 :(得分:2)

我怀疑您犯的错误是试图同时推理多个递归。
一次只关注一个函数调用。

示例:

max []NONE,如您所说。

接下来以max [2]为例。

这是

let val tl_ans = max []
in
    if isSome tl_ans andalso valOf tl_ans > 2
    then
        tl_ans
    else
        SOME 2
end

这是

if isSome NONE andalso valOf NONE > 2
then
    NONE
else
    SOME 2

这显然是 SOME 2

接下来,尝试max [3,2]

这是

let val tl_ans = max [2]
in
    if isSome tl_ans andalso valOf tl_ans > 3
    then
        tl_ans
    else
        SOME 3
end

并且您知道 max [2]SOME 2,所以这是

if isSome (SOME 2) andalso valOf (SOME 2) > 3
then
    SOME 2
else
    SOME 3

这是SOME 3

等等...