Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] static variables in a function
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Remi VANICAT <vanicat@l...>
Subject: Re: [Caml-list] static variables in a function
Max Kirillov <max630@mail.ru> writes:

> On Sat, Jun 15, 2002 at 12:14:09PM -0400, John Prevost wrote:
> <...>
>> If we change our focus, howeverm the technique becomes more
>> interesting.  Take a look at this, for example:
> <...>
>> let memoize f =
>
> Hmm... this isn't executed at read time because function has
> a parameter...

this code :
let memoize f =
  let stow = Hashtbl.create 20 in
  fun x -> begin
    if not (Hashtbl.mem stow x) then begin
      try (let v = f x in Hashtbl.replace stow x (Val v))
        with e -> Hashtbl.replace stow x (Exn e)
     end;
    match Hashtbl.find stow x with
      | Val x -> x
      | Exn e -> raise e
  end

was correct :
it create a new Hastable for each different function one want to
memoize. Otherwise the hastable will be shared between different
function, what we realy don't want.

look at this for a proof of what I'm saying :

# let print_once = memoize print_endline;;
val print_once : string -> unit = <fun>
# print_once "foo";;
foo
- : unit = ()
# print_once "bar";;
bar
- : unit = ()
# print_once "bar";;
- : unit = ()
# 

the last time, the value isn't recompile (and then nothing is
printed), so the memoization have worked.


-- 
Rémi Vanicat
vanicat@labri.u-bordeaux.fr
http://dept-info.labri.u-bordeaux.fr/~vanicat
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners