代码之家  ›  专栏  ›  技术社区  ›  Swift142

为什么这不是一个列表?

  •  0
  • Swift142  · 技术社区  · 7 年前

    请原谅我对OCaml的陌生性,但我有一个非常简单的函数,其中我返回两个列表的交集,但只有当元素同时位于两个列表中时。在第三行,我被告知“这个表达式的类型是‘a’,但一个表达式的类型应该是‘a list’,但这不是我正在输出的列表吗?

     let rec intersection (l1 : 'a list) (l2 : 'a list) : 'a list = match l1,l2 with
      | [],[] -> []             (* empty lists *)
      | [h1::t1], [h2::t2] ->   (* non-empty lists *)
          if h1 = h2          (* if both elements are the same *)
            then h1 :: intersection(t1,t2)   (* include in intersection response *)
            else intersection(t1, t2)        (* else ignore it and check the remaining elements *)
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Jeffrey Scofield    7 年前

    a :: b 列表的标题是 a 谁的尾巴是 b . 那么表达式 [a :: b] 是一个列表列表。很可能你的模式应该是 h1 :: t1 h2 :: t2 .

    如果你像@PieOhPah所指出的那样发布整个函数,那么帮助会容易得多。

    您的代码中至少有两个错误。如果我按照上面给出的方式编译代码,我会看到:

    File "a1.ml", line 5, characters 13-15:
    Error: This expression has type 'a but an expression was expected of type
         'a list
         The type variable 'a occurs inside 'a list
    

    如果我改变你的模式 [h1 :: t1], [h2 :: t2] h1 :: t1, h2 :: t2

    File "a2.ml", line 5, characters 31-38:
    Error: This expression has type 'b * 'c
       but an expression was expected of type 'a list
    

    发生第二个错误是因为递归调用 intersection 正在传递元组 intersection (a, b) . 但是 以咖喱形式定义,即它采用单独的参数 intersection a b

    如果我同时做了这两个更改,我就看不到任何进一步的类型错误。还有其他错误,但它们不是类型错误。