【发布时间】:2019-05-04 12:44:12
【问题描述】:
我想创建一个函数,该函数采用 int 的惰性列表并随着元素数量的增加返回惰性列表,每个元素 x 必须重复 x 次。例如,我将像常规一样编写惰性列表,为了提高可读性,我将函数 [1; 2; 3],返回[1; 2; 2; 3; 3; 3]。
我写了一些代码,必须这样做:
type 'a lazyList = LNil | LCons of 'a * (unit -> 'a lazyList);;
let lhd = function
| LNil -> failwith "lhd"
| LCons (x, _) -> x
;;
let ltl = function
| LNil -> failwith "ltl"
| LCons (_, xf) -> xf()
;;
let increase llist =
let rec increaseHelper (count, lList) = match (count, lList) with
| (0, LCons(_, xf)) -> increaseHelper((lhd (ltl llist)), (xf()))
| (_, LCons(x, _)) -> LCons(x, function() -> increaseHelper(count - 1, lList))
| (_, LNil) -> LNil
in increaseHelper(lhd llist, llist)
;;
(* ltake函数返回n个常规列表中的惰性元素*)
let rec ltake = function
| (0, _) -> []
| (_, LNil) -> []
| (n, LCons(x, xf)) -> x :: ltake(n - 1, xf())
;;
ltake (20,increase (LCons(4, function() -> LCons(3, function() -> LCons(1, function() -> LCons(4, function() -> LNil))))));;
这个测试返回: - : int list = [4; 4; 4; 4; 3; 3; 3; 1个; 1个; 1个; 4; 4; 4]
所以主要问题是增加函数对于惰性列表的前两个元素工作正常,但是在 3 - 无穷大元素它保存语句从 2 个元素,重复元素多少次
【问题讨论】:
标签: function functional-programming ocaml