This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] surprising program
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2001-10-24 (05:21) From: Alan Schmitt Subject: Re: [Caml-list] surprising program
```Hi,

This is an evaluation order problem. In OCaml, the evaluation order is
not specified (there is such an order but one shouldn't take it into
account, as it may change some day), and when you write:
{t with p1= !n }::numero f
there is no guarantee that the record is created before the recursive
call (and what actually happens is the recursive call, the creation of
the record, and the consing of the record on the list). Since recursive
calls are done first, n gets its final value before the records are
created, and they all have the same p1. In the second example, you use:
let a = !n' in {t with p1= a }::numero' f
so you force the evaluation of 'a' before the recursive call, which is
the Right Way (tm).

HTH,

Alan

* Michel Levy (Michel.Levy@imag.fr) wrote:
> I don't understand the behavior of the following program (ocaml 3.01)
>
> type couple = {p1 :int ;p2:int};;
> let c1 = {p1=0;p2=10};;
> let c2 = {p1=0;p2 = 20};;
>
> let n = ref 0;;
> let rec numero l =
>   match l with
>     | [] -> []
>     | t::f ->n:=!n+1; {t with p1= !n }::numero f;;
>
> (*
> # numero [c1;c2];;
> - : couple list = [{p1=2; p2=10}; {p1=2; p2=20}]
> *)
>
> Why the fied p1 has the value 2 ?
> Why it's different with the fonction numero'
>
> let n' = ref 0;;
> let rec numero' l =
>   match l with
>     | [] -> []
>     | t::f -> n':=!n'+1;
> 	let a = !n' in {t with p1= a }::numero' f;;
> (*
> # numero' [c1;c2];;
> - : couple list = [{p1=1; p2=10}; {p1=2; p2=20}]
> *)
>
> Thank you really much for any explanation.
>
> --
> Michel Levy
> 36 rue George Sand 38400 Saint Martin d'Hères
> email : Michel.Levy@imag.fr
> http://www-lsr.imag.fr/users/Michel.Levy/
> -------------------
> 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

--
The hacker: someone who figured things out and made something cool happen.
-------------------
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

```