1
1
package com .jnape .palatable .lambda .monoid ;
2
2
3
+ import com .jnape .palatable .lambda .functions .builtin .fn2 .Map ;
3
4
import com .jnape .palatable .lambda .functions .builtin .fn2 .ReduceLeft ;
4
5
import com .jnape .palatable .lambda .functions .builtin .fn2 .ReduceRight ;
5
6
import com .jnape .palatable .lambda .semigroup .Semigroup ;
6
7
8
+ import java .util .function .Function ;
9
+
10
+ import static com .jnape .palatable .lambda .functions .builtin .fn2 .Map .map ;
11
+
7
12
/**
8
13
* A {@link Monoid} is the pairing of a {@link Semigroup} with an identity element.
9
14
*
@@ -24,6 +29,7 @@ public interface Monoid<A> extends Semigroup<A> {
24
29
*
25
30
* @param as the elements to reduce
26
31
* @return the reduction, or {@link Monoid#identity} if empty
32
+ * @see ReduceLeft
27
33
*/
28
34
default A reduceLeft (Iterable <A > as ) {
29
35
return ReduceLeft .reduceLeft (toBiFunction (), as ).orElse (identity ());
@@ -35,11 +41,28 @@ default A reduceLeft(Iterable<A> as) {
35
41
*
36
42
* @param as an Iterable of elements in this monoid
37
43
* @return the reduction, or {@link Monoid#identity} if empty
44
+ * @see ReduceRight
38
45
*/
39
46
default A reduceRight (Iterable <A > as ) {
40
47
return ReduceRight .reduceRight (toBiFunction (), as ).orElse (identity ());
41
48
}
42
49
50
+ /**
51
+ * Homomorphism combined with catamorphism. Convert an <code>Iterable<B></code> to an
52
+ * <code>Iterable<A></code> (that is, an <code>Iterable</code> of elements this monoid is formed over), then
53
+ * reduce the result from left to right. Under algebraic data types, this is isomorphic to a flatMap.
54
+ *
55
+ * @param fn the mapping function from A to B
56
+ * @param bs the Iterable of Bs
57
+ * @param <B> the input Iterable element type
58
+ * @return the folded result under this Monoid
59
+ * @see Map
60
+ * @see Monoid#reduceLeft(Iterable)
61
+ */
62
+ default <B > A foldMap (Function <? super B , ? extends A > fn , Iterable <B > bs ) {
63
+ return reduceLeft (map (fn , bs ));
64
+ }
65
+
43
66
/**
44
67
* Promote a {@link Semigroup} to a {@link Monoid} by supplying an identity element.
45
68
*
0 commit comments