Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic OCaml OOP question

Tags:

oop

ocaml

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.

like image 936
Mat Kelly Avatar asked Mar 09 '26 05:03

Mat Kelly


2 Answers

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 = ()
like image 107
Chris Conway Avatar answered Mar 11 '26 03:03

Chris Conway


Declare the type:

class myClass (foo:myClass2) =
like image 37
Jules Avatar answered Mar 11 '26 04:03

Jules



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!