The main question is OCAML OOP

I am trying to learn oCaml and I have a problem with why the program below is not valid.

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;;

An error occurred while trying to compile the program:

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 in why:

val dMember = foo
method doIt = dMember#doSomething

wrong. Any (and I mean any) help is appreciated.

+3
source share
2 answers

Declare type:

class myClass (foo:myClass2) =
+1
source

OCaml objects cannot have free type variables in their signatures. Since the type of the argument is foonot completely specified, you need to parameterize the myClassfree variables in the type foo.

class ['a] myClass foo =
object
 val dMember = foo
 method doIt : 'a = dMember#doSomething
end;;

This definition is of type

class ['a] myClass :
  (< doSomething : 'a; .. > as 'b) ->
  object val dMember : 'b method doIt : 'a end

dataypes, , 'a tree ( 'a - ). , 'a foo#doSomething, foo.

# let x = new myClass (new myClass2);; 
val x : unit myClass = <obj>
# x#doIt ;;
Doing something
- : unit = ()
+6

Source: https://habr.com/ru/post/1702218/


All Articles