Okamla method input

I played with method overrides and I found this stupid example:

class a = object method get (x : a) = x end class b = object inherit a method get (x : b) = x end 

I clearly indicate that I want the get method from class b to take b and return b, but the method signature is β†’ a. And if I do this (new b) #get (new a) he is very pleased when he really shouldn't. After that, I added something stupid:

 class a = object method get (x : a) = x end class b = object inherit a method get (x : b) = x#foo(x) method foo (x : a) = x end 

And I get Error: This expression has type b It has no method foo

What is happening on earth?

+4
source share
1 answer

First, take the first example: OCaml has structural typing of objects, not nominal typing. In other words, the type of an object is completely determined by its methods (and their types). Thus, classes a and b are actually the same type.

 $ ocaml OCaml version 4.00.0 # class a = object method get (x: a) = x end;; class a : object method get : a -> a end # class b = object inherit a method get (x: b) = x end;; class b : object method get : a -> a end # let a0 = new a;; val a0 : a = <obj> # let b0 = new b;; val b0 : b = <obj> # (a0: b);; - : b = <obj> # (a0: a);; - : a = <obj> # (b0: a);; - : a = <obj> # (b0: b);; - : b = <obj> # 

(I am trying to show here that both a0 and b0 are of type a and type b .)

In the second example, I would say that you are trying to give a new type to the get method. When you override a method in OCaml, the parameters and return types must be the same as in the parent class.

The error message seems unsuccessful. I assume that the compiler believes that type b is a different name for type a .

One of the strengths of OCaml is that it will infer types. If you leave : b for the get parameter in class b , you will get the following error instead:

 This expression has type a. It has no method foo 

This is a little more useful as it shows (I think) that a parameter is required for a .

Side comment (forgive me): if you get to the OO part of OCaml from the main language of OO, this may seem strange to you. But if you first learn the FPam part in OCaml, you may be wondering why all the major OO languages ​​are not so much wrong :-). (Of course, all the trade-offs, and there is no right way to structure calculations. But the OCaml OO subsystem does something pretty impressive.)

+5
source

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


All Articles