Ocaml 使用“向左折叠”定义反转

Ocaml 使用“向左折叠”定义反转,ocaml,higher-order-functions,fold,Ocaml,Higher Order Functions,Fold,我有这个左折的定义 let rec fold_left f lst u = match lst with | [] -> u |(h::t) -> fold_left f t ( f h u) 我必须用左上方的折叠定义反向。我现在有 let reverse l1 = fold_left (fun x y -> y::x) l1 [] 但我总是犯这个错误 Error

我有这个左折的定义

let rec fold_left f lst u = match lst with
                            | [] -> u
                            |(h::t) -> fold_left f t ( f h u)
我必须用左上方的折叠定义反向。我现在有

let reverse l1 = fold_left (fun x y -> y::x) l1 []
但我总是犯这个错误

Error: This expression has type 'a list
       but an expression was expected of type 'a
       The type variable 'a occurs inside 'a list

我在这里遗漏了什么?

您只需要将累加器和下一个项目翻转过来(
y::x
,而不是
x::y
)。这项工作:

let reverse l1 = fold_left (fun x y -> x::y) l1 []

为什么重新定义fold_left而不使用List.fold_left?一些老师这样做是为了让学生了解它是如何工作的。我唯一要说的是,对于
fold\u left
,累加器是第二个参数,而不是第三个参数,因此在使用
List.fold\u left
时,您可能会感到困惑。您也可以编写
let reverse l=fold\u left List.cons l[]