0

我正在尝试编写Batteries.LazyList.lazy_fold_right. 我想要一个类似的函数,它可以折叠在两个惰性列表而不是一个惰性列表上。但是,我遇到了一个对我没有任何意义的错误。

这是我在batLazyList.ml中开始的原始电池定义:

let lazy_fold_right f l init =
  let rec aux rest = lazy begin
    match next rest with
    | Cons (x, t) -> f x (aux t)
    | Nil -> Lazy.force init
  end in
aux l

这是我的版本:

let lazy_fold_right2 f l1 l2 init =
  let open Batteries.LazyList in
  let rec aux rest1 rest2 =
    lazy begin
      match next rest1, next rest2 with
      | Cons (x1, t1), Cons (x2, t2) -> f x1 x2 (aux t1 t2)
      | Nil, Nil | Nil, _ | _, Nil -> Lazy.force init
    end
  in
aux l1 l2

错误出现在带有多个sinit的行尾的变量上:Nil

Error: This expression has type int -> (int -> 'a) -> 'a t but an expression was expected of type 'b lazy_t

嗯?代码中哪里有与ints 相关的内容?我没看到什么?

( Cons, Nil, 和nextLazyList在 batLazyList.ml 中定义。)

4

1 回答 1

1

错误来自隐藏局部变量的init函数。避免该问题的两种可能性是激活警告 44(用于阴影本地标识符)或定义一个短别名而不是本地打开:Batteries.LazyListinitBatteries.LazyList

let lazy_fold_right2 f l1 l2 init =
  let module L = Batteries.LazyList in
  let rec aux rest1 rest2 =
    lazy begin
      match L.next rest1, L.next rest2 with
      | L.Cons (x1, t1), Cons (x2, t2) -> f x1 x2 (aux t1 t2)
      | Nil, Nil | Nil, _ | _, Nil -> Lazy.force init
    end
  in
aux l1 l2
于 2018-01-18T23:02:26.637 回答