[
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: | Gerd Stolpmann <gerd@g...> |
| Subject: | Re: "pointers" to methods |
On Tue, 06 Feb 2001, Mattias Waldau wrote:
>In the following code I would like to apply the method inc or dec to the
>object obj. However, what is the syntax I should use? At all comments below
>the compilation fails.
You can use partially evaluated method calls as pointers to methods. However,
this works only for methods with at least one argument:
let main() =
let obj = new class1 in
let method_to_call =
if Random.int 2 = 0 then
obj # inc
else
obj # dec
in
method_to_call 2;
obj # get()
;;
For methods without arguments, one has to explicitly create a function
representing the pointer. If inc and dec had no argument:
let main() =
let obj = new class1 in
let method_to_call =
if Random.int 2 = 0 then
(fun () -> obj # inc)
else
(fun () -> obj # dec)
in
method_to_call ();
obj # get()
;;
>class class1 =
> object (self)
> val mutable x = 1
> method inc step = x <- x+step
> method dec step = x <- x+step
> method get () = x
> end
>
>let main () =
> let method_to_call =
> if Random.int 2 = 0 then
> inc (* pointer to inc-method in class1 *)
> else
> dec (* pointer to dec-method in class1 *)
> in
> let obj = new class1 in
> obj#method_to_call 2; (* apply pointer to method in class1 *)
> obj#get ()
>
Gerd
--
----------------------------------------------------------------------------
Gerd Stolpmann Telefon: +49 6151 997705 (privat)
Viktoriastr. 100
64293 Darmstadt EMail: gerd@gerd-stolpmann.de
Germany
----------------------------------------------------------------------------