Grav v1.14.0

Deque

import "std/collections" (included in import "std") · namespace std.collections

Deque<T> (a double-ended queue) adds and removes at both ends in O(1), using a ring buffer. Indexing (d[i], counted from the front) is O(1) too. Use it for queues, sliding windows, and undo histories with a limit.

grav
import "std"

fn main() {
    let d = new Deque<int>()
    d.pushBack(2)
    d.pushBack(3)
    d.pushFront(1)
    print(d)
    print("${d.peekFront()} ${d.peekBack()} ${d[1]}")
    print(d.popFront())
    print(d.popBack())
    print(d)

    // a sliding window of the last 3 values
    let window = new Deque<int>()
    for (v in [4, 8, 15, 16, 23]) {
        window.pushBack(v)
        if (window.size() > 3) { window.popFront() }
    }
    print(window)
}
Output
[1, 2, 3]
1 3 2
1
3
[2]
[15, 16, 23]

popFront, popBack, peekFront and peekBack on an empty deque throw StateError; a bad index throws IndexError.

API

class Deque<T>

Constructors

  • new Deque()

Methods

  • fn size() -> int — The number of elements.
  • fn length() -> int — The number of elements (same as size()).
  • fn isEmpty() -> bool — Whether the deque is empty.
  • fn clear() — Removes every element.
  • fn pushBack(item: T) — Adds an element at the back (O(1)).
  • fn pushFront(item: T) — Adds an element at the front (O(1)).
  • fn popFront() -> T — Removes and returns the front element (StateError when empty).
  • fn popBack() -> T — Removes and returns the back element (StateError when empty).
  • fn peekFront() -> T — The front element (IndexError when empty).
  • fn peekBack() -> T — The back element (IndexError when empty).
  • fn get(i: int) -> T — The element at index i from the front (IndexError when out of range).
  • fn set(i: int, item: T) — Replaces the element at index i from the front.
  • fn operator[](i: int) -> T — d[i]: the element at index i from the front.
  • fn operator[]=(i: int, item: T) — d[i] = v: replaces the element at index i.
  • fn contains(item: T) -> bool — Whether some element equals item.
  • fn forEach(f: fn(T)) — Calls f on each element, front to back.
  • fn toString() -> string — As text: [1, 2, 3] (strings in quotes).
  • fn toArray() -> Array<T> — The elements as a new Array, front to back.

Edit this page on GitHub