【问题标题】:Define reverse using fold left使用左折叠定义反向
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 你也可以写let reverse l = fold_left List.cons l []
猜你喜欢
  • 2014-09-03
  • 2017-04-11
  • 1970-01-01
  • 2021-04-19
  • 2023-02-15
  • 2012-01-19
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
相关资源
最近更新 更多