ZetCode

Scheme structured data in lists

last modified November 25, 2026 Guile 3.0

Scheme programs often keep their data in plain lists instead of defining record types. A list can be a row of a table, a list of alternating keys and values, or an association list of named fields, and these can be nested into trees like the documents of JSON. Such data needs no declarations, prints readably with write, and can be read back with read. This article shows common shapes of list data and the procedures that query, walk, and change them, in GNU Guile 3.0.7. The association lists article covers the alist procedures, and the records article covers record types.

Rows as lists

The simplest table is a list of rows in which every row is a list of fields in a fixed order. Small accessor procedures give the positions names, so the rest of the program does not depend on them.

rows.scm
(define people
  '(("Lucia" 34 "Bratislava")
    ("Peter" 41 "Kosice")
    ("Jana" 28 "Bratislava")
    ("Tomas" 52 "Nitra")))

(define (person-name p) (car p))
(define (person-age p) (cadr p))
(define (person-city p) (caddr p))

(display (map person-name people))
(newline)

(define (from-city city)
  (filter (lambda (p) (string=? (person-city p) city)) people))

(display (map person-name (from-city "Bratislava")))
(newline)

(define ages (map person-age people))
(display (exact->inexact (/ (apply + ages) (length ages))))
(newline)
(display (apply max ages))
(newline)

person-name, person-age, and person-city pick the first, second, and third field. With them, the queries read like their descriptions: the names of all people, the people from Bratislava, the average age, and the oldest age. filter keeps the rows that pass a test, and map extracts a column. A positional row is compact, but adding a field in the middle changes every position, and a missing field cannot simply be left out.

$ guile rows.scm
(Lucia Peter Jana Tomas)
(Lucia Jana)
38.75
52

Property lists

A property list, or plist, is a flat list of alternating keys and values. It is common in other Lisps. Scheme has no built-in procedures for it, but they take only a few lines.

