File under: development, plt, racket, scheme
SPATH
Easy access to Racket nested data structures
spath for PLT racket
Turns this
(hashref (hashref (hashref h key1) key2 ) key3 )
into this
(spath '( key1 key2 key3 ) h)
Examples
[spath
'[1 "bananas"] ; Extract the 1th (second) element of the list, then do a hash lookup for the word "bananas"
'[ "c" [ [apples . "yes"] ["bananas" "no"] ]]]
-> '("no")
and using an example from the manual:
(struct posn (x y [z #:auto]) #:auto-value 0 #:transparent)
(let ((position [posn 1 '[a b c]]]))
(s= y/1 position))
-> 'b
Spath gives you easy (read) access to nested data structures, similar to
other popular scripting languages. Spath can currently handle nested
vectors, lists, assoc lists, hashes and records. Hopefully objects will be
added soon too.
This is handy when dealing with large datastructures, usually
generated by someone else. So for instance, you can import a JSON data structure,
and then use spath to find and (coming soon) modify
parts of the document using native scheme functions.
There are several different functions provided for your convenient,
starting with the basic spath
(spath '( key1 key2 key3 ) data-structure)
spath will recurse through the data structure, using each element from
'( key1 key2 key3 ) list as a key to access each level of the nested data structure. spath does not catch errors,
so any "key not found" or "array index out of bounds" errors will bubble
up to the calling function.
(s= key1/key2/key3 data-structure )
s= works similar to spath, but uses sloppy matching for the keys. Unlike spath,
s= accepts keys separated by the '/' character, similar to the way directory
paths work. So/you/can/write/keys/like/this. = breaks the keys up, then tries
each one first as a number (if possible), then as a string, then as a symbol.
The first key that works is the one used.
(=l key1/key2/key3 data-structure thunk )
=l works like s=, but if the key cannot be found, the thunk will run, and its
result will be returned.
(=f data/path data-structure value )
=f works just like =l, but if the key is not found, the default value is returned.
Caveats
Racket currently seems to check only the first element of a list to see if it is
a cons-list. This means that a list that has a pair for its first element may
be mistaken for a cons-list, and then assoc will be used to look up the list index as
if it were an assoc key. There is currently no way of forcing a list index in
this circumstance, so you'll have to extract the element yourself.
Status
Incomplete - needs hash setters
Download
spath for PLT racket