JavaScript has really elegant syntaxes to manipulate dictionaries.
Dictionary creation:
Given:
let x = 42;
{a: 1 + 2, b: 3, ['a' + 'b']: 4, x} is a dictionary with four entries:
'a' maps to 3;
'b' maps to 3;
'ab' maps to 4; and
'x' maps to 42
Merging
Other dictionaries can also be merged as a part of dictionary creation.
Given:
let a = {a: 1, c: 2};
let b = {b: 2, c: 3};
Then {b: 42, ...a, ...b, a: 4, d: 5} has four entries:
'a' maps to 4;
'b' maps to 2;
'c' maps to 3; and
'd' maps to 5
Note that object merging can be used to set a value functionally without mutating the dictionary.
Extraction:
Given:
let x = {a: 1, b: 2, c: 3, d: 4};
let {a, b: bp} = x; binds a to 1 and bp to 2.
Extraction of the rest
As a part of extraction, there can be at most one ..., which will function as the extraction of the rest
For example:
let {a, b: bp, ...y} = x; binds a to 1, bp to 2, y to {c: 3, d: 4}.
js-dict and js-extract macros
The js-dict and js-extract macros bring these operations to Racket, using immutable hash tables as the data structure. Additionally, the js-extract macro improves upon JS by supporting arbitrary match pattern.
Background
JavaScript has really elegant syntaxes to manipulate dictionaries.
Dictionary creation:
Given:
{a: 1 + 2, b: 3, ['a' + 'b']: 4, x}
is a dictionary with four entries:'a'
maps to3
;'b'
maps to3
;'ab'
maps to4
; and'x'
maps to42
Merging
Other dictionaries can also be merged as a part of dictionary creation.
Given:
Then
{b: 42, ...a, ...b, a: 4, d: 5}
has four entries:'a'
maps to4
;'b'
maps to2
;'c'
maps to3
; and'd'
maps to5
Note that object merging can be used to set a value functionally without mutating the dictionary.
Extraction:
Given:
let {a, b: bp} = x;
bindsa
to1
andbp
to2
.Extraction of the rest
As a part of extraction, there can be at most one
...
, which will function as the extraction of the restFor example:
let {a, b: bp, ...y} = x;
bindsa
to1
,bp
to2
,y
to{c: 3, d: 4}
.js-dict and js-extract macros
The
js-dict
andjs-extract
macros bring these operations to Racket, using immutable hash tables as the data structure. Additionally, thejs-extract
macro improves upon JS by supporting arbitrary match pattern.js-dict
: dictionary creationThen
obj
should be'#hash((a . 40) (b . 2) (c . 3) (d . 4) (x . ((10))) (y . 30))
js-extract
: dictionary extractionWith the above
obj
, in the following code:f
should be equal40
c
should be equal3
d
should be equal4
x
should be equal10
rst
should be equal'#hash((b . 2) (y . 30))
Macro
Licence
MIT / CC-BY 4.0