Skip to content

Instantly share code, notes, and snippets.

@nbardiuk
Created October 18, 2018 17:31
Show Gist options
  • Save nbardiuk/651fcd227cb42dc117e91a2464be1256 to your computer and use it in GitHub Desktop.
Save nbardiuk/651fcd227cb42dc117e91a2464be1256 to your computer and use it in GitHub Desktop.
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"));
System.out.println(result);
}
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