如何在 OCaml 中显示 Lazy List 的结果?

How to display a result of Lazy List in OCaml?

我的代码是:

type 'a llist = LNil | LCons of 'a * 'a llist Lazy.t;;
let rec lfrom k = LCons (k, lazy (lfrom (k+1)));;
let rec toLazyList = function
 [] -> LNil
 | x::xs -> LCons(x, lazy (toLazyList xs))
;;

let rec ltake = function
 (0, _) -> []
 | (_, LNil) -> []
 | (n, LCons(x, lazy xs)) -> x :: ltake(n-1, xs)
;;

let rec lzip (lxs, lys) =
 match (lxs, lys) with
 (LCons(h1, lazy t1),LCons(h2, lazy t2)) -> LCons((h1, h2), lazy (lzip (t1, t2)))
 | _ -> LNil
;;

  let lrepeat k ll =
    if k < 1 then failwith "Number less than 1"
    else
    let rec helper (rpts, rest) = match (rpts, rest) with
      (_, LNil) -> LNil
      | (0, LCons(_, tl)) -> helper(k, Lazy.force tl)
      | (_, LCons(hd, _)) -> LCons(hd, lazy (helper(rpts - 1, rest)))
    in helper (k, ll)

然后我做:

> let x = toLazyList([3;4;5]);; 

> val x : int llist = LCons (3, <lazy>)

> lrepeat 3 x;;

> int llist = LCons (3, <lazy>)

但是如何显示一个LazyList?

惰性列表可能是无限的,所以一般来说,打印所有内容并不是一个好主意。通常,人们采用一些有限前缀并将其收集到一个有限列表中。您甚至可以使用自己的代码实现相应的功能,

# ltake (3,x);;
- : int list = [3; 4; 5]

旁注,您应该对 ltake 使用柯里化,这样它就可以像 ltake 3 x.

一样工作