Skip to content

Commit 431126a

Browse files
committed
Merge pull request #161 from mperry/list-partition
Added List.partition
2 parents 724081f + ed7007e commit 431126a

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

core/src/main/java/fj/data/List.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,22 @@ public final List<List<A>> partition(final int n) {
854854
return unfold(as -> as.isEmpty() ? Option.<P2<List<A>, List<A>>>none() : some(as.splitAt(n)), this);
855855
}
856856

857+
/**
858+
* Partitions the list into a tuple where the first element contains the
859+
* items that satisfy the the predicate f and the second element contains the
860+
* items that does not. The relative order of the elements in the returned tuple
861+
* is the same as the original list.
862+
*
863+
* @param f Predicate function.
864+
*/
865+
public P2<List<A>, List<A>> partition(F<A, Boolean> f) {
866+
P2<List<A>, List<A>> p2 = foldLeft(acc -> a ->
867+
f.f(a) ? P.p(acc._1().cons(a), acc._2()) : P.p(acc._1(), acc._2().cons(a)),
868+
P.p(nil(), nil())
869+
);
870+
return P.p(p2._1().reverse(), p2._2().reverse());
871+
}
872+
857873
/**
858874
* Returns the list of initial segments of this list, shortest first.
859875
*

core/src/test/java/fj/data/ListTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package fj.data;
22

3+
import fj.Equal;
4+
import fj.P2;
35
import org.junit.Test;
46

57
import java.util.Arrays;
@@ -53,4 +55,13 @@ public void convertToString() {
5355
expected.append(')');
5456
assertEquals(expected.toString(), List.range(0, n).toString());
5557
}
58+
59+
@Test
60+
public void partition() {
61+
P2<List<Integer>, List<Integer>> p = List.range(1, 5).partition(i -> i % 2 == 0);
62+
Equal<List<Integer>> e = Equal.listEqual(Equal.intEqual);
63+
assertTrue(e.eq(p._1(), List.list(2, 4)));
64+
assertTrue(e.eq(p._2(), List.list(1, 3)));
65+
}
66+
5667
}

0 commit comments

Comments
 (0)