【问题标题】:How exactly this code works?这段代码究竟是如何工作的?
【发布时间】:2013-12-05 06:42:55
【问题描述】:

我知道代码是如何工作的,除了这里的 x 变量:SOME y => SOME (x::y)

fun same_string(s1 : string, s2 : string) =
    s1 = s2

fun all_except_option (str, xs) = 
    case xs of 
    [] => NONE 
     | (x::xs') => case (same_string(str,x)) of 
               true => SOME xs' 
            | false => case all_except_option(str,xs') of 
                   NONE => NONE 
                    | SOME y=> SOME (x::y) 

当您返回 SOME(x::y) 时,"x" 如何保存 ["a","b"] 元素?

val test1 = all_except_option("string", ["a","b","string","c"]) = SOME ["a","b","c"]

【问题讨论】:

    标签: functional-programming pattern-matching sml ml


    【解决方案1】:

    它没有。 y 绑定了列表 ["b","c"]x 绑定了 "a"

    x::y 然后给出列表"a"::["b","c"] = ["a","b","c"]

    从头开始遍历代码:

    "string" <> "a",因此进行了递归调用。
    "string" <> "b",因此进行了另一个递归调用。
    "string = "string",因此SOME ["c"]从第一个递归调用中返回。
    现在,x 持有 "b"y 在第一次递归调用中持有 ["c"],依此类推 SOME "b"::["c"] = SOME ["b","c"] 已返回。
    最后,x 持有 "a"y 持有 ["b","c"] 在顶级调用中,等等 SOME "a"::["b","c"] = SOME ["a","b","c"] 从该调用返回为最终结果。

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 2018-06-16
      • 2021-04-11
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 2021-08-15
      • 2012-06-08
      相关资源
      最近更新 更多