Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] const equivalent for mutable types?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jean-Marie Gaillourdert <jmg@g...>
Subject: Re: [Caml-list] const equivalent for mutable types?
Hi,

Am Samstag, 31. Juli 2004 10:56 schrieb Christopher A. Gorski:
> In my code I find that I'm passing a lot of mutable values to functions.
>   Some functions merely read the values.  Others modify the values.  Is
> there a method in OCaml for reproducing behavior similar in spirit to
> the const declaration in C?

In a purely functional language every parameter is "const". Although OCaml is 
not pure this behaviour is still the default. 

> Here is a specific case of the general problem:
>
> let t=ref 0
> let change r = incr r
> let nochange r = Printf.printf "test:%d\n" !r
>
> The problem is that in complex programs I often get confused over what
> functions are modifying values and what functions are not.  I feel like
> I should be able to do something like
>
> let result = change (const r)
>
> and have the compiler give me a type error.
>
> Is there a way to do this in OCaml?  Should I change my programming
> style?  Am I asking a naive question that's already been answered many
> times over in a different form?

There is a very simple way to do so: Just don't pass the references around.

let t=ref 0
let change r = incr r
let nochange r = Printf.printf "test:%d\n" r

You can now distinguish "const" parameters from "non-const" parameters.

change t
nochange !t 


Regards,
 Jean-Marie Gaillourdet

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