Created
September 3, 2016 20:59
-
-
Save jnape/138195ea8e1be2455d1c3855ce1d49bd to your computer and use it in GitHub Desktop.
General recursion with Elgot algebras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.jnape.palatable.lambda.adt.Either; | |
import com.jnape.palatable.lambda.functions.Fn3; | |
import com.jnape.palatable.lambda.functor.Functor; | |
import com.jnape.palatable.lambda.functor.builtin.Identity; | |
import java.util.function.Function; | |
import static com.jnape.palatable.lambda.adt.Either.left; | |
import static com.jnape.palatable.lambda.adt.Either.right; | |
public final class Hylomorphism<A, B, FA extends Functor<A>, FB extends Functor<B>> | |
implements Fn3<Function<? super FB, ? extends B>, Function<? super A, ? extends FA>, A, B> { | |
@Override | |
@SuppressWarnings("unchecked") | |
public B apply(Function<? super FB, ? extends B> phi, Function<? super A, ? extends FA> psi, A a) { | |
return phi.apply((FB) psi.apply(a).fmap(apply(phi, psi))); | |
} | |
public static final class Elgot<A, B, FA extends Functor<A>, FB extends Functor<B>> | |
implements Fn3<Function<? super FB, ? extends B>, Function<? super A, ? extends Either<B, FA>>, A, B> { | |
@Override | |
@SuppressWarnings("unchecked") | |
public B apply(Function<? super FB, ? extends B> phi, Function<? super A, ? extends Either<B, FA>> psi, A a) { | |
return psi.apply(a).match(b -> b, fa -> phi.apply((FB) fa.fmap(apply(phi, psi)))); | |
} | |
public static <A, B, FA extends Functor<A>, FB extends Functor<B>> Elgot<A, B, FA, FB> elgot() { | |
return new Elgot<>(); | |
} | |
public static void main(String[] args) { | |
Elgot<String, Integer, Identity<String>, Identity<Integer>> elgot = elgot(); | |
Integer r = elgot.apply(Identity::runIdentity, s -> s.length() > 3 ? left(s.length()) : right(new Identity<>(s + "+"))).apply(""); | |
System.out.println(r); // prints "4" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment