Skip to content

Commit 0386eb7

Browse files
committed
Add sumNel for Semigroup using a NonEmptyList
1 parent 158aabf commit 0386eb7

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

core/src/main/java/fj/Semigroup.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,12 @@ static <A> A multiply1p(F<A, F<A, A>> sum, int n, A a) {
9898
}
9999

100100
/**
101+
* Sums the given values with left-fold.
102+
*/
103+
public A sumNel(final NonEmptyList<A> as) {
104+
return as.foldLeft1(sum);
105+
}
106+
101107
/**
102108
* Swaps the arguments when summing.
103109
*/

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import java.util.Collection;
77
import java.util.Iterator;
88

9+
import static fj.Function.flip;
910
import static fj.Function.identity;
1011
import static fj.data.Option.some;
1112
import static fj.data.Option.somes;
@@ -87,6 +88,26 @@ public NonEmptyList<A> append(final NonEmptyList<A> as) {
8788
return nel(head, bb);
8889
}
8990

91+
/**
92+
* Performs a right-fold reduction across this list. This function uses O(length) stack space.
93+
*/
94+
public final A foldRight1(final F<A, F<A, A>> f) {
95+
return reverse().foldLeft1(flip(f));
96+
}
97+
98+
/**
99+
* Performs a left-fold reduction across this list. This function runs in constant space.
100+
*/
101+
public final A foldLeft1(final F<A, F<A, A>> f) {
102+
A x = head;
103+
104+
for (List<A> xs = tail; !xs.isEmpty(); xs = xs.tail()) {
105+
x = f.f(x).f(xs.head());
106+
}
107+
108+
return x;
109+
}
110+
90111
/**
91112
* Maps the given function across this list.
92113
*

0 commit comments

Comments
 (0)