Implement dict-map.

This commit is contained in:
Dominik Pantůček 2023-03-16 10:22:50 +01:00
parent 6e614feab3
commit 33f02bd329
3 changed files with 31 additions and 3 deletions

View file

@ -91,6 +91,17 @@
(define (dict-keys d)
(map car d))
;; Maps dictionary values, the procedure gets key-value pairs if it
;; accepts more than one argument.
(define (dict-map proc d)
(let ((both? (> (length (procedure-information proc)) 2)))
(map
(lambda (kv)
(let ((k (car kv))
(v (cdr kv)))
(cons k (if both? (proc k v) (proc v)))))
d)))
;; Performs self-tests of the dictionary module.
(define (dictionary-tests!)
(run-tests
@ -103,6 +114,16 @@
(test-exn dict-remove (dict-remove (make-dict) 'nonexistent))
(test-true dict-remove (null? (dict-remove (dict-set (make-dict) 'existing 1) 'existing)))
(test-equal? dict-keys (dict-keys (dict-set (make-dict) 'existing 1)) '(existing))
(test-equal? dict-map (dict-map (lambda (v) (* 2 v))
'((a . 1)
(b . 2)))
'((a . 2)
(b . 4)))
(test-equal? dict-map (dict-map (lambda (k v) (* 2 v))
'((a . 1)
(b . 2)))
'((a . 2)
(b . 4)))
))
)