9.8. Real-Time Queues#

Real-time queues are perhaps the most efficient implementations of persistent queues. We believe they were invented by Hood and Melville (Cornell TR 1980, IPL paper 1981). The implementation presented here is based on Okasaki (JFP paper 1995, CUP book 1998).

9.8.1. How Much Work Can One Dequeue Do?#

Recall how a batched queue works. It keeps two lists. We dequeue from the outbox, and we enqueue by consing onto the inbox. For example, the pair

outbox = [1; 2; 3]
inbox  = [6; 5; 4]

represents the queue

1, 2, 3, 4, 5, 6

because reversing the inbox gives [4; 5; 6]. Suppose we dequeue twice. That leaves [3] in the outbox and [6; 5; 4] in the inbox. How much work will the next dequeue do?

Removing 3 is easy. But now we need 4 at the front, and 4 is all the way at the end of the inbox. So this dequeue calls List.rev [6; 5; 4]. If there were a million elements in the inbox, we’d have to visit all million to finish that one dequeue.

Could we have started the reversal a little earlier? Or, better yet, could we do a little of the work on each enqueue and dequeue? That would give us a real-time queue, in which each operation takes constant time even in the worst case. To implement one, we’ll need a way to control when OCaml evaluates an expression.

9.8.2. When Does OCaml Do the Work?#

Let’s start with a little experiment in utop. We’ll have the reversal print a message so we can tell when it happens.

let reverse_inbox xs =
  print_endline "reversing";
  List.rev xs

let inbox = [6; 5; 4]
let now = reverse_inbox inbox

When does reversing appear? As soon as we define now. OCaml evaluates the right-hand side of a let binding before binding the name to the value.

Because of the dynamic semantics of function application, it turns out we already have a way to delay that evaluation: we can put the expression in the body of a function.

let later () = reverse_inbox inbox
let first = later ()
let again = later ()

Defining later prints nothing. Each of the next two lines prints reversing, because each call evaluates the body of later. A function of type unit -> 'a that we use to delay a computation is called a thunk.

Note

Some of the material in this section (including thunks, laziness, and memoization) also exists in Sequences and Memoization. We repeat it here for self-containment.

9.8.2.1. How Could We Remember the Result?#

Both calls to later produce [4; 5; 6]. It seems a shame to reverse the list a second time when we’ve already computed the answer. We could save the result of the first call and return it on the second. That technique is called memoization.

How could we implement it? A ref would let us remember something from one call to the next. Initially the ref should contain the thunk, because we still need a way to compute the result. Once the thunk returns, the ref should contain the result itself. A variant gives us just the two cases we need.

module MemoizedThunk = struct
  type 'a state = Suspended of (unit -> 'a) | Done of 'a
  type 'a t = 'a state ref

  let delay thunk = ref (Suspended thunk)

  let force cell =
    match !cell with
    | Done value -> value
    | Suspended thunk ->
        let value = thunk () in
        cell := Done value;
        value
end

The module calls those two operations delay and force. Let’s try them with our reversal. Which line will print reversing?

let pending = MemoizedThunk.delay later
let shared = pending
let first = MemoizedThunk.force pending
let again = MemoizedThunk.force shared

Evaluating the binding for first prints the message. At that point the ref contains Suspended later, so force calls later () and assigns Done [4; 5; 6] to the ref. What does force find when we call it on shared? That very same ref, with the answer already in it.

9.8.2.2. From MemoizedThunk to OCaml’s lazy#

OCaml has built-in support for this idiom. Where we wrote MemoizedThunk.delay (fun () -> reverse_inbox inbox), we can instead write lazy (reverse_inbox inbox). Notice what the keyword lazy does for us: if we pass an expression to an ordinary function, OCaml evaluates the argument before the function gets a chance to do anything with it. With lazy, we can write the expression we want to delay and OCaml supplies the thunk.

let pending = lazy (reverse_inbox inbox)
let shared = pending
let first = Lazy.force pending
let again = Lazy.force shared

