Ocaml类型错误混淆:为什么这会出错?

时间:2011-03-16 03:41:45

标签: list types ocaml typechecking

    let rec add_tail l e = match l with
      | [] -> [e]
      | (h::t) -> h::(add_tail t e)

    let rec fill_help l x n = match n = 0 with
      true -> l
      | false -> add_tail(l, x); fill_help(l, x, n-1)

    let fill x n = 
      let l = [] in
      fill_help(l, x, n)

我在解释器中收到错误

    # #use "prac.ml";;
    val prod : int list -> int = <fun>
    val add_tail : 'a list -> 'a -> 'a list = <fun>
    File "prac.ml", line 13, characters 21-27:
    Error: This expression has type 'a * 'b
           but an expression was expected of type 'c list

第13行将是

    | false -> add_tail(l, x); fill_help(l, x, n-1)

1 个答案:

答案 0 :(得分:4)

首先,你用一个元组作为参数(fill_help)来调用(l, x, n-1),即使它没有定义为一个。您应该将fill_help改为fill_help l x (n-1)。与add_tail相同。

其次,你调用一个无副作用的函数(add_tail)并抛弃它的返回值。这几乎总是一个错误。在调用l后,您似乎希望add_tail有所不同。它不会。您可能需要fill_help (add_tail l x) x (n-1)