English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Re: Constructor/reference bug?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 1999-08-12 (14:42)
From: Damien Doligez <Damien.Doligez@i...>
Subject: Re: Constructor/reference bug?
>From: John Skaller <skaller@maxtal.com.au>

>let g x = 
>let lineno = ref (1,"") in
>let rec f x' = match x' with
>| NEWLINE p :: t -> lineno := p; f t
>| COLON :: t     -> CTRL !lineno :: f t
>| h :: t -> h :: f t
>| [] -> []
>in f x;;
>The code doesn't work as I expected: every
>CTRL value refers to the same lineno, the last one.
>If I change the COLON line to read:
>| COLON :: t -> let x = !lineno in CTRL x :: f t
>the code works as expected -- the CTRL refers to the
>value of lineno at the time the last NEWLINE was processed.
>What's happening? Are coproduct constructors lazy?

You have to be careful because f is a function with side effects.

In the line

    | COLON :: t     -> CTRL !lineno :: f t

the subexpression "!lineno" is not guaranteed to be evaluated before
"f t".  The current implementation happens to evaluate "f t" first.
Using "let x = !lineno in ..." is the right way to write your

-- Damien