The type of pending is int list Lazy.t. We call such a value a suspension. The function Lazy.force : 'a Lazy.t -> 'a evaluates the suspended computation the first time we ask for its value. As before, only the binding for first prints a message.

Warning

There is a difference if the computation raises an exception. OCaml remembers the exception and raises it on each subsequent force. Our MemoizedThunk would try the computation again, because it never reached the assignment to Done.

So, would lazy (List.rev inbox) solve our queue problem? No: consider what happens on the first force. If the inbox has a million elements, that force still visits all million. We need a way to force each element incrementally.

9.8.3. Lazy Lists#

Suppose we want to look at the first element of a list before we’ve finished computing the rest. How much of the list do we need? Just enough to tell whether it’s empty and, if it isn’t, to get its head and a way to ask for its tail. Let’s call that much of a list a node.

type 'a lazylist = 'a lazylist_node Lazy.t

and 'a lazylist_node =
  | Nil
  | Cons of 'a * 'a lazylist

Where is the suspension in this type? The lazy list itself is a suspension. Forcing it gives us one node. If that node is a Cons, we get an element of type 'a and another lazy list. We can decide later whether to force that one.

9.8.3.1. From Lists to Lazy Lists and Back#

This function converts an ordinary list to a lazy list:

let rec of_list lst =
  lazy begin match lst with
  | [] -> Nil
  | x :: xs -> Cons (x, of_list xs)
  end

let nums = of_list [1; 2; 3]

How many times has the pattern match run after num is defined? Zero. Even the first match is inside the lazy. Now try this in utop.

let rest =
  match Lazy.force nums with
  | Nil -> failwith "expected a nonempty list"
  | Cons (_, xs) -> xs

That force matches 1 :: [2; 3] and produces Cons (1, of_list [2; 3]). OCaml does call of_list [2; 3] to get the tail. What does that call do? It returns a suspension immediately. Forcing nums again gives us the same node. Forcing rest for the first time produces the node for 2.

To go back to an ordinary list, we have to keep asking for nodes until we reach Nil.

let[@tail_mod_cons] rec to_list ll =
  match Lazy.force ll with
  | Nil -> []
  | Cons (x, xs) -> x :: to_list xs

The [@tail_mod_cons] attribute asks the compiler to use tail-call optimization, even though there is still a cons remaining after the call. The traversal still forces the whole input, so we only want to use to_list when we really want to see the whole answer.

9.8.3.2. How Much Work Does One Force Do?#

Suppose we want just the first two elements. We can write take much as we would for ordinary lists.

let rec take n ll =
  lazy begin if n <= 0 then Nil
    else
      match Lazy.force ll with
      | Nil -> Nil
      | Cons (x, xs) -> Cons (x, take (n - 1) xs)
  end

Try to_list (take 2 (of_list [1; 2; 3])). We get [1; 2]. Do we ever force the input node for 3? When we reach take 0, the if gives us Nil before we ask the input for another node.

Append works much the same way. As long as the first list has another element, we can produce another element of the result.

let rec append ll1 ll2 =
  lazy begin match Lazy.force ll1 with
  | Nil -> Lazy.force ll2
  | Cons (x, xs) -> Cons (x, append xs ll2)
  end

Why force ll2 in the Nil branch? The expression inside lazy has to produce a node. The first node of the second list is exactly the one we need.

Now suppose we want to drop the first two elements. Before we can say what the first node of the result is, we have to get past those two elements. Here’s how the LazyList module does it.

let rec drop' n ll =
  if n <= 0 then ll
  else
    match Lazy.force ll with
    | Nil -> lazy Nil
    | Cons (_, xs) -> drop' (n - 1) xs

let drop n ll = lazy (Lazy.force (drop' n ll))

When we call drop 2 ll, the outer lazy lets us return immediately. When we force the result, drop' walks past two nodes, assuming there are that many. The enclosing Lazy.force then asks the remaining suffix for its first node. Increasing 2 to a million could make that first force quite expensive. But we can’t do much better, because we have to reach the first node of the suffix – we can’t delay it.

What about reversing a lazy list?

let rec reverse' ll acc =
  match Lazy.force ll with
  | Nil -> acc
  | Cons (x, xs) -> reverse' xs (lazy (Cons (x, acc)))

let reverse ll =
  lazy (Lazy.force (reverse' ll (lazy Nil)))

Where is the first element we need? All the way at the end of ll. The first force of reverse ll walks the entire input, building the answer in the accumulator. Imagine refilling a queue with append outbox (reverse (of_list inbox)). We could read the whole old outbox without doing any work on the reversal. But the very next node would cost us a trip through the whole inbox. Could we put each request for an old outbox element to work on the reversal, too?

9.8.4. The Queue Representation#

Let’s keep the inbox as an ordinary list. Enqueueing by consing onto it was cheap all along. We’ll use a lazy list for the outbox, and we’ll keep one more lazy list called the backlog.

type 'a queue = {
  outbox : 'a lazylist;
  inbox : 'a list;
  backlog : 'a lazylist;
}

let empty =
  { outbox = lazy Nil; inbox = []; backlog = lazy Nil }

Let \(L(o)\) be the ordinary list we’d get by forcing every node of the lazy list \(o\) – that is, to_list o. Our abstraction function is

\[ AF(\{outbox;\ inbox;\ backlog\}) = L(outbox) \mathbin{@} \operatorname{rev}(inbox). \]

For example, if the outbox contains 1 through 3 and the inbox is [6; 5; 4], the queue contains 1 through 6 in that order. The abstraction function accounts for every element without mentioning the backlog.

What, then, is the backlog for? That requires a longer explanation. Its purpose is to help refill the outbox. Let’s start by investigating when that needs to happen.

9.8.5. When Should We Refill the Outbox?#

Again, start with the queue in which the outbox contains 1 through 3 and the inbox is [6; 5; 4]. Suppose we enqueue 7 on that queue. The outbox and inbox had equal lengths. Now we have three elements in the outbox and four in the inbox. Imagine starting a new outbox that will eventually contain all seven elements. Which element will someone ask for first? The 1 from the old outbox. Then 2 and 3. While we’re supplying those three elements, we could be getting the 7, 6, and 5 into reverse order. By the time someone asks for 4, we’d have it in hand, with 5, 6, and 7 lined up behind it.

Who will force the node for 1? Suppose the next operation is another enqueue. The inbox will grow again, even though nobody has asked for the front. Let’s use that enqueue to do some of the work on the outbox. We’ll let the backlog point into the new outbox. On each enqueue or successful dequeue, force the node at the backlog. If it’s a Cons, move the backlog to its tail. The outbox and the backlog share nodes, so that force also does the work for anyone who later reads the outbox.

Let’s trace the queue. The outbox column shows the elements in the order we’d get by forcing the whole outbox. The last column tells us where the backlog points within that same lazy list. Each row shows the queue after the update.

Update

Outbox in dequeue order

Queue’s inbox

Next outbox node to step (head of backlog)

Enqueue 7

[1; 2; 3; 4; 5; 6; 7]

[]

1

Enqueue 8

[1; 2; 3; 4; 5; 6; 7]

[8]

2

Dequeue

[2; 3; 4; 5; 6; 7]

[8]

3

Dequeue

[3; 4; 5; 6; 7]

[8]

4

Dequeue

[4; 5; 6; 7]

[8]

5

Enqueueing 7 starts the refill and gives the queue a fresh, empty inbox. Both the outbox and the backlog point to the lazy list starting at 1. Enqueueing 8 puts 8 in the fresh inbox and forces the node for 1. Now the outbox still starts at 1, but the backlog starts at 2. What happens on the first dequeue? Removing 1 reads the node we just forced. Stepping the backlog forces the node for 2 and moves the backlog to 3.

9.8.6. Stepping the Backlog#

Suppose our next three operations enqueue 9, 10, and 11. The outbox stays at 4, and each enqueue steps past one more backlog node. After enqueueing 11, the outbox is 4 5 6 7, the inbox is 11 10 9 8, and the backlog is empty. What would one more update do to those lengths? An enqueue would grow the inbox to five. A dequeue would shrink the outbox to three. Either way, it’s time to start another refill.

Here’s the helper we call after updating the inbox or outbox. Its parameter still contains the backlog from before the update.

let step_backlog q =
  match Lazy.force q.backlog with
  | Cons (_, xs) -> { q with backlog = xs }
  | Nil ->
      let lazy_refill =
        lazy_append_reverse q.outbox q.inbox (lazy Nil)
      in
      { outbox = lazy_refill; inbox = []; backlog = lazy_refill }

The call to step_backlog that steps past 7 takes the Cons branch. It’s the next update that finds Nil and starts the refill. Why bind lazy_refill once? Recall pending and shared from our memoization example. We want those two fields to refer to the very same suspension.

With that helper, the public operations are short.

exception Empty

let enqueue q x =
  step_backlog { q with inbox = x :: q.inbox }

let dequeue q =
  match Lazy.force q.outbox with
  | Nil -> raise Empty
  | Cons (_, xs) -> step_backlog { q with outbox = xs }

let front q =
  match Lazy.force q.outbox with
  | Nil -> raise Empty
  | Cons (x, _) -> x

let is_empty { outbox; _ } =
  match Lazy.force outbox with
  | Nil -> true
  | Cons _ -> false

Calling front or is_empty can force a node. Neither changes the lengths of the inbox and outbox, so both leave the backlog where it is.

The crucial question is: could the outbox be empty while the inbox still contains an element? All three operations that inspect the outbox depend on our ruling that out. Let’s figure out how to ensure it.

9.8.7. Implementing the Refill#

Consider the refill that started when we enqueued 7. Its job is to produce [1; 2; 3] @ List.rev [7; 6; 5; 4]. How can we supply the 1 and do one step of the reversal at the same time? Recall the accumulator in reverse'. We can take 7 off the old inbox and put it onto an initially empty accumulator. When we supply 2, we’ll put 6 in front of 7. When we supply 3, we’ll put 5 in front of those two.

Here are the arguments to the refill helper, lazy_append_reverse xs ys acc. Each row shows the inputs for producing one result node. Read the old inbox from the head, at the left. The accumulator holds the elements we’ve taken off that inbox so far, already in dequeue order.

Node to produce

Old outbox remaining (xs)

Old inbox still to reverse (ys)

Accumulator (acc)

1

[1; 2; 3]

[7; 6; 5; 4]

[]

2

[2; 3]

[6; 5; 4]

[7]

3

[3]

[5; 4]

[6; 7]

4

[]

[4]

[5; 6; 7]

Compare the two tables after enqueueing 8. The backlog points to the node for 2. What will we get if we follow that lazy list to the end? The second row of the refill table gives us the answer, [2; 3] @ List.rev [6; 5; 4] @ [7]. The 7 in the accumulator goes at the very end.

Now suppose xs starts with x and ys starts with y. We can return x as the head of the result. Where should y go? Since List.rev (y :: ys') = List.rev ys' @ [y], putting y at the head of the accumulator leaves the elements in exactly the order we need for the tail.

What about the base case? Look at the row for 4. Once we supply 4, we can use the accumulator directly as its tail.

Now that we understand what the helper needs to do, here is the implementation:

let rec lazy_append_reverse (xs : 'a lazylist)
    (ys : 'a list) (acc : 'a lazylist) : 'a lazylist =
  match (Lazy.force xs, ys) with
  | Nil, y :: _ -> lazy (Cons (y, acc))
  | Cons (x, xs'), y :: ys' ->
      lazy
        (Cons
           ( x,
             lazy_append_reverse xs' ys'
               (lazy (Cons (y, acc))) ))
  | _, [] -> failwith "rotate: RI violated"

Notice where the lazy is. Calling the helper forces one old outbox node and matches the inbox. In the recursive case it returns a suspension for the new node. Forcing that suspension produces Cons. To supply its tail, OCaml calls the helper on xs' and ys' with one more element on the accumulator. That call inspects the next old node and returns a lazy list. The recursion stops there until someone asks for another node.

Try that distinction on the first row of the trace. Enqueueing 7 inspects the old node for 1 and the inbox headed by 7. Enqueueing 8 asks for the new node for 1. That’s when we put 7 on the accumulator and inspect the old node for 2 to prepare the tail.

9.8.8. The Representation Invariant#

Look again at the queue just after the third dequeue. The outbox has four elements, the inbox has one, and the backlog has three. It takes three updates to step past those three backlog elements. It also takes three updates for the inbox to catch up with the outbox, whether we enqueue three times, dequeue three times, or do some of each. Why do those counts agree?

Let \(|o|\), \(|i|\), and \(|b|\) be the lengths of the outbox, inbox, and backlog in a queue returned by the implementation. Each enqueue grows the inbox by one. Each successful dequeue shrinks the outbox by one. Either way, the difference \(|o|-|i|\) decreases by one before we call step_backlog. That gives us the representation invariant:

\[ |b| = |o| - |i|. \]

The backlog is also a shared suffix of the outbox, with every node before that suffix already evaluated. In the empty queue all three lengths are zero and there are no nodes to visit. Let’s see what happens on an update.

  • If the old backlog has a Cons node, stepping it decreases \(|b|\) by one, just as the update decreased \(|o|-|i|\) by one. Forcing that node makes it available in the shared outbox. If a dequeue and the backlog both start at the same node, they both move to its tail.

  • If the old backlog is empty, the outbox and inbox had equal lengths before the update. After the update, the inbox has exactly one more element than the outbox. Each recursive call of lazy_append_reverse consumes one element of each, so when the outbox reaches Nil, exactly one inbox element remains. That’s why the base case can use y and ignore the tail in y :: _. The new inbox is empty, and the new backlog is the entire new outbox. Both parts of the invariant hold again.

Now we can justify inspecting only the outbox in is_empty, front, and dequeue. Rearranging the equation gives \(|o| = |i| + |b|\). If the outbox has length zero, the inbox must have length zero too.

9.8.9. Why Every Operation Is Constant Time#

Consider the moment we start a refill. The backlog has stepped past every element of the old outbox, and step_backlog has just forced the terminal Nil. Consequently, every node the refill inspects in that outbox is already available. Reading one of those nodes costs constant time. This is what prevents a force in one refill from setting off a chain of earlier refills.

How much work can forcing one new outbox node do? In the recursive case, it adds one inbox element to the accumulator and calls the helper once on the remaining inputs. That call reads one available old node, inspects one inbox cell, and returns a suspension. The base case supplies the last inbox element with the accumulator as its tail. Each accumulator node just supplies an element and its existing tail. Every case takes constant time.

An enqueue conses onto the inbox and steps the backlog once. A successful dequeue reads one outbox node and steps the backlog once. Even a step that starts a refill makes only the initial call to the helper. And front and is_empty each read just one outbox node. So every public operation takes \(O(1)\) time in the worst case, even with a million elements in the queue.

9.8.10. What Gets Shared Between Queue Versions?#

Keep the queue we had just after enqueueing 7. Enqueue 8 on that version, then go back to it and enqueue 80 instead. The two new queues have different inboxes, and the original queue still contains 1 through 7. Yet both enqueues step the same backlog. How many times do they compute the new node for 1? Just once. The first enqueue that forces it leaves the answer there for the other.

We’ve seen persistent data structures share values before. Here two versions of a queue can even share a computation that neither has performed yet! Once either version forces it; both have access to the result.