Search code examples
listdictionaryracketbnfredex

How to create a dictionary mapping on custom dictionary in Racket?


I have defined dictionary as this judgment in BNF grammar:

d ::= () (any boolean) (list cons d d)

Meaning, dictionaries are empty, or (any boolean) or a list of such pairs.

If I want to create a mapping, say "a true", how do I do it?

If I do

(define-values (d) (values '(a true)))

it just creates a new d, doesn't map to previous judgment d defined.


Solution

  • IIUC you want your dictionary to be just an association list:

    (define d (list (cons 'x #t) (cons 'y #f)))
    

    Depending on how are you going to implement the add operation you could either set! a new mapping:

    (set! d (cons (cons 'z #t) d))
    

    Or just create a new list (preferred):

    (define d (list (cons 'z #t) (cons 'x #t) (cons 'y #f)))
    

    Either way, the dictionary d will have the new mapping in the expected format:

    '((z . #t) (x . #t) (y . #f))