Reimplement and document ldict-filter.

This commit is contained in:
Dominik Pantůček 2023-04-09 20:00:17 +02:00
parent bd7421b626
commit 90fa195dc5
2 changed files with 20 additions and 9 deletions

View file

@ -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 In all cases the value the procedure returns is taken as the new value
for given key. 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 ### IO
(import util-io) (import util-io)

View file

@ -179,15 +179,17 @@
;; Returns a dictionary containing only kv pairs matching the ;; Returns a dictionary containing only kv pairs matching the
;; predicate which must accept two arguments. Unlike list filter, ;; predicate which must accept two arguments. Unlike list filter,
;; does not perform final reverse on the result. ;; does not perform final reverse on the result.
(define (dict-filter pred? d) (define (ldict-filter pred? ld)
(let loop ((d d) (let loop ((pairs (ldict-pairs ld))
(r '())) (res '()))
(if (null? d) (if (null? pairs)
r (cons TAG-LDICT
(loop (cdr d) (cons (ldict-meta ld)
(if (pred? (caar d) (cdar d)) res))
(cons (car d) r) (loop (cdr pairs)
r))))) (if (pred? (caar pairs) (cdar pairs))
(cons (car pairs) res)
res)))))
;; Reduce over dictinary, the reducing procedure gets accumulator, ;; Reduce over dictinary, the reducing procedure gets accumulator,
;; key and value as its three arguments. ;; key and value as its three arguments.