Table reader / writer

(def parse-table-items (port (o acc (table)))
  (scheme.skip-whitespace port)
  (if (is (peekc port) #\})
       (do (readc port) acc)
       (with (k (read port)
              v (read port))
         (= (acc k) v)
         (parse-table-items port acc))))

(extend-readtable #\{ parse-table-items)

; need the errsafe on type tests because (type x) croaks on
; non-Arc types

(extend ac-literal (x) (errsafe:isa x 'table)

(def print-table (f x s)
  (scheme.display "{" s)
  (between (k v) x (scheme.display " " s)
    (write k s)
    (scheme.display " " s)
    (write v s))
  (scheme.display "}" s))
(def print-cdr (f x s)
  (if (no x)
       (scheme.display ")" s)
      (errsafe:acons x)
       (do (scheme.display " " s)
           (print f (car x) s)
         (print-cdr f (cdr x) s))
       (do (scheme.display " . " s)
           (print f x s)
         (scheme.display ")" s))))

(def print (f x s)
  (if (errsafe:acons x)
       (do (scheme.display "(" s)
           (print f (car x) s)
           (print-cdr f (cdr x) s))
      (errsafe:isa x 'table)
       (print-table f x s)
       (f x s))
  (unless scheme.explicit-flush (scheme.flush-output s)))

(def disp (x (o s (stdout)))
  (print scheme.display x s))

(def write (x (o s (stdout)))
  (print scheme.write x s))

This hack provides a minimal implementation which allows literal tables to be read and written.

Other features that would probably be useful (but I haven’t attempted to provide) is a way to construct a table from expressions and to include the table’s default value in its written form... though obj and friends has worked fine for me for constructing tables and I haven’t used the table default value feature myself.


arc> (obj a (list 1 2 (obj b 3) 4))
{a (1 2 {b 3} 4)}
arc> ({a (1 2 {b 3} 4)} 'a)
(1 2 {b 3} 4)
arc> (let x {a 1}
       (= x!a 2)
{a 2}
arc> (w/outstring s (write {a (1 2 "foo" #\A . 3)} s) (inside s))
"{a (1 2 \"foo\" #\\A . 3)}"


This hack depends on arc3.1, extend0, scheme0, defarc-literal0, arc-write0, between0, skipwhite1, and extend-readtable0.

Get this hack

Using the hackinator:

$ hack \ \ \ \ \ \ \ \ \ \ \


Same as Arc.


Compared to the previous version table-rw2:

Contact me

Twitter: awwx
Email: andrew.wilcox [at]