这段代码究竟是如何工作的

时间:2013-11-21 00:29:16

标签: functional-programming pattern-matching sml ml

我知道代码如何工作,除了 x 变量:SOME y =>一些( 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"]

1 个答案:

答案 0 :(得分: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在{@ 1}}中保留["b","c"],因此 该调用返回SOME "a"::["b","c"] = SOME ["a","b","c"]作为最终结果。