plists.scm
(define lucia '(name "Lucia" age 34 city "Bratislava"))

(define (plist-ref plist key default)
  (cond ((null? plist) default)
        ((eq? (car plist) key) (cadr plist))
        (else (plist-ref (cddr plist) key default))))

(define (plist-set plist key value)
  (cond ((null? plist) (list key value))
        ((eq? (car plist) key) (cons* key value (cddr plist)))
        (else (cons* (car plist) (cadr plist)
                     (plist-set (cddr plist) key value)))))

(define (plist->alist plist)
  (if (null? plist)
      '()
      (cons (cons (car plist) (cadr plist))
            (plist->alist (cddr plist)))))

(display (plist-ref lucia 'age #f))
(newline)
(display (plist-ref lucia 'email "none"))
(newline)
(write (plist-set lucia 'age 35))
(newline)
(write (plist-set lucia 'email "lucia@example.com"))
(newline)
(write lucia)
(newline)
(write (plist->alist lucia))
(newline)

plist-ref steps through the list two elements at a time with cddr and returns the value after a matching key, or the default. plist-set returns a new list: it replaces the value of an existing key and adds a missing key at the end. The original lucia is unchanged, because the procedure builds new pairs with cons* instead of modifying the old ones. plist->alist converts the flat list into the association list form used in the rest of the article.

$ guile plists.scm
34
none
(name "Lucia" age 35 city "Bratislava")
(name "Lucia" age 34 city "Bratislava" email "lucia@example.com")
(name "Lucia" age 34 city "Bratislava")
((name . "Lucia") (age . 34) (city . "Bratislava"))

Rows as association lists

When every row is an association list, each field carries its name. Rows can then have their fields in any order, and a row can have extra fields or lack some. Two small procedures in the style of SQL make queries over such rows easy to write.

table.scm
(define people
  '(((name . "Lucia") (age . 34) (city . "Bratislava"))
    ((name . "Peter") (age . 41) (city . "Kosice") (email . "peter@example.com"))
    ((name . "Jana") (age . 28) (city . "Bratislava"))
    ((name . "Tomas") (age . 52) (city . "Nitra"))))

(define (get row field)
  (let ((entry (assq field row)))
    (if entry (cdr entry) 'none)))

(define (where test rows)
  (filter test rows))

(define (select fields rows)
  (map (lambda (row)
         (map (lambda (field) (get row field)) fields))
       rows))

(define (older-than n)
  (lambda (row) (> (get row 'age) n)))

(for-each (lambda (row) (write row) (newline))
          (select '(name age) (where (older-than 30) people)))

(write (select '(name email) people))
(newline)

(write (map (lambda (row) (cons '(adult . #t) row))
            (where (older-than 50) people)))
(newline)

get looks up a field and returns none when the row does not have it, as only Peter has an email address. where keeps the rows that pass a test, and select turns every row into a list of the requested fields. older-than returns a test procedure, a closure over n. Adding a field to a row is as easy as consing a pair in front of it; the old row stays unchanged and shares its pairs with the new one.

$ guile table.scm
("Lucia" 34)
("Peter" 41)
("Tomas" 52)
(("Lucia" none) ("Peter" "peter@example.com") ("Jana" none) ("Tomas" none))
(((adult . #t) (name . "Tomas") (age . 52) (city . "Nitra")))

Joining two tables

Related data is often kept in separate tables that refer to each other by an identifier, like customers and their orders. Combining them is a join.

join.scm
(define customers
  '(((id . 1) (name . "Lucia"))
    ((id . 2) (name . "Peter"))
    ((id . 3) (name . "Jana"))))

(define orders
  '(((order . 101) (customer . 1) (total . 45.5))
    ((order . 102) (customer . 3) (total . 12.0))
    ((order . 103) (customer . 1) (total . 30.25))
    ((order . 104) (customer . 4) (total . 8.0))))

(define (get row field)
  (cdr (assq field row)))

(define (find-by field value rows)
  (let loop ((rows rows))
    (cond ((null? rows) #f)
          ((equal? (get (car rows) field) value) (car rows))
          (else (loop (cdr rows))))))

(define (join-orders)
  (map (lambda (order)
         (let ((customer (find-by 'id (get order 'customer) customers)))
           (list (get order 'order)
                 (if customer (get customer 'name) "unknown")
                 (get order 'total))))
       orders))

(for-each (lambda (row) (write row) (newline)) (join-orders))

(define (total-for customer)
  (apply + (map (lambda (order) (get order 'total))
                (filter (lambda (order) (= (get order 'customer) (get customer 'id)))
                        orders))))

(for-each (lambda (customer)
            (display (get customer 'name))
            (display ": ")
            (display (total-for customer))
            (newline))
          customers)

find-by returns the first row whose field has a given value, or #f. join-orders looks up the customer of each order and builds a row with the order number, the customer's name, and the total. Order 104 refers to customer 4, who does not exist, so the name is unknown. total-for works in the other direction: it filters the orders of one customer and adds up their totals. Peter has no orders, and (apply + '()) is the exact 0. Each lookup scans the whole list, which is fine for small tables; for large ones, the rows would go into a hash table keyed by the identifier.

$ guile join.scm
(101 "Lucia" 45.5)
(102 "Jana" 12.0)
(103 "Lucia" 30.25)
(104 "unknown" 8.0)
Lucia: 75.75
Peter: 0
Jana: 12.0

JSON-like trees

JSON documents consist of objects, arrays, strings, numbers, booleans, and null. A common Scheme representation uses an association list with symbol keys for an object, a vector for an array, and the symbol null for null. Using vectors for arrays keeps them apart from objects, which are lists. Such a tree can be stored as Scheme data in a file and loaded with a single read.

shapes.scm
(define shop (call-with-input-file "shop.dat" read))

(define (json-type x)
  (cond ((eq? x 'null) "null")
        ((boolean? x) "boolean")
        ((number? x) "number")
        ((string? x) "string")
        ((vector? x) "array")
        ((list? x) "object")
        (else "unknown")))

(for-each (lambda (entry)
            (display (car entry))
            (display ": ")
            (display (json-type (cdr entry)))
            (newline))
          shop)

(define products (cdr (assq 'products shop)))
(display (vector-length products))
(newline)
(write (cdr (assq 'title (vector-ref products 1))))
(newline)
(write (assq 'address shop))
(newline)

The file shop.dat holds a whole shop as one Scheme datum. json-type tests the vector before the list, and the symbol null before anything else. The program prints the type of every top-level field, then navigates by hand to the title of the second product. When write prints the address entry, the dot before the inner list disappears: (address . ((city . ...))) and (address (city . ...)) are the same pairs, and the second form is the one Scheme prints.

$ cat shop.dat
((name . "Corner Books")
 (open . #t)
 (rating . null)
 (address . ((city . "Bratislava") (street . "Obchodna 12")))
 (staff . #("Lucia" "Peter"))
 (products
  . #(((id . 1) (title . "SICP") (price . 45.5) (tags . #("lisp" "classic")))
      ((id . 2) (title . "The Little Schemer") (price . 32.0) (tags . #("lisp")))
      ((id . 3) (title . "HtDP") (price . 39.9) (tags . #())))))
$ guile shapes.scm
name: string
open: boolean
rating: null
address: object
staff: array
products: array
3
"The Little Schemer"
(address (city . "Bratislava") (street . "Obchodna 12"))

Writing JSON

To exchange the data with other programs, the tree has to be written as JSON. The writer goes into a module, because the last example uses it again. It puts every field of an object on its own indented line and writes arrays of simple values on one line.

json-writer.scm
(define-module (json-writer)
  #:use-module (srfi srfi-1)
  #:export (write-json))

(define (write-json x port)
  (write-value x 0 port)
  (newline port))

(define (simple? x)
  (not (or (vector? x) (pair? x))))

(define (write-value x level port)
  (cond ((eq? x 'null) (display "null" port))
        ((eq? x #t) (display "true" port))
        ((eq? x #f) (display "false" port))
        ((number? x)
         (display (if (and (exact? x) (not (integer? x))) (exact->inexact x) x)
                  port))
        ((string? x) (write x port))
        ((vector? x) (write-array (vector->list x) level port))
        ((list? x) (write-object x level port))
        (else (error "cannot write as JSON:" x))))

(define (write-array items level port)
  (if (every simple? items)
      (begin
        (display "[" port)
        (unless (null? items)
          (write-value (car items) level port)
          (for-each (lambda (item)
                      (display ", " port)
                      (write-value item level port))
                    (cdr items)))
        (display "]" port))
      (write-block "[" "]" items level port
                   (lambda (item) (write-value item (+ level 1) port)))))

(define (write-object entries level port)
  (write-block "{" "}" entries level port
               (lambda (entry)
                 (write (symbol->string (car entry)) port)
                 (display ": " port)
                 (write-value (cdr entry) (+ level 1) port))))

(define (write-block open close items level port write-item)
  (display open port)
  (let loop ((items items))
    (unless (null? items)
      (newline port)
      (display (make-string (* 2 (+ level 1)) #\space) port)
      (write-item (car items))
      (unless (null? (cdr items)) (display "," port))
      (loop (cdr items))))
  (unless (null? items)
    (newline port)
    (display (make-string (* 2 level) #\space) port))
  (display close port))

write-value dispatches on the type of the value. Strings are written with Scheme's write, whose escapes for quotes, backslashes, newlines, and tabs are the same as in JSON; a complete writer would also have to write the other control characters as \u escapes. Exact fractions, which JSON does not have, become decimals. write-array uses every from SRFI 1 to decide whether an array fits on one line. write-block writes the elements of an object or a nested array one per line, indented by two spaces per level, with commas between them.

tojson.scm
(use-modules (json-writer))

(define shop (call-with-input-file "shop.dat" read))

(write-json (vector 1 2/5 "say \"hi\"" #t #f 'null) (current-output-port))
(write-json '() (current-output-port))
(write-json shop (current-output-port))

The program writes a small array that shows the conversion of each type, an empty object, and the whole shop. The empty list is an empty object, so an empty array must be written as the empty vector #(), as the tags of the third product are.

$ guile -L . tojson.scm
[1, 0.4, "say \"hi\"", true, false, null]
{}
{
  "name": "Corner Books",
  "open": true,
  "rating": null,
  "address": {
    "city": "Bratislava",
    "street": "Obchodna 12"
  },
  "staff": ["Lucia", "Peter"],
  "products": [
    {
      "id": 1,
      "title": "SICP",
      "price": 45.5,
      "tags": ["lisp", "classic"]
    },
    {
      "id": 2,
      "title": "The Little Schemer",
      "price": 32.0,
      "tags": ["lisp"]
    },
    {
      "id": 3,
      "title": "HtDP",
      "price": 39.9,
      "tags": []
    }
  ]
}

Paths

A value deep in a tree is reached by a path: a list of keys for objects and indexes for arrays. The get-in procedure of the association lists article follows keys only; with vectors in the tree, a path also needs numbers.

paths.scm
(define shop (call-with-input-file "shop.dat" read))

(define (tree-ref tree path)
  (cond ((null? path) tree)
        ((and (integer? (car path)) (vector? tree))
         (and (< (car path) (vector-length tree))
              (tree-ref (vector-ref tree (car path)) (cdr path))))
        ((and (symbol? (car path)) (list? tree))
         (let ((entry (assq (car path) tree)))
           (and entry (tree-ref (cdr entry) (cdr path)))))
        (else #f)))

(write (tree-ref shop '(address city)))
(newline)
(write (tree-ref shop '(staff 1)))
(newline)
(write (tree-ref shop '(products 0 title)))
(newline)
(write (tree-ref shop '(products 0 tags 1)))
(newline)
(write (tree-ref shop '(products 5 title)))
(newline)
(write (tree-ref shop '(name 0)))
(newline)
(write (tree-ref shop '(rating)))
(newline)

tree-ref takes the first step of the path and continues with the rest. A number selects an element of a vector after a range check, and a symbol selects a field of an object. A step that does not fit the data, such as an index into a string or a missing product, returns #f. The rating exists and is null, which is different from a missing field. Because #f means "not found", a field whose value is false cannot be told apart from a missing one; a procedure that needs that distinction would take a default value, as plist-ref does.

$ guile paths.scm
"Bratislava"
"Peter"
"SICP"
"classic"
#f
#f
null

Walking the tree

Some questions concern the whole tree rather than one path: all values of a key wherever it appears, the number of values, or the depth of nesting. They all follow the same recursion: handle the current node, then process its children.

walk.scm
(define shop (call-with-input-file "shop.dat" read))

(define (object? x)
  (and (list? x) (or (null? x) (pair? (car x)))))

(define (children tree)
  (cond ((vector? tree) (vector->list tree))
        ((object? tree) (map cdr tree))
        (else '())))

(define (find-all key tree)
  (let ((here (if (object? tree)
                  (let ((entry (assq key tree)))
                    (if entry (list (cdr entry)) '()))
                  '())))
    (append here
            (apply append (map (lambda (child) (find-all key child))
                               (children tree))))))

(define (count-leaves tree)
  (let ((kids (children tree)))
    (if (and (null? kids) (not (vector? tree)) (not (object? tree)))
        1
        (apply + (map count-leaves kids)))))

(define (depth tree)
  (let ((kids (children tree)))
    (if (null? kids)
        0
        (+ 1 (apply max (map depth kids))))))

(write (find-all 'title shop))
(newline)
(write (find-all 'city shop))
(newline)
(write (apply + (find-all 'price shop)))
(newline)
(write (count-leaves shop))
(newline)
(write (depth shop))
(newline)

object? recognises an association list: a list whose first element is a pair, or the empty list. children returns the elements of a vector or the values of an object; other values have no children. find-all collects the value of the key in the current node, if any, and appends the results from all children. count-leaves counts the strings, numbers, booleans, and nulls; an empty array or object adds nothing. depth counts the levels of objects and arrays down to the deepest value: shop, products, product, tags.

$ guile walk.scm
("SICP" "The Little Schemer" "HtDP")
("Bratislava")
117.4
19
4

Updating and saving

Changing a nested value without modifying the original tree means copying only the nodes on the path to it. Everything else is shared between the old and the new tree. The result can then be written to a file with write and read back with read.

update.scm
(use-modules (json-writer))

(define shop (call-with-input-file "shop.dat" read))

(define (tree-update tree path change)
  (cond ((null? path) (change tree))
        ((vector? tree)
         (let ((copy (vector-copy tree)))
           (vector-set! copy (car path)
                        (tree-update (vector-ref tree (car path)) (cdr path) change))
           copy))
        (else
         (map (lambda (entry)
                (if (eq? (car entry) (car path))
                    (cons (car entry) (tree-update (cdr entry) (cdr path) change))
                    entry))
              tree))))

(define (discount price)
  (/ (round (* price 90)) 100))

(define sale (tree-update shop '(products 1 price) discount))
(define renamed (tree-update sale '(address street) (lambda (s) "Hlavna 5")))

(write-json (vector-ref (cdr (assq 'products renamed)) 1) (current-output-port))
(write (list (cdr (assq 'street (cdr (assq 'address shop))))
             (cdr (assq 'street (cdr (assq 'address renamed))))))
(newline)
(write (eq? (assq 'staff shop) (assq 'staff renamed)))
(newline)

(call-with-output-file "shop-sale.dat"
  (lambda (port) (write renamed port)))
(write (equal? renamed (call-with-input-file "shop-sale.dat" read)))
(newline)

tree-update applies a procedure to the value at the end of a path. Along the way, it copies a vector with vector-copy before it replaces one element, and it maps over an object to rebuild only the entry with the matching key. A key that does not exist leaves the object as it was. The program lowers the price of the second product by ten percent, rounded to cents, and renames the street. The original shop still has the old street, while the unchanged staff entry is the same object, eq?, in both trees. Finally, the new tree is written to shop-sale.dat, and reading it back gives an equal? tree.

$ guile -L . update.scm
{
  "id": 2,
  "title": "The Little Schemer",
  "price": 28.8,
  "tags": ["lisp"]
}
("Obchodna 12" "Hlavna 5")
#t
#t

Source

Association Lists — GNU Guile Reference Manual

Introducing JSON

In this article we have stored rows as lists, property lists, and association lists, queried them with where and select, joined two tables, represented JSON documents with alists and vectors, written them as JSON, followed paths into a tree, walked the whole tree, and updated it without mutation before saving it. The pattern matching article takes such data apart with match, and the quasiquote article builds it from templates.

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.