Browse thread
[Caml-list] static variables in a function
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Max Kirillov <max630@m...> |
| Subject: | Re: [Caml-list] static variables in a function |
Oh, thank you for clarification. I'm very new to functional
programming, and didn't know yet about tricks like this. As
I understand, the point was to call 'ref' at initialization
stage. I thought about using 'lazy' for that, but still
placed it inside a full function definition, so it didn't
help.
This makes a possibility to write very funny
functions. For example:
# let acc v =
let vR = ref v in
fun f ->
let newV = f !vR in
vR := newV;
newV ;;
val acc : 'a -> ('a -> 'a) -> 'a = <fun>
# let f1 = acc 12;;
val f1 : (int -> int) -> int = <fun>
# f1 ((+) 1);;
- : int = 13
# f1 ((+) 1);;
- : int = 14
# f1 ((+) 1);;
- : int = 15
# f1 ((+) 1);;
- : int = 16
# f1 ((+) 1);;
- : int = 17
# let f2 = acc "hello";;
val f2 : (string -> string) -> string = <fun>
# f2 ((^) " a");;
- : string = " ahello"
# f2 ((^) " b");;
- : string = " b ahello"
# f2 ((^) " c");;
- : string = " c b ahello"
I'm not sure if this style of coding better than placing the
mutable values to be hidden inside modules or classes. Even
when possible (in other languages), I prefer to use
latter way to do. Well it's a matter of taste.
Max.
On Sat, Jun 15, 2002 at 02:36:03AM -0400, John Prevost wrote:
>>>>>> "mk" == Max Kirillov <max630@mail.ru> writes:
>
>mk> Hello. The code you write will generate a new (empty) ref at
>mk> every call.
>
> Actually, it won't. Take a look at the code that was sent by Yutaka OIWA:
>
> let get_chunk =
> let chunks_list = ref [] in
> fun () ->
> ...
>
> The ref is bound outside of the function definition, so it's created
> once and kept in the closure, not allocated in each call.
<...>
> Your version also works, but creates a module-level binding for the
> value as well, which isn't desirable for something like this, where
> you want the value to be local to the function definition.
>
> John.
-------------------
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