-
Notifications
You must be signed in to change notification settings - Fork 51
Generic Monoids
Cyclops has merged with simple-react. Please update your bookmarks (stars :) ) to https://github.com/aol/cyclops-react
All new develpoment on cyclops occurs in cyclops-react. Older modules are still available in maven central.

AsGenericMonoid.asMonoid and As.asMonoid allow external Monoid implementations (e.g. from Functional Java) to be coerced to com.aol.cyclops.lambda.api.Monoid.
Monoids have a specific mathematical meaning, and meaning for functional programmers. For most of the rest of us, they have the very nice property of fitting the interface of Stream.reduce exactly - and - of allowing reducing operations to be performed in parallel.
Monoids consist of a zero element, and a combiner function that combines two elements. Combining an element with the zero element leaves the original element unchanged. For example, if we had a combiner function that adds two numbers. The zero element could be the number 0, as passing it to the combiner would leave the other number unchanged. ("" behaves similarly for String concatenation, and 1 for multiplication etc).
Java 8 introduced Mutable Reduction as the main way to convert Streams into Collections, primarily because Collections in the JDK are mutable. Stream.collect won't work particularly well (or at all) with functional immutable and persistent collections - but genuine Immutable Reduction will.
Just like Monoids can be defined for addition, multiplication and String concatenation (as mentioned above)- they can also be formed for the concatenation of persistent data structures.
This makes them a very useful addition to the Java developers toolkit - and allows us to simplify the conversion of Streams to Immutable Collections in the same manner as Stream.collect did for Mutable collections.
Cyclops takes a practical approach and isn't in the business of defining mathematical interfaces, so Monoid also contains useful methods to reduce a Stream using it's zero element and combiner. Monoid also provides a mechanism to first convert a Stream to a suitable type before reduction.
The Reducers class contains a number of pre-rolled Monoids including those for
- Concatenation of PStacks see pcollections.org
- Concatenation of PMaps see pcollections.org
- Concatenation of Strings
and more.
We use some of these internally, for example to convert Streams into Persistent (Immutable) Maps
e.g.
converters = Reducers.<MonadicConverter>toPStack().mapReduce(StreamUtils.stream(loader.iterator()).sorted((a,b) -> b.priority()-a.priority()));