3 ms·
If you want to override behaviour, why not just define a sum type wrapping other objects, a master function that matches on different cases, and then smaller fu
by zogrodea 3y ago
If you want to override behaviour, why not just define a sum type wrapping other objects, a master function that matches on different cases, and then smaller functions that decide on what to do for each case? That seems fine to me.
Like this:
type obj1 = { ... }
type sum =
| One of obj1
| Two of obj2
...
match param with
| One obj -> f(obj)
| Two obj -> f2(obj)
----
There is also the handle pattern which I've used with some success. You basically place some functions in a record/tuple and then call those functions when you need to.
https://jaspervdj.be/posts/2018-03-08-handle-pattern.html https://jaspervdj.be/posts/2018-03-08-handle-pattern.html
Edit: I mean to say that I've used something similar to the handle pattern in an immutable context (having a central function that takes objects that can be arbitrarily nested which carry their own function and data, and the parent object can call its function on a child object, and the child can call its function on its child, and so on...). Hopefully I am making sense.
- layer8 3y agoThat means having to code the dispatch manually that OO languages do automatically. It’s kind of the point of OO languages to not have to do that manually, and to have the subtype-specific functions be explicitly associated with each other, and not just implicitly by how they are used.
- zogrodea 3y agoThat's true. I didn't think of it that way.
- trashburger 3y agoWell, as my sibling comment says, you have just re-implemented dynamic dispatch in object programming ;). As a response to your edit, note that dynamic dispatch and immutability are not mutually exclusive; an object can have immutable state and can still have its behavior extended by creating an adapter object, for example.