ZetCode

Scheme stacks, queues and trees

last modified November 25, 2026 Guile 3.0

Stacks, queues, and trees are basic data structures. A stack returns the element added last, a queue the element added first, and a binary search tree keeps its elements ordered so that a search follows a single path from the root. In Scheme, the first two are built from lists, and trees from records. Most versions here are functional: an operation returns a new structure and leaves the old one intact. The examples are run with GNU Guile 3.0.7.

A stack

A list is already a stack. cons adds an element to the front, car reads it, and cdr removes it. Naming these operations makes the intent clear.

stack.scm
(define empty-stack '())

(define (stack-empty? s) (null? s))
(define (push s x) (cons x s))
(define (top s) (car s))
(define (pop s) (cdr s))

(define s1 (push (push (push empty-stack 'a) 'b) 'c))
(define s2 (pop s1))
(define s3 (push s2 'd))

(display s1)
(newline)
(display (top s1))
(display " ")
(display (top s2))
(display " ")
(display (top s3))
(newline)
(display (list s1 s2 s3))
(newline)
(display (stack-empty? (pop (pop s2))))
(newline)

push returns a new stack and does not change the old one. s2 is s1 without its top, and s3 pushes d onto s2. All three stacks share the pairs of (b a), as described in the pairs and lists article, so each push and pop takes constant time and no copying is needed. top and pop of an empty stack fail like car of an empty list, so a program checks stack-empty? first.

$ guile stack.scm
(c b a)
c b d
((c b a) (b a) (d b a))
#t

Checking brackets

A stack fits every problem where the most recent open item must be closed first. A classic case is checking whether the brackets in a text are balanced: each closing bracket must match the last opening bracket that is still open.

brackets.scm
(define pairs '((#\) . #\() (#\] . #\[) (#\} . #\{)))

(define (opening? c) (memv c '(#\( #\[ #\{)))

(define (balanced? text)
  (let loop ((chars (string->list text)) (stack '()))
    (cond ((null? chars) (null? stack))
          ((opening? (car chars))
           (loop (cdr chars) (cons (car chars) stack)))
          ((assv (car chars) pairs)
           => (lambda (entry)
                (and (pair? stack)
                     (char=? (car stack) (cdr entry))
                     (loop (cdr chars) (cdr stack)))))
          (else (loop (cdr chars) stack)))))

(for-each
 (lambda (text)
   (write text)
   (display (if (balanced? text) " balanced" " not balanced"))
   (newline))
 '("(define (f x) (* x x))"
   "v[i] = {a[(j + 1)]}"
   "(car '(1 2)"
   "list[0))"
   "{[}]"
   ""))

balanced? walks the characters with the stack as a loop variable. An opening bracket is pushed. For a closing bracket, assv finds the matching opening bracket, and the => clause of cond passes the entry on. The stack must not be empty and its top must be the matching bracket; otherwise and returns #f at once. Other characters are skipped. At the end, the text is balanced only when the stack is empty. In "{[}]", the } arrives while [ is on top.

$ guile brackets.scm
"(define (f x) (* x x))" balanced
"v[i] = {a[(j + 1)]}" balanced
"(car '(1 2)" not balanced
"list[0))" not balanced
"{[}]" not balanced
"" balanced

A functional queue

A queue adds elements at the back and removes them at the front. With a single list, one of the two operations must walk the whole list. A functional queue therefore keeps two lists: the front list in order, and the back list reversed, so both ends are at the head of a list.

queue.scm
(use-modules (srfi srfi-9))

(define-record-type <queue>
  (make-queue front back)
  queue?
  (front queue-front-list)
  (back queue-back-list))

(define empty-queue (make-queue '() '()))

(define (queue-empty? q)
  (and (null? (queue-front-list q)) (null? (queue-back-list q))))

(define (normalize q)
  (if (null? (queue-front-list q))
      (make-queue (reverse (queue-back-list q)) '())
      q))

(define (enqueue q x)
  (normalize (make-queue (queue-front-list q) (cons x (queue-back-list q)))))

(define (queue-front q) (car (queue-front-list q)))

(define (dequeue q)
  (normalize (make-queue (cdr (queue-front-list q)) (queue-back-list q))))

(define (show q)
  (display (queue-front-list q))
  (display " ")
  (display (queue-back-list q))
  (newline))

(define q1 (enqueue (enqueue (enqueue empty-queue 'ann) 'bob) 'cid))
(show q1)
(define q2 (dequeue q1))
(show q2)
(define q3 (enqueue (enqueue q2 'dan) 'eve))
(show q3)
(display (queue-front q3))
(newline)
(define q4 (dequeue (dequeue q3)))
(show q4)
(display (queue-front q1))
(display " ")
(display (queue-empty? (dequeue (dequeue q4))))
(newline)

enqueue conses the element onto the back list. dequeue drops the first element of the front list. When the front list becomes empty, normalize reverses the back list into a new front list. The output shows the two lists after each step: bob and cid move to the front when ann leaves, and the later arrivals wait in the back list. A reversal costs time proportional to its length, but each element is reversed only once, so on average each operation takes constant time. The old queue q1 still has ann at the front.

$ guile queue.scm
(ann) (cid bob)
(bob cid) ()
(bob cid) (eve dan)
bob
(dan eve) ()
ann #t

A mutable queue

When the old versions of a queue are not needed, a queue can be a single list with a pointer to its last pair. Adding an element changes the cdr of the last pair with set-cdr!. The example uses the queue for round-robin scheduling: each task runs for at most two time units and then goes to the back of the queue.

roundrobin.scm
(use-modules (srfi srfi-9))

(define-record-type <mqueue>
  (make-raw-mqueue front rear)
  mqueue?
  (front mqueue-front set-mqueue-front!)
  (rear mqueue-rear set-mqueue-rear!))

(define (make-mqueue) (make-raw-mqueue '() '()))

(define (mqueue-empty? q) (null? (mqueue-front q)))

(define (enqueue! q x)
  (let ((cell (list x)))
    (if (mqueue-empty? q)
        (set-mqueue-front! q cell)
        (set-cdr! (mqueue-rear q) cell))
    (set-mqueue-rear! q cell)))

(define (dequeue! q)
  (let ((x (car (mqueue-front q))))
    (set-mqueue-front! q (cdr (mqueue-front q)))
    x))

(define quantum 2)
(define tasks (make-mqueue))

(for-each (lambda (task) (enqueue! tasks task))
          '((editor . 3) (compiler . 5) (backup . 1) (player . 4)))

(let loop ((time 0))
  (unless (mqueue-empty? tasks)
    (let* ((task (dequeue! tasks))
           (run (min quantum (cdr task)))
           (left (- (cdr task) run)))
      (display time)
      (display ": ")
      (display (car task))
      (if (> left 0)
          (enqueue! tasks (cons (car task) left))
          (display " done"))
      (newline)
      (loop (+ time run)))))

The record holds the first and the last pair of the list. enqueue! creates a one-element list and links it after the last pair, or makes it the whole list when the queue is empty. dequeue! moves the front to the next pair. Both take constant time. The tasks are pairs of a name and the remaining time. A task that is not finished goes back into the queue with less time left. Guile also has a ready-made mutable queue in the (ice-9 q) module, with make-q, enq!, and deq!.

$ guile roundrobin.scm
0: editor
2: compiler
4: backup done
5: player
7: editor done
8: compiler
10: player done
12: compiler done

A binary search tree

A binary search tree is empty, or it is a node with a key and two subtrees. All keys in the left subtree are smaller than the node's key, and all keys in the right subtree are larger. A search goes left or right at each node, like the binary search of the searching article.

bst.scm
(use-modules (srfi srfi-1) (srfi srfi-9))

(define-record-type <node>
  (make-node key left right)
  node?
  (key node-key)
  (left node-left)
  (right node-right))

(define empty-tree '())

(define (tree-insert tree x)
  (cond ((null? tree) (make-node x empty-tree empty-tree))
        ((< x (node-key tree))
         (make-node (node-key tree) (tree-insert (node-left tree) x) (node-right tree)))
        ((> x (node-key tree))
         (make-node (node-key tree) (node-left tree) (tree-insert (node-right tree) x)))
        (else tree)))

(define (tree-contains? tree x)
  (cond ((null? tree) #f)
        ((< x (node-key tree)) (tree-contains? (node-left tree) x))
        ((> x (node-key tree)) (tree-contains? (node-right tree) x))
        (else #t)))

(define (in-order tree)
  (if (null? tree)
      '()
      (append (in-order (node-left tree))
              (list (node-key tree))
              (in-order (node-right tree)))))

(define (list->tree lst)
  (fold (lambda (x tree) (tree-insert tree x)) empty-tree lst))

(define tree (list->tree '(50 30 70 20 40 60 80 30)))

(display (in-order tree))
(newline)
(display (map (lambda (x) (tree-contains? tree x)) '(40 45 80)))
(newline)
(display (node-key tree))
(display " ")
(display (node-key (node-left tree)))
(display " ")
(display (node-key (node-right tree)))
(newline)

The nodes are immutable records, and the empty list is the empty tree. tree-insert returns a new tree: it rebuilds the nodes on the path to the new key and shares all other subtrees with the old tree. A key that is already present leaves the tree unchanged, so the second 30 is ignored. tree-contains? follows one path from the root. in-order lists the left subtree, the key, and the right subtree, which gives the keys in sorted order. list->tree inserts the keys of a list with fold from the SRFI 1 list library.

$ guile bst.scm
(20 30 40 50 60 70 80)
(#t #f #t)
50 30 70

Traversals

The tree procedures now go into a module, as described in the modules article. Besides the in-order traversal, a tree can be walked in three other common orders.

tree.scm
(define-module (tree)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:export (make-node node-key node-left node-right empty-tree
            tree-insert tree-contains? list->tree in-order))

(define-record-type <node>
  (make-node key left right)
  node?
  (key node-key)
  (left node-left)
  (right node-right))

(define empty-tree '())

(define (tree-insert tree x)
  (cond ((null? tree) (make-node x empty-tree empty-tree))
        ((< x (node-key tree))
         (make-node (node-key tree) (tree-insert (node-left tree) x) (node-right tree)))
        ((> x (node-key tree))
         (make-node (node-key tree) (node-left tree) (tree-insert (node-right tree) x)))
        (else tree)))

(define (tree-contains? tree x)
  (cond ((null? tree) #f)
        ((< x (node-key tree)) (tree-contains? (node-left tree) x))
        ((> x (node-key tree)) (tree-contains? (node-right tree) x))
        (else #t)))

(define (list->tree lst)
  (fold (lambda (x tree) (tree-insert tree x)) empty-tree lst))

(define (in-order tree)
  (if (null? tree)
      '()
      (append (in-order (node-left tree))
              (list (node-key tree))
              (in-order (node-right tree)))))

The module exports the constructor and accessors of the node record, so that programs can write their own procedures over trees.

traversal.scm
(use-modules (tree) (srfi srfi-1))

(define (pre-order tree)
  (if (null? tree)
      '()
      (cons (node-key tree)
            (append (pre-order (node-left tree))
                    (pre-order (node-right tree))))))

(define (post-order tree)
  (if (null? tree)
      '()
      (append (post-order (node-left tree))
              (post-order (node-right tree))
              (list (node-key tree)))))

(define (children node)
  (remove null? (list (node-left node) (node-right node))))

(define (by-levels tree)
  (let loop ((level (if (null? tree) '() (list tree))))
    (if (null? level)
        '()
        (cons (map node-key level)
              (loop (append-map children level))))))

(define tree (list->tree '(50 30 70 20 40 60 80 35 65)))

(display (in-order tree))
(newline)
(display (pre-order tree))
(newline)
(display (post-order tree))
(newline)
(display (by-levels tree))
(newline)
(display (equal? (in-order (list->tree (pre-order tree))) (in-order tree)))
(display " ")
(display (equal? (pre-order (list->tree (pre-order tree))) (pre-order tree)))
(newline)

Pre-order visits a node before its subtrees, and post-order after them. by-levels walks the tree breadth first: it keeps the list of nodes on the current level, collects their keys, and builds the next level from their children with append-map. The list of nodes plays the role of a queue. Pre-order is the order in which to save a tree: inserting the keys again in pre-order rebuilds the same shape, as the last line checks.

$ guile -L . traversal.scm
(20 30 35 40 50 60 65 70 80)
(50 30 20 40 35 70 60 65 80)
(20 35 40 30 65 60 80 70 50)
((50) (30 70) (20 40 60 80) (35 65))
#t #t

The shape of the tree

A search in a tree takes as many steps as the tree is high. The height depends on the order in which the keys are inserted, not only on the keys.

shape.scm
(use-modules (tree) (srfi srfi-1))

(define (tree-size tree)
  (if (null? tree)
      0
      (+ 1 (tree-size (node-left tree)) (tree-size (node-right tree)))))

(define (tree-height tree)
  (if (null? tree)
      0
      (+ 1 (max (tree-height (node-left tree)) (tree-height (node-right tree))))))

(define (show-tree tree depth)
  (unless (null? tree)
    (show-tree (node-right tree) (+ depth 1))
    (display (make-string (* 4 depth) #\space))
    (display (node-key tree))
    (newline)
    (show-tree (node-left tree) (+ depth 1))))

(define (balanced-tree sorted)
  (if (null? sorted)
      empty-tree
      (let ((half (quotient (length sorted) 2)))
        (make-node (list-ref sorted half)
                   (balanced-tree (take sorted half))
                   (balanced-tree (drop sorted (+ half 1)))))))

(define mixed (list->tree '(50 30 70 20 40 60 80)))
(show-tree mixed 0)
(display (list (tree-size mixed) (tree-height mixed)))
(newline)

(define chain (list->tree '(1 2 3 4 5)))
(show-tree chain 0)

(define numbers (iota 1000))
(display (tree-height (list->tree numbers)))
(display " ")
(display (tree-height (balanced-tree numbers)))
(display " ")
(display (equal? (in-order (balanced-tree numbers)) numbers))
(newline)

tree-size counts the nodes and tree-height measures the longest path from the root. show-tree prints the tree turned on its side, with the root on the left and the right subtree on top. Seven keys in a good order give a tree of height 3. Keys inserted in ascending order give a chain in which every node has only a right child; such a tree is no better than a list. A thousand sorted keys build a tree of height 1000. balanced-tree builds a tree from a sorted list by making the middle element the root and building the halves recursively; its height is 10, the smallest possible for a thousand keys. Self-balancing trees, such as red-black trees, keep the height low during insertion.

$ guile -L . shape.scm
        80
    70
        60
50
        40
    30
        20
(7 3)
                5
            4
        3
    2
1
1000 10 #t

Source

Queues — GNU Guile Reference Manual

Binary search tree — Wikipedia

In this article we have built a functional stack on a list, checked brackets with it, written a functional queue from two lists and a mutable queue with a rear pointer, built a binary search tree from records, walked it in four orders, and measured the height of balanced and unbalanced trees. The recursion article explains tree recursion, and the structured data in lists article walks trees of nested lists.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.