Implement ldict-remove procedure.

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

View file

@ -73,6 +73,14 @@ the dictionary does not contain it and no default is given, an
exception is raised. Otherwise the default value is returned in case exception is raised. Otherwise the default value is returned in case
of missing key. of missing key.
(ldict-remove ld k)
* ```ld``` - a ldict instance
* ```k``` - a compatible key
Returns a new dictionary with the record under given key removed. If
the dictionary does not contain the key ```k```, an error is raised.
### IO ### IO
(import util-io) (import util-io)

View file

@ -110,17 +110,21 @@
;; 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 d k) (define (dict-remove ld k)
(let loop ((s d) (let ((equality? (ldict-equality? ld)))
(r '()) (let loop ((pairs (ldict-pairs ld))
(e #t)) (res '())
(if (null? s) (failure #t))
(if e (if (null? pairs)
(if failure
(error 'dict-remove "Key does not exist" k) (error 'dict-remove "Key does not exist" k)
r) (cons TAG-LDICT
(if (eq? (caar s) k) (cons (ldict-meta ld)
(loop (cdr s) r #f) res)))
(loop (cdr s) (cons (car s) r) e))))) (loop (cdr pairs)
(if (equality? (caar pairs) k)
res
(cons (car pairs) res)))))))
;; 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