Implement new ldict-set procedure.

This commit is contained in:
Dominik Pantůček 2023-04-09 19:45:40 +02:00
parent a80b216bbc
commit ac1c5d28c6
2 changed files with 23 additions and 11 deletions

View file

@ -81,6 +81,15 @@ of missing key.
Returns a new dictionary with the record under given key removed. If Returns a new dictionary with the record under given key removed. If
the dictionary does not contain the key ```k```, an error is raised. the dictionary does not contain the key ```k```, an error is raised.
(ldict-set ld k v)
* ```ld``` - a ldict instance
* ```k``` - a compatible key
* ```v``` - a value to insert
Sets existing key ```k``` to the new value ```v``` or inserts it if it
is not already present in the dictionary ```ld```.
### IO ### IO
(import util-io) (import util-io)

View file

@ -110,7 +110,7 @@
;; Returns a new dictionary based on d with key k removed. If it ;; Returns a new dictionary based on d with key k removed. If it
;; doesn't contain the key, an error is raised. ;; doesn't contain the key, an error is raised.
(define (dict-remove ld k) (define (ldict-remove ld k)
(let ((equality? (ldict-equality? ld))) (let ((equality? (ldict-equality? ld)))
(let loop ((pairs (ldict-pairs ld)) (let loop ((pairs (ldict-pairs ld))
(res '()) (res '())
@ -129,16 +129,19 @@
;; Adds a new value v under the key k to the dictionary d possibly ;; Adds a new value v under the key k to the dictionary d possibly
;; overwriting any value which has been stored under the key ;; overwriting any value which has been stored under the key
;; before. Returns the updated dictionary. ;; before. Returns the updated dictionary.
(define (dict-set d k v) (define (ldict-set ld k v)
(let ((dr (let loop ((s d) (let ((equality? (ldict-equalit? ld)))
(r '())) (let loop ((pairs (ldict-pairs ld))
(if (null? s) (res '()))
r (if (null? pairs)
(if (eq? (caar s) k) (cons TAG-LDICT
(loop (cdr s) r) (cons (ldict-meta ld)
(loop (cdr s) (cons (car s) r)))))))
(cons (cons k v) (cons (cons k v)
dr))) res)))
(loop (cdr pairs)
(if (equality? (caar pairs) k)
res
(cons (car pairs) res)))))))
;; Returns the list of keys stored in given dictionary. ;; Returns the list of keys stored in given dictionary.
(define (dict-keys d) (define (dict-keys d)