SML模式匹配投掷"类型的规则不同意[tycon mismatch]"错误

时间:2014-11-03 22:19:02

标签: pattern-matching sml

fun sample(list_of_str_lists, s) =
    case list_of_str_lists of
           [] => []
        | x::[] => case (all_except_option(s, x)) of
                        SOME lst => lst
                      | NONE => []
        | x::xs' => case (all_except_option(s, x)) of
                        SOME lst => lst @ sample(xs', s)
                      | NONE => [] @ sample(xs', s)

它使用一个辅助函数,它接受一个字符串列表,如果该列表中有匹配的字符串,则返回该列表中list option中的所有元素(同样,不包括匹配的字符串)。因此,辅助函数将采用列表["a", "b", "c"]和字符串"a",如果它与"a"匹配,则会返回包含["b", “c”]的选项。

我的问题出在最后一个模式匹配分支的sample中。它抛出错误

earlier rule(s): 'Z list option -> 'Z list
  this rule: string list list -> string list
  in rule:
    :: (x,xs') =>
      (case (all_except_option (s,x))
        of SOME lst => lst @ sample <exp>
         | NONE => nil @ sample <exp>

但我不明白为什么,因为我试图匹配SOME lst的调用模式,但它将其描述为string list list。发生了什么事?

1 个答案:

答案 0 :(得分:4)

由于嵌套的case表达式,这是一个语法问题。解析器假定案例| x::xs' => ...是正在进行的案例表达式case (all_except_option(s, x)) of ...的延续,因为它无法告诉它实际上意味着属于封闭表达式case list_of_str_lists of ...

如果将内部case表达式括在括号中,函数定义将解析。

fun sample(list_of_str_lists, s) =
  case list_of_str_lists of
    []     => []
  | x::[]  => (case (all_except_option(s, x)) of
                 SOME lst => lst
               | NONE     => [])
  | x::xs' => (case (all_except_option(s, x)) of
                  SOME lst => lst @ sample(xs', s)
                | NONE     => [] @ sample(xs', s))