Version française
Home     About     Download     Resources     Contact us    
Browse thread
"pointers" to methods
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: John Prevost <jmp@a...>
Subject: Re: "pointers" to methods
>>>>> "mw" == Mattias Waldau <mattias.waldau@tacton.se> writes:


    mw> In the following code I would like to apply the method inc or
    mw> dec to the object obj. However, what is the syntax I should
    mw> use? At all comments below the compilation fails.

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

Try this

let main () = 
  let call_method =
    if Random.int 2 = 0 then
      fun x -> x #inc
    else
      fun x -> x #dec
  in
  let obj = new class1 in
  call_method obj 2;
  obj #get ()

You can't reference a method name explicitly, but you can create a
function that calls that method.  This is fairly equivalent.  If you
wanted the function to be more like a non-function value, just make it
opaque and add a "call_method" function.

John.