Comment by ngruhn

1 month ago

I'm a bit torn on ad-hoc polymorphism. You can definitely do cool things with it. But, as others have pointed out, it does reduce type safety:

https://cs-syd.eu/posts/2023-08-25-ad-hoc-polymorphism-erode...

The same point holds of interfaces. And it’s not clear what the alternative is. No type system I’m aware of would force you to change all occurrences of this business logic pattern, with or without ad hoc polymorphism.

But at least ad hoc polymorphism lets you search for all instances of that business logic easily.

  • ML languages have a "types, modules, types-of-modules, and functors" approach to ad-hoc poly. It's a bit strange compared to what other languages do. I am wondering whether it's ever been seen outside of SML and OCaml.

    For JSON deserialisation, you would declare a module-type called "JSON-deserialiser", and you would define a bunch of modules of that module-type.

    The unusual thing is that a JSON-deserialiser would no longer be tied to a type (read: type, not module-type). Types in ML-like languages don't have any structure at all. I suppose you can now define many different JSON-serialisers for the same type?

The article provides a contrived example and doesn't prove that ad-hoc polymorphism reduces type-safety. Even when `Maybe [a]` is being folded via `Foldable f` the claimed type-safety isn't reduced, it's the context of the folding that's being changed from `[a]` to `Maybe a`, and everything is type-safe. Secondly, if you really want to distinguish between the empty list and disabled allow-lists within your type-system you do define your own data type with that representation, and you don't declare it foldable, because the folding algebra doesn't make sense for any practical use-case of the disabled allow-lists. The language actually provides you with the means to reduce evaluation contexts your types can be part of.