[plt-scheme] Dict Merge

From: Paulo J. Matos (pocmatos at gmail.com)
Date: Sun Jun 7 12:53:33 EDT 2009

Hi all,

Since I didn't find a portable way (among dict types) to merge several
dicts I devised one (which assumes that no dicts have the same key):

;; dict-merge : dict? ..1
;; Receives a list of dictionaries and merges them into a single dictionary.
;; The resulting dictionary is of the same time of the first
dictionary and assumes that the set of keys of each dict are disjoint.
(define dict-merge
  (case-lambda [(dict) dict]
               [(dict1 dict2)
                (let loop ([res dict1] [next (dict-iterate-first dict2)])
                  (if next
                      (loop (dict-set res (dict-iterate-key dict2
next) (dict-iterate-value dict2 next))
                            (dict-iterate-next dict2 next))
                      res))]
               [(dict . dicts)
                (foldl (lambda (el acum) (dict-merge acum el))
                       dict
                       dicts)]))

> (dict-merge #hash((b . "banana") (a . "apple")) #hash((c . "cider") (p . "pizza")))
#hash((b . "banana")
      (a . "apple")
      (c . "cider")
      (p . "pizza"))
> (dict-merge #hash((b . "banana") (a . "apple")) '((c . "cider") (p . "pizza")))
#hash((b . "banana")
      (a . "apple")
      (c . "cider")
      (p . "pizza"))

Is this a good way to do it or can you improve on it? (moreover, why
is there no such thing already in the library? it would be interesting
to add one)

Cheers,
-- 
Paulo Jorge Matos - pocmatos at gmail.com
http://www.pmatos.net


Posted on the users mailing list.