tags:

views:

167

answers:

2

Hello, 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.

+1  A: 

Declare the type:

class myClass (foo:myClass2) =
Jules
Wouldn't that defeat the purpose of using structural typing in the myClass.doIt method?
Juliet
+3  A: 

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 = ()
Chris Conway