【问题标题】:Recursion In simple ML Standard简单机器学习标准中的递归
【发布时间】:2021-09-02 15:05:46
【问题描述】:
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)。 问题是我无法理解这个程序是如何逐行运行的,我觉得我错过了一些东西。

【问题讨论】:

    标签: functional-programming ml


    【解决方案1】:

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

    例子:

    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

    等等……

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 1970-01-01
      • 2010-12-14
      • 2013-08-05
      • 1970-01-01
      • 2019-05-03
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多