From: Vincent Cheval <vincheval@wanadoo.fr>
> I have a question about Object in Ocaml. I wonder if it's possible
> to create static function in the definition of a object in
> Ocaml. Here is a small exemple :
>
> Assume that you have this class definition:
>
> #class test (n:int) =
> # object
> # val x = n
> # method get_x = x
> # end;;
> #
> #let equal (t_1:test) (t_2:test) = t_1#x = t_2#x;;
>
> This class and the function are well defined but I would like not to
> use the method "get_x" and define my class like that :
>
> #class test (n:int) =
> # object
> # val x = n
> # method equal (t_1:test) (t_2:test) = t_1#x = t_2#x
> # end;;
>
> If we were on Java or C++, i should use Static in front of the
> declaration of "equal". So my question is : Is it possible to do the
> same thing in OCaml ?
Actually, a static method is not really a method, but just a way to
use classes as modules. OCaml already as modules independently of
classes, so this is not relevant: just use a normal function outside
of the class.
Looking more carefully about your 2nd example, it happens to be
impossible to encode it directly in ocaml, but for a different reason:
there is no way to access fields directly from outside an object. So
if you write a function outside of the class, it will not be able to
use x. The standard way to define such functions without exposing the
value of x is to add a method get_x, but give the returned value an
abstract type:
module Test : sig
type x_t
class test : int ->
object
method get_x : x_t
method print : unit
end
val equal : test -> test -> bool
end = struct
type x_t = int
class test (n : int) =
object
val x = n
method get_x = x
method print = print_int x
end
let equal t1 t2 = t1#get_x = t2#get_x
end
(I added another method, because using an object without any method is
not meaningful)
Another approach, if you don't want to inherit from test, it to use
private row variables:
module Test : sig
type test = private < print : unit; .. >
val create : int -> test
val equal : test -> test -> bool
end = struct
class test (n : int) =
object
val x = n
method get_x = x
method print = print_int x
end
let create = new test
let equal t1 t2 = t1#get_x = t2#get_x
end
Jacques Garrigue