Fork me on GitHub
#java
<
2024-06-03
>
Ben Sless06:06:18

Trying to implement category theory things in Java (why not), I get tripped up on java syntax and generics Thought I'd start with interfaces for Functor, Applicative and Monad, then go from there Starting off, Functor:

public interface Functor<A> {
    // which is the correct signature for map?
    <B extends Functor<B>> Functor<B>map(Function<A,B> f);
    <B> Functor<B>map(Function<A,B> f);
}
The comment says it. In theory, we can map over every functor, but do I need to express somehow that the receiver and return value can be anything that extends Functor? It gets more complicated when Applicative provides a default implementation for functor:
@Override
    default <B> Functor<B> map(Function<A, B> f) {
        return this.apply(pure(f));
    }
Is this right? Does map over Applicative return Functor? Can I express somehow that it returns anything which extends Functor<B>? I have the same problem with Monad but figuring out the syntax / correct typing for applicative will probably carry over

Ben Sless07:06:13

Do I need to change the implementation in Applicative to return an Applicative?

littleli13:06:14

I'm not really good at this. But take a look at https://typelevel.org/cats/typeclasses/applicative.html it may cast some light on what is happening there with map and why you need ap (or product as an alternative reasoning) as a supportive construct https://typelevel.org/cats/typeclasses/applicative.html#what-is-ap So the way I see it is that Applicative is a Functor where you teach your map an additional superpower to be able to handle things like Optional types. I'm not sure if Java type system is capable to express this.