From 90fa195dc5376873f953b188bb6fbc46e26e40f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Pant=C5=AF=C4=8Dek?= Date: Sun, 9 Apr 2023 20:00:17 +0200 Subject: [PATCH] Reimplement and document ldict-filter. --- doc/utils.md | 9 +++++++++ src/util-dict.scm | 20 +++++++++++--------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/doc/utils.md b/doc/utils.md index 941d191..434450d 100644 --- a/doc/utils.md +++ b/doc/utils.md @@ -112,6 +112,15 @@ if it accepts three arguments, the key, value and numeric index In all cases the value the procedure returns is taken as the new value for given key. + (ldict-filter pred? ld) + +* ```pred?``` - predicate procedure +* ```ld``` -a ldict instance + +Returns a new dictionary containing only key/value pairs matching the +given predicate. The procedure ```pred?``` must accept two arguments - +the key and the value. + ### IO (import util-io) diff --git a/src/util-dict.scm b/src/util-dict.scm index e2ab419..c8740c9 100644 --- a/src/util-dict.scm +++ b/src/util-dict.scm @@ -179,15 +179,17 @@ ;; 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))))) + (define (ldict-filter pred? ld) + (let loop ((pairs (ldict-pairs ld)) + (res '())) + (if (null? pairs) + (cons TAG-LDICT + (cons (ldict-meta ld) + res)) + (loop (cdr pairs) + (if (pred? (caar pairs) (cdar pairs)) + (cons (car pairs) res) + res))))) ;; Reduce over dictinary, the reducing procedure gets accumulator, ;; key and value as its three arguments.