Version franaise
Home About Download Resources Contact us
Browse thread
The Implicit Accumulator: a design pattern using optional arguments
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Pierre Etchemat <petchema@c...>
Subject: Re: [Caml-list] The Implicit Accumulator: a design pattern using optional arguments
Le Wed, 27 Jun 2007 14:53:05 +0100, Jon Harrop <jon@ffconsultancy.com> a crit :

> 
> # let symbol =
>     let m = Hashtbl.create 1 in
>     fun string ->
>       try Hashtbl.find m string with Not_found ->
>       Hashtbl.add m string string;
>       string;;
> val symbol : '_a -> '_a = <fun>

The usual way to do this in OCaml is using a weak hashtable. Benefit is
that the strings can still be collected when not longer used. Weak
hashtables also have a "merge" function that do exactly what we want:

module H = Weak.Make(struct
        type t = string
        let hash = Hashtbl.hash
        let equal (x:t) y = x = y
      end)

let symbol =
  let symbols = H.create 13 in
  H.merge symbols