【发布时间】:2015-05-05 03:50:44
【问题描述】:
我正在阅读由 Chris Okasaki 编写的纯函数式数据结构。
本书第6章向我们介绍了惰性评估,我比较了两个版本
(*
https://github.com/mmottl/pure-fun/blob/master/chp5.ml#L47
*)
module BatchedQueue : QUEUE = struct
type 'a queue = 'a list * 'a list
let empty = [], []
let is_empty (f, _) = f = []
let checkf (f, r as q) = if f = [] then List.rev r, f else q
let snoc (f, r) x = checkf (f, x :: r)
let head = function [], _ -> raise Empty | x :: _, _ -> x
let tail = function [], _ -> raise Empty | _ :: f, r -> checkf (f, r)
end
懒惰的版本是:
(*
https://github.com/mmottl/pure-fun/blob/master/chp6.ml#L128
*)
module BankersQueue : QUEUE = struct
type 'a queue = int * 'a stream * int * 'a stream
let empty = 0, lazy Nil, 0, lazy Nil
let is_empty (lenf, _, _, _) = lenf = 0
let check (lenf, f, lenr, r as q) =
if lenr <= lenf then q
else (lenf + lenr, f ++ reverse r, 0, lazy Nil)
let snoc (lenf, f, lenr, r) x =
check (lenf, f, lenr + 1, lazy (Cons (x, r)))
let head = function
| _, lazy Nil, _, _ -> raise Empty
| _, lazy (Cons (x, _)), _, _ -> x
let tail = function
| _, lazy Nil, _, _ -> raise Empty
| lenf, lazy (Cons (_, f')), lenr, r -> check (lenf - 1, f', lenr, r)
end
这两个版本非常相似,check函数都需要反转列表,理论上是O(n)。
好像两个版本的时间复杂度一样,不知道在Queue数据结构中使用惰性求值有什么好处?
【问题讨论】:
标签: ocaml lazy-evaluation