3 ms·
> there's no guarantee that `Optional<A> implements Monad<A>` implies that also `Optional<B> implements Monad<B> In a language like Java (and presumably many o
by Tainnor 3y ago
> there's no guarantee that `Optional<A> implements Monad<A>` implies that also `Optional<B> implements Monad<B>
In a language like Java (and presumably many others) a generic type argument is implicitly universally quantified. Optional<A> implementing Monad<A> would therefore imply that Optional<B> implements Monad<B>.
The problem for why you can't define "monad" as an interface in Java is because you can't refer to the type constructor (due to the lack of HKT, as you yourself explained). That means that you can't even define "map" generically. You can define it for Optional, or List:
class Optional<A> {
...
Optional<B> map(Function<A, B> f) { ... }
...
}
class List<A> {
...
List<B> map(Function<A, B> f) { ... }
}
but you can't extract map into a Monad interface because you'd have to write the return type as "T<B>" or something and that's not possible (for a non-concrete T).
- Twey 3y agoThe universal quantification works for defining the _implementation_, but (by itself) not for defining the constraints. Yes, if you write an implementation for `Optional<A>` then it _is_ implemented for any `A` — but it's impossible for an implementation to _require_ it to be implemented for every `A` (and thereby be able to take advantage of that fact, e.g. to be able to know that `Optional<A> → Optional<B>` is well-defined for any `A` and `B`). :)