Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions core/src/main/java/fj/data/List.java
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,22 @@ public final List<List<A>> partition(final int n) {
return unfold(as -> as.isEmpty() ? Option.<P2<List<A>, List<A>>>none() : some(as.splitAt(n)), this);
}

/**
* Partitions the list into a tuple where the first element contains the
* items that satisfy the the predicate f and the second element contains the
* items that does not. The relative order of the elements in the returned tuple
* is the same as the original list.
*
* @param f Predicate function.
*/
public P2<List<A>, List<A>> partition(F<A, Boolean> f) {
P2<List<A>, List<A>> p2 = foldLeft(acc -> a ->
f.f(a) ? P.p(acc._1().cons(a), acc._2()) : P.p(acc._1(), acc._2().cons(a)),
P.p(nil(), nil())
);
return P.p(p2._1().reverse(), p2._2().reverse());
}

/**
* Returns the list of initial segments of this list, shortest first.
*
Expand Down
11 changes: 11 additions & 0 deletions core/src/test/java/fj/data/ListTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package fj.data;

import fj.Equal;
import fj.P2;
import org.junit.Test;

import java.util.Arrays;
Expand Down Expand Up @@ -53,4 +55,13 @@ public void convertToString() {
expected.append(')');
assertEquals(expected.toString(), List.range(0, n).toString());
}

@Test
public void partition() {
P2<List<Integer>, List<Integer>> p = List.range(1, 5).partition(i -> i % 2 == 0);
Equal<List<Integer>> e = Equal.listEqual(Equal.intEqual);
assertTrue(e.eq(p._1(), List.list(2, 4)));
assertTrue(e.eq(p._2(), List.list(1, 3)));
}

}