I am attempting to learn oCaml and am having an issue as to why the below program is invalid.
class myClass2 =
object
method doSomething = Printf.printf "%s\n" "Doing something"
end;;
class myClass foo =
object
val dMember = foo
method doIt = dMember#doSomething
end;;
let mc2 = new myClass2;;
let mc = new myClass mc2;;
mc#doIt;;
The error I receive when trying to compile the program is:
File "sample.ml", line 6, characters 5-84:
Some type variables are unbound in this type:
class myClass :
(< doSomething : 'b; .. > as 'a) ->
object val dMember : 'a method doIt : 'b end
The method doIt has type 'a where 'a is unbound
I am particularly interested as to why:
val dMember = foo
method doIt = dMember#doSomething
is invalid. Any (and I mean any) help is appreciated.
OCaml objects can't have free type variables in their signatures. Since the type of the argument foo is not fully specified, you need to parameterize myClass by the free variables in the type of foo.
class ['a] myClass foo =
object
val dMember = foo
method doIt : 'a = dMember#doSomething
end;;
This definition has the type
class ['a] myClass :
(< doSomething : 'a; .. > as 'b) ->
object val dMember : 'b method doIt : 'a end
This is similar to normal parameterized dataypes, e.g., 'a tree (the brackets around the 'a are just a bit of syntactic cruft). Note that 'a is the type of foo#doSomething, not of foo.
# let x = new myClass (new myClass2);;
val x : unit myClass = <obj>
# x#doIt ;;
Doing something
- : unit = ()
Declare the type:
class myClass (foo:myClass2) =
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With