|
| 1 | +package com.jnape.palatable.lambda.functions.builtin.fn2; |
| 2 | + |
| 3 | +import com.jnape.palatable.lambda.functions.Fn1; |
| 4 | +import com.jnape.palatable.lambda.functions.Fn2; |
| 5 | +import com.jnape.palatable.lambda.functor.builtin.Lazy; |
| 6 | + |
| 7 | +import java.util.function.BiFunction; |
| 8 | +import java.util.function.Function; |
| 9 | + |
| 10 | +import static com.jnape.palatable.lambda.functor.builtin.Lazy.lazy; |
| 11 | +import static com.jnape.palatable.lambda.monad.Monad.join; |
| 12 | + |
| 13 | +/** |
| 14 | + * Given a {@link BiFunction} that receives a recursive function and an input and yields a {@link Lazy lazy} result, and |
| 15 | + * an input, produce a {@link Lazy lazy} result that, when forced, will recursively invoke the function until it |
| 16 | + * terminates in a stack-safe way. |
| 17 | + * <p> |
| 18 | + * Example: |
| 19 | + * <pre> |
| 20 | + * <code> |
| 21 | + * Lazy<BigInteger> lazyFactorial = lazyRec((fact, x) -> x.equals(ONE) |
| 22 | + * ? lazy(x) |
| 23 | + * : fact.apply(x.subtract(ONE)).fmap(y -> y.multiply(x)), |
| 24 | + * BigInteger.valueOf(50_000)); |
| 25 | + * BigInteger value = lazyFactorial.value(); // 3.34732050959714483691547609407148647791277322381045 × 10^213236 |
| 26 | + * </code> |
| 27 | + * </pre> |
| 28 | + * |
| 29 | + * @param <A> the input type |
| 30 | + * @param <B> the output type |
| 31 | + */ |
| 32 | +public final class LazyRec<A, B> implements |
| 33 | + Fn2<BiFunction<Function<? super A, ? extends Lazy<B>>, A, Lazy<B>>, A, Lazy<B>> { |
| 34 | + |
| 35 | + private static final LazyRec<?, ?> INSTANCE = new LazyRec<>(); |
| 36 | + |
| 37 | + private LazyRec() { |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public Lazy<B> apply(BiFunction<Function<? super A, ? extends Lazy<B>>, A, Lazy<B>> fn, A a) { |
| 42 | + return join(lazy(() -> fn.apply(nextA -> apply(fn, nextA), a))); |
| 43 | + } |
| 44 | + |
| 45 | + @SuppressWarnings("unchecked") |
| 46 | + public static <A, B> LazyRec<A, B> lazyRec() { |
| 47 | + return (LazyRec<A, B>) INSTANCE; |
| 48 | + } |
| 49 | + |
| 50 | + public static <A, B> Fn1<A, Lazy<B>> lazyRec(BiFunction<Function<? super A, ? extends Lazy<B>>, A, Lazy<B>> fn) { |
| 51 | + return LazyRec.<A, B>lazyRec().apply(fn); |
| 52 | + } |
| 53 | + |
| 54 | + public static <A, B> Lazy<B> lazyRec(BiFunction<Function<? super A, ? extends Lazy<B>>, A, Lazy<B>> fn, A a) { |
| 55 | + return lazyRec(fn).apply(a); |
| 56 | + } |
| 57 | +} |
0 commit comments