使用List.fold_left时的错误类型

时间:2018-01-31 17:10:34

标签: compiler-errors ocaml typeerror

这段代码有一个类型错误,如果你们帮助我那会很棒...

29  let function_1 func (accu: 'a list) b = if (func b)    (* func is a function that takes in a value and returns a boolean*)
30                                        then accu::[]    (* If func return false, I append an empty list. It will create a list list, and it is my intention.*)
31                                        else accu::[b]   (* If func return true, I append the element b.*)
32
33  let function_2 func list =                             (* func is a function that takes in a value and returns a boolean. It is used in function_1*)
34           match list with
35           | [] -> [ [] ]
36           | x::rest -> List.fold_left function_1 func [x] rest

错误发生在:

Line 36, characters 29-40
Error: This expression has type
          ('a list -> bool) -> 'a list -> 'a list -> 'a list list
       but an expression was expected of type
          ('a list -> bool) -> 'a list -> 'a list -> bool
       Type 'a list list is not compatible with type bool

P.S。如果可以,请给我解释而不是实际代码。我更感兴趣的是如何调试它以及为什么它不起作用......

谢谢!

1 个答案:

答案 0 :(得分:0)

List.fold_left的类型是('a -> 'b -> 'a) -> 'a -> 'b list -> 'a,所以 传递给fold_left的函数的返回类型(在您的情况下,它的function_1)必须与他的第一个参数相同。但function_1的类型为('a list -> bool) -> 'a list -> 'a list -> 'a list list而不是('a list -> bool) -> 'a list -> ('a list -> bool)

我不知道你想要达到的目的,所以我不能说太多。