Skip to content

Commit de00ae9

Browse files
committed
adding tail()
1 parent b783c73 commit de00ae9

File tree

2 files changed

+71
-0
lines changed
  • src
    • main/java/com/jnape/palatable/lambda/functions/builtin/fn1
    • test/java/com/jnape/palatable/lambda/functions/builtin/fn1

2 files changed

+71
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.jnape.palatable.lambda.functions.builtin.fn1;
2+
3+
import com.jnape.palatable.lambda.functions.Fn1;
4+
5+
import java.util.Iterator;
6+
7+
/**
8+
* Returns the tail of an <code>Iterable</code>; the is, an <code>Iterable</code> of all the elements except for the
9+
* head element. If the input <code>Iterable</code> is empty, the result is also an empty <code>Iterable</code>;
10+
*
11+
* @param <A> the Iterable element type
12+
*/
13+
public final class Tail<A> implements Fn1<Iterable<A>, Iterable<A>> {
14+
15+
private Tail() {
16+
}
17+
18+
@Override
19+
public Iterable<A> apply(Iterable<A> as) {
20+
return () -> {
21+
Iterator<A> iterator = as.iterator();
22+
if (iterator.hasNext())
23+
iterator.next();
24+
return iterator;
25+
};
26+
}
27+
28+
public static <A> Tail<A> tail() {
29+
return new Tail<>();
30+
}
31+
32+
public static <A> Iterable<A> tail(Iterable<A> as) {
33+
return Tail.<A>tail().apply(as);
34+
}
35+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.jnape.palatable.lambda.functions.builtin.fn1;
2+
3+
import com.jnape.palatable.lambda.functions.Fn1;
4+
import com.jnape.palatable.traitor.annotations.TestTraits;
5+
import com.jnape.palatable.traitor.runners.Traits;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import testsupport.traits.EmptyIterableSupport;
9+
import testsupport.traits.FiniteIteration;
10+
import testsupport.traits.ImmutableIteration;
11+
import testsupport.traits.Laziness;
12+
13+
import static com.jnape.palatable.lambda.functions.builtin.fn1.Tail.tail;
14+
import static java.util.Arrays.asList;
15+
import static java.util.Collections.emptyList;
16+
import static org.junit.Assert.assertThat;
17+
import static testsupport.matchers.IterableMatcher.iterates;
18+
19+
@RunWith(Traits.class)
20+
public class TailTest {
21+
22+
@TestTraits({Laziness.class, EmptyIterableSupport.class, FiniteIteration.class, ImmutableIteration.class})
23+
public Fn1<? extends Iterable, ?> createTraitsTestSubject() {
24+
return tail();
25+
}
26+
27+
@Test
28+
public void skipsFirstElementOfNonEmptyList() {
29+
assertThat(tail(asList(1, 2, 3)), iterates(2, 3));
30+
}
31+
32+
@Test
33+
public void isEmptyIfEmptyIterable() {
34+
assertThat(tail(emptyList()), iterates());
35+
}
36+
}

0 commit comments

Comments
 (0)