【发布时间】:2017-10-17 03:25:01
【问题描述】:
我有这个左折叠的定义
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
我在这里错过了什么?
【问题讨论】:
-
为什么要重新定义 fold_left 而不是使用 List.fold_left?
-
有些老师这样做是为了让学生了解它是如何工作的。我唯一要说的是,对于
fold_left,累加器是第二个参数,而不是第三个参数,所以你在使用List.fold_left时可能会感到困惑。
标签: ocaml higher-order-functions fold