3 ms·
I'm not sure you can emulate objects with modules. In particular, there is no "self" type with modules... or am I missing something?
by tomp 12y ago
I'm not sure you can emulate objects with modules. In particular, there is no "self" type with modules... or am I missing something?
- jamii 12y agoNo, ML modules are usually early bound which prevents open recursion eg module First = struct let rec even x = if (x >= 0) then ( print_endline "even!"; odd (x-1) ) else () and odd x = if (x >= 0) then ( print_endline "odd!"; even (x-1) ) else () module Second = struct include First let odd x = if (x >= 0) then ( print_endline "weird!"; even (x-1) ) else () end Second.odd(3) (* weird! * even! * odd! * even! *) In ocaml you can use classes for open recursion but that is implemented using dynamic dispatch. For static dispatch you would have to hack something together using a record that is passed itself.
- tomp 12y agoThat's more of an issue with implementation than with typing. I mean more like, in an OO language it is possible to declare an interface with a method that returns the final subtype (i.e. the object's this type), which isn't even know yet at the point the interface is defined.
- jamii 12y agoAh, I see what you are getting at. They seem related to me though. Open recursion requires calling the method from the final subtype rather than the current type - `even` would have to call `this#odd` instead of `odd`. The core problem in both cases is not being able to refer to the final subtype in any way. Hmmm, even if modules could refer to this final subtype you would probably have to choose between doing it via dynamic dispatch or sacrificing separate compilation, since the parent module doesn't know what method to dispatch to at the time of compilation.
- tel 12y agoThere are recursive modules but you're right if you're noting that modules don't offer open recursion. That's definitely something Scala offers that ML modules cannot.