From 165794f317034995c41735f1cecd6ff4ecb3d747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Pant=C5=AF=C4=8Dek?= Date: Thu, 16 Mar 2023 10:34:08 +0100 Subject: [PATCH] Implement dict-filter. --- dictionary.scm | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/dictionary.scm b/dictionary.scm index 93dcb20..f6672f6 100644 --- a/dictionary.scm +++ b/dictionary.scm @@ -32,6 +32,8 @@ dict-has-key? dict-ref dict-remove dict-set dict-keys + dict-map + dict-filter dictionary-tests! ) @@ -102,6 +104,19 @@ (cons k (if both? (proc k v) (proc v))))) d))) + ;; Returns a dictionary containing only kv pairs matching the + ;; predicate which must accept two arguments. Unlike list filter, + ;; does not perform final reverse on the result. + (define (dict-filter pred? d) + (let loop ((d d) + (r '())) + (if (null? d) + r + (loop (cdr d) + (if (pred? (caar d) (cdar d)) + (cons (car d) r) + r))))) + ;; Performs self-tests of the dictionary module. (define (dictionary-tests!) (run-tests @@ -124,6 +139,11 @@ (b . 2))) '((a . 2) (b . 4))) + (test-equal? dict-filter (dict-filter (lambda (k v) + (odd? v)) + '((a . 1) + (b . 2))) + '((a . 1))) )) )