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

/ Cookbook.HashReadAndWrite

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

Reading and Writing Hash Tables

Problem

You want to write a hash table to disk and at a later time read it back.

Solution

The functions write-hash-table and read-hash-table write and read a hash table to and from a port respectively.

;; write-hash-table: hash-table port -> void
(define (write-hash-table table port)
  (parameterize ((print-hash-table #t))
    (write table port)))

;; read-hash-table port -> (U hash-table #f)
(define (read-hash-table port)
  (let ((data (read port)))
    (if (hash-table? data)
        data
        #f)))

Note that read-hash-table returns #f if the data it reads from the port is not a hash-table. As a side-effect the data read is thrown away. If you don't want this data to be thrown away simply call read on the port, as read-hash-table is just a wrapper around read.

Discussion

Example usage:

> (define port (open-output-string))
> (write-hash-table 
    (make-immutable-hash-table '((a . 1) (b . 2)))
    port)
> (get-output-string port)
"#hasheq((b . 2) (a . 1))"
> (read-hash-table (open-input-string (get-output-string port)))
#<hash-table>

PltScheme includes built-in support for writing and reading hash tables. However there are some caveats:


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