From bd7421b62694785044b734dd931be08217f6f93f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Pant=C5=AF=C4=8Dek?= Date: Sun, 9 Apr 2023 19:55:22 +0200 Subject: [PATCH] Implement and document new ldict-map. --- doc/utils.md | 16 ++++++++++++++++ src/util-dict.scm | 21 +++++++++++++-------- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/doc/utils.md b/doc/utils.md index de36bc6..941d191 100644 --- a/doc/utils.md +++ b/doc/utils.md @@ -96,6 +96,22 @@ is not already present in the dictionary ```ld```. Returns the list of keys stored in given dictionary. + (ldict-map proc ld) + +* ```proc``` - procedure accepting 1, 2 or 3 arguments +* ```ld``` - a ldict instance + +Returns a new dictionary of the same type with all values processed by +given procedure. + +If it accepts one argument, only the value is passed to it. If it +accepts two values, the key and the value is passed to it. And lastly +if it accepts three arguments, the key, value and numeric index +(starting from 0) are passed to it. + +In all cases the value the procedure returns is taken as the new value +for given key. + ### IO (import util-io) diff --git a/src/util-dict.scm b/src/util-dict.scm index e1e58eb..e2ab419 100644 --- a/src/util-dict.scm +++ b/src/util-dict.scm @@ -41,10 +41,13 @@ ldict-set ldict-keys + ldict-map ldict-filter ldict-reduce + ldict-update + ldict-tests! ) @@ -151,18 +154,20 @@ ;; Maps dictionary values, the procedure gets key-value pairs if it ;; accepts more than one argument. If it accepts a third argument, ;; index gets passed as well. - (define (dict-map proc d) + (define (ldict-map proc ld) (let* ((lpi (length (procedure-information proc))) (both? (> lpi 2)) (index? (> lpi 3))) - (let loop ((d d) - (r '()) + (let loop ((pairs (ldict-pairs)) + (res '()) (i 0)) - (if (null? d) - r ; No reverse needed, order does not matter - (loop (cdr d) - (let ((k (caar d)) - (v (cdar d))) + (if (null? pairs) + (cons TAG-LDICT + (cons (ldict-meta ld) + res)) + (loop (cdr pairs) + (let ((k (caar pairs)) + (v (cdar pairs))) (cons (cons k (if both? (if index? (proc k v i)