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: David Mentre <David.Mentre@i...>
Subject: Re: [Caml-list] where is my count: newbie's question
Francois Thomasset <Francois.Thomasset@inria.fr> writes:

> # 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.

It works. In your case, your are not using the proper returned function
by the body of fnx:

# let g = fnx 3 ;;
val f : unit -> int = <fun>
# g ();;
x = 3
count = 0
- : int = 1
# g ();;
x = 3
count = 1
- : int = 2

Said otherwise, you do not create the function 'f' (let f()=...) inside
the body of fnx until you provide the first int argument. At that time,
a new function corresponding to f is returned, with a new count set to
zero. 

> Of course if I remove the int argument I retrieve the behavior I expected:
> # let fnx = let count = ref 0 in
>   let f() =
>   Printf.printf "count = %d\n" !count;
>   count := !count + 1; !count
>   in f;;
> val fnx : unit -> int = <fun>

In that case, the *variable* fnx is assigned the function f, created
immediately.



-- 
 David.Mentre@inria.fr -- http://www.irisa.fr/prive/dmentre/
 Opinions expressed here are only mine.
-------------------
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