views:

213

answers:

2

I would like to create an object with a data member using OCaml but do not necessarily want to specify an initial value for the data member. Many examples seem to use a list but I would like to use a single instance of an object type I've created. Is this possible? Thanks.

class bar = object end;;

class foo =
object (self)
val myDataMember = ((* ??? *) : bar)
end;;

Additionally, I've tried the option keyword to no avail:

class bar = 
object (self) 
    method doIt = Printf.printf "Doing it!"
end;;

class foo bar =
object (self)
  val mutable myDataMember = (None : bar option)
  method get = myDataMember
end;;

let f = new foo (new bar);;
f#get#bar#doIt;;

Here, the compiler complains about the data member having "bar option" type when I wished to specify it to have bar type.

+2  A: 

You have to use optional type:

class foo =
object (self)
val myDataMember = (None : bar option)
end;;

of course, for this to be usable you will probably have to use mutable:

class foo =
object (self)
  val mutable myDataMember = (None : bar option)
  method set t = myDataMember <- (Some t)
  method get () =
    match myDataMember with
    Some x -> x
    None -> failwith "not initialized"
end;;
Rémi
I seem to have trouble with the result when using the option keyword. I've updated the original post. Please help. Thanks so far.
Mat
A: 

f#get#bar#doIt;;

Here, the compiler complains about the data member having "bar option" type when I wished to specify it to have bar type.

In response to your new question. You didn't specify it to be of type bar, you specified it to be of bar option (exactly when you typed (None : bar option)). To access this you need to match --this might be better in the get method, but the point is valid.

match f#get#bar with
  | Some x -> x#doIt
  | None -> failwith "value not initialized"

I don't know what you intended bar to mean when you wrote, class foo bar, but it's an argument for the class foo (functional object) and has nothing to do with the class bar. Take a look at the type definition of foo.

'a -> object val mutable data : bar option method get : bar option end

This is an object that takes one argument, of any type and constructs an instance of the object. Overall, I don't think you want an option type as a solution, but leverage functional objects, like this:

class bar = object (self)
    method doIt = Printf.printf "Doing it"
end

class foo (arg1:bar) = object (self)
    val mutable data = arg1
    method get = data
    method set new_data = data <- new_data
end
nlucaroni