Implement ldict-ref.

This commit is contained in:
Dominik Pantůček 2023-04-09 19:34:27 +02:00
parent a5ed5bca53
commit 1df2792838
2 changed files with 21 additions and 7 deletions

View file

@ -62,6 +62,17 @@ Returns ```#t``` if given dictionary contains no keys.
Returns ```#t``` if given ```ld``` contains given key ```k```.
(ldict-ref ld k [default])
* ```ld``` - a ldict instance
* ```k``` - a compatible key
* ```default``` - optional fallback value
Retrieves the value associated with given key in given dictionary. If
the dictionary does not contain it and no default is given, an
exception is raised. Otherwise the default value is returned in case
of missing key.
### IO
(import util-io)

View file

@ -97,13 +97,16 @@
;; is provided it is used as default value in case the key does not
;; exist. If only two arguments are given and the key does not exist,
;; raises an error.
(define (dict-ref d k . r)
(let ((p (assq k d)))
(if p
(cdr p)
(if (null? r)
(error 'dict-ref "Key does not exist" k)
(car r)))))
(define (ldict-ref ld k . ds)
(let ((equality? (ldict-equality? ld)))
(let loop ((pairs (ldict-pairs ld)))
(if (null? pairs)
(if (null? ds)
(error 'ldict-ref "Key does not exist" k)
(car ds))
(if (equality? (caar pairs) k)
(cdar pairs)
(loop (cdr pairs)))))))
;; Returns a new dictionary based on d with key k removed. If it
;; doesn't contain the key, an error is raised.