s c h e m a t i c s : c o o k b o o k

/ Cookbook.HashCopy

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Copying The Contents of a Hash Table

Problem

You want to copy the contents of a hash table from one hash table to another, preserving both keys and values.

Solution

Using the recipe given in HashRecipeTraverse hash-table-copy! iterates over the source hash, copying all keys and values to the target hash:

;; hash-table-copy! : hash-table hash-table -> void
(define (hash-table-copy! source target)
  (hash-table-for-each
    source
    (lambda (key value)
      (hash-table-put! target key value))))

Discussion

An example usage, using write-hash-table from HashReadAndWrite, is:

> (define new-hash-table (make-hash-table))
> (hash-table-copy! 
    (make-immutable-hash-table '((a . 1) (b . 2)))
    new-hash-table)
> (write-hash-table new-hash-table (current-output-port))
#hasheq((b . 2) (a . 1))

Any existing values in the target hash table will be overwritten.

This function is useful to convert an immutable hash (for example, one read by HashReadAndWrite) to a mutable hash.


Comments about this recipe

Contributors

-- NoelWelsh - 17 Sep 2004

CookbookForm
TopicType: Recipe
ParentTopic: HashRecipes
TopicOrder: 999

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest