Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] where is my count: newbie's question
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Markus Mottl <mottl@m...>
Subject: Re: [Caml-list] where is my count: newbie's question
On Mon, 11 Jun 2001, Francois Thomasset wrote:
> # let fnx(x) = let count = ref 0 in         
>   let f() =                                 
>   Printf.printf "x = %d\n" x;
>   Printf.printf "count = %d\n" !count;
>   count := !count + 1; !count
>   in f;;
> val fnx : int -> unit -> int = <fun>
> I would have expected that count remembers its previous value, which would be 
> incremented at each call, but this is not true : !count is always 0.
> Of course if I remove the int argument I retrieve the behavior I expected:

The reason is that "ref 0" is a function, which always creates a
"fresh" reference cell everytime it is called. If you want to use the
same reference always, you have to either make it a global variable,
or you have to define it as such:

  let f =
    let count = ref 0 in
    fun x ->
      Printf.printf ...

Of course, this also works (more similar to your example):

  let f =
    let count = ref 0 in
    let f x =
      Printf.printf ...
    in
    f

Regards,
Markus Mottl

-- 
Markus Mottl, mottl@miss.wu-wien.ac.at, http://miss.wu-wien.ac.at/~mottl
-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr