使用左侧折叠定义反向

时间:2017-10-17 03:25:01

标签: 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)

我必须使用上面的fold_left定义反向。我目前有

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

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您只需使用累加器和下一个项目(y::x而不是x::y)。这有效:

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