|
| 1 | +package com.jnape.palatable.lambda.functions.builtin.fn1; |
| 2 | + |
| 3 | +import com.jnape.palatable.lambda.functions.Fn1; |
| 4 | + |
| 5 | +import java.util.Collections; |
| 6 | + |
| 7 | +import static com.jnape.palatable.lambda.adt.Maybe.just; |
| 8 | +import static com.jnape.palatable.lambda.adt.Maybe.nothing; |
| 9 | +import static com.jnape.palatable.lambda.adt.hlist.HList.tuple; |
| 10 | +import static com.jnape.palatable.lambda.functions.builtin.fn1.Empty.empty; |
| 11 | +import static com.jnape.palatable.lambda.functions.builtin.fn1.Tail.tail; |
| 12 | +import static com.jnape.palatable.lambda.functions.builtin.fn2.Snoc.snoc; |
| 13 | +import static com.jnape.palatable.lambda.functions.builtin.fn2.Unfoldr.unfoldr; |
| 14 | + |
| 15 | +/** |
| 16 | + * Given an <code>{@link Iterable}<A></code>, produce an |
| 17 | + * <code>{@link Iterable}<{@link Iterable}<A>></code>, representing all of the subsequences of tail |
| 18 | + * elements, ordered by size, starting with the full {@link Iterable}. |
| 19 | + * <p> |
| 20 | + * For example, <code>tails(asList(1,2,3))</code> would iterate <code>[1,2,3]</code>, <code>[2,3]</code>, |
| 21 | + * <code>[3]</code>, and <code>[]</code>. |
| 22 | + * |
| 23 | + * @param <A> the Iterable element type |
| 24 | + */ |
| 25 | +public final class Tails<A> implements Fn1<Iterable<A>, Iterable<Iterable<A>>> { |
| 26 | + |
| 27 | + private static final Tails INSTANCE = new Tails(); |
| 28 | + |
| 29 | + private Tails() { |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + public Iterable<Iterable<A>> apply(Iterable<A> as) { |
| 34 | + return snoc(Collections::emptyIterator, |
| 35 | + unfoldr(next -> empty(next) |
| 36 | + ? nothing() |
| 37 | + : just(tuple(next, tail(next))), as)); |
| 38 | + } |
| 39 | + |
| 40 | + @SuppressWarnings("unchecked") |
| 41 | + public static <A> Tails<A> tails() { |
| 42 | + return INSTANCE; |
| 43 | + } |
| 44 | + |
| 45 | + public static <A> Iterable<Iterable<A>> tails(Iterable<A> as) { |
| 46 | + return Tails.<A>tails().apply(as); |
| 47 | + } |
| 48 | +} |
0 commit comments