Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
fold map
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
class Scratch {
public static void main(String[] args) {
Monoid<Integer> sum = Monoid.of(0, Integer::sum);
Fold<String, Integer> sumStrings = Fold.of(Integer::parseInt, sum);
Integer result = sumStrings.fold(Arrays.asList("1", "2", "3"));
interface Monoid<A> {
A zero();
A add(A a1, A a2);
static <A> Monoid<A> of(A zero, BiFunction<A, A, A> add) {
return new Monoid<A>() {
@Override public A zero() {
return zero;
@Override public A add(A a1, A a2) {
return add.apply(a1, a2);
interface Fold<A, B> {
Function<A, B> toMonoid();
Monoid<B> monoid();
default B fold(Iterable<A> as) {
B result = monoid().zero();
for (A a : as) {
result = monoid().add(result, toMonoid().apply(a));
return result;
static <A, B> Fold<A, B> of(Function<A, B> toMonoid, Monoid<B> monoid) {
return new Fold<A, B>() {
@Override public Function<A, B> toMonoid() {
return toMonoid;
@Override public Monoid<B> monoid() {
return monoid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment