【问题标题】:What's the advantage using lazy evaluation in Queue data structure?在队列数据结构中使用惰性求值有什么好处?
【发布时间】: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


    【解决方案1】:

    check 函数的惰性版本(因此 snoc)实际上是 O(1),因为它使用惰性操作执行反向操作,即 (++)reverse 都是惰性的。那是给予信用的地方。当您使用headtail 时,您开始付款。此外,由于隐藏的可变性(懒惰实际上是受限可变性的一种变体),即使您有不同的期货,您也只需为此信用支付一次。银行家队列(和批处理队列)上有一个非常有趣的blog post,它可以帮助您理解为什么这会有所作为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多