0

我的代码是:

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 呢?

4

1 回答 1

3

惰性列表可能是无限的,因此一般情况下,将其全部打印出来并不是一个好主意。通常,需要一些有限前缀并将其收集到一个有限列表中。您甚至使用自己的代码实现了相应的功能,

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

附带说明,您应该使用 currying forltake以便它可以作为ltake 3 x.

于 2019-11-26T16:46:53.457 回答