awwx.ws

table-rw3

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)
  scheme-t)

(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.

Examples

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)
       x)
{a 2}
arc> (w/outstring s (write {a (1 2 "foo" #\A . 3)} s) (inside s))
"{a (1 2 \"foo\" #\\A . 3)}"

Prerequisites

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

Get this hack

Using the hackinator:

$ hack \
    ycombinator.com/arc/arc3.1.tar \
    awwx.ws/defarc0.patch \
    awwx.ws/defarc-ac0.patch \
    awwx.ws/extend0.arc \
    awwx.ws/scheme0.arc \
    awwx.ws/defarc-literal0.patch \
    awwx.ws/arc-write0.patch \
    awwx.ws/between0.arc \
    awwx.ws/skipwhite1.arc \
    awwx.ws/extend-readtable0.arc \
    awwx.ws/table-rw3.arc

License

Same as Arc.

Changes

Compared to the previous version table-rw2:

Contact me

Twitter: awwx
Email: andrew.wilcox [at] gmail.com