Implement and document new ldict-map.

This commit is contained in:
Dominik Pantůček 2023-04-09 19:55:22 +02:00
parent 5533a3256e
commit bd7421b626
2 changed files with 29 additions and 8 deletions

View file

@ -96,6 +96,22 @@ is not already present in the dictionary ```ld```.
Returns the list of keys stored in given dictionary. 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 ### IO
(import util-io) (import util-io)

View file

@ -41,10 +41,13 @@
ldict-set ldict-set
ldict-keys ldict-keys
ldict-map ldict-map
ldict-filter ldict-filter
ldict-reduce ldict-reduce
ldict-update ldict-update
ldict-tests! ldict-tests!
) )
@ -151,18 +154,20 @@
;; Maps dictionary values, the procedure gets key-value pairs if it ;; Maps dictionary values, the procedure gets key-value pairs if it
;; accepts more than one argument. If it accepts a third argument, ;; accepts more than one argument. If it accepts a third argument,
;; index gets passed as well. ;; index gets passed as well.
(define (dict-map proc d) (define (ldict-map proc ld)
(let* ((lpi (length (procedure-information proc))) (let* ((lpi (length (procedure-information proc)))
(both? (> lpi 2)) (both? (> lpi 2))
(index? (> lpi 3))) (index? (> lpi 3)))
(let loop ((d d) (let loop ((pairs (ldict-pairs))
(r '()) (res '())
(i 0)) (i 0))
(if (null? d) (if (null? pairs)
r ; No reverse needed, order does not matter (cons TAG-LDICT
(loop (cdr d) (cons (ldict-meta ld)
(let ((k (caar d)) res))
(v (cdar d))) (loop (cdr pairs)
(let ((k (caar pairs))
(v (cdar pairs)))
(cons (cons k (if both? (cons (cons k (if both?
(if index? (if index?
(proc k v i) (proc k v i)