|
| 1 | +package com.jnape.palatable.lambda.functions.builtin.fn1; |
| 2 | + |
| 3 | +import com.jnape.palatable.lambda.adt.Either; |
| 4 | +import com.jnape.palatable.lambda.functions.Fn1; |
| 5 | +import com.jnape.palatable.lambda.functions.builtin.fn2.Snoc; |
| 6 | +import com.jnape.palatable.lambda.monoid.builtin.Merge; |
| 7 | + |
| 8 | +import java.util.Collections; |
| 9 | + |
| 10 | +import static com.jnape.palatable.lambda.adt.Either.right; |
| 11 | +import static com.jnape.palatable.lambda.functions.builtin.fn1.Constantly.constantly; |
| 12 | +import static com.jnape.palatable.lambda.functions.builtin.fn3.FoldLeft.foldLeft; |
| 13 | + |
| 14 | +/** |
| 15 | + * Fold an <code>{@link Iterable}<{@link Either}<L, R>></code> into an <code>{@link Either}<{@link |
| 16 | + * Iterable}<L>, {@link Iterable}<R>></code>, preserving all results of the side that's returned. That |
| 17 | + * is, if the result is a <code>left</code>, it will contain all left values; if it is a <code>right</code>, it will |
| 18 | + * contain all right values. |
| 19 | + * <p> |
| 20 | + * It may be useful to think of this as a more efficient version of <code>{@link Merge}<{@link Iterable}<L>, |
| 21 | + * {@link Iterable}<R>></code>. |
| 22 | + * |
| 23 | + * @param <L> the left parameter type |
| 24 | + * @param <R> the right parameter type |
| 25 | + */ |
| 26 | +public final class Coalesce<L, R> implements Fn1<Iterable<Either<L, R>>, Either<Iterable<L>, Iterable<R>>> { |
| 27 | + |
| 28 | + private static final Coalesce INSTANCE = new Coalesce(); |
| 29 | + |
| 30 | + private Coalesce() { |
| 31 | + } |
| 32 | + |
| 33 | + @Override |
| 34 | + public Either<Iterable<L>, Iterable<R>> apply(Iterable<Either<L, R>> eithers) { |
| 35 | + return foldLeft((acc, e) -> acc |
| 36 | + .biMapL(ls -> e.match(Snoc.<L>snoc().flip().apply(ls), constantly(ls))) |
| 37 | + .flatMap(rs -> e.biMap(Collections::singletonList, |
| 38 | + Snoc.<R>snoc().flip().apply(rs))), |
| 39 | + right(Collections::emptyIterator), |
| 40 | + eithers); |
| 41 | + } |
| 42 | + |
| 43 | + @SuppressWarnings("unchecked") |
| 44 | + public static <A, B> Coalesce<A, B> coalesce() { |
| 45 | + return INSTANCE; |
| 46 | + } |
| 47 | + |
| 48 | + public static <A, B> Either<Iterable<A>, Iterable<B>> coalesce(Iterable<Either<A, B>> eithers) { |
| 49 | + return Coalesce.<A, B>coalesce().apply(eithers); |
| 50 | + } |
| 51 | +} |
0 commit comments