Skip to content

X Folding

John McClean edited this page Jul 6, 2018 · 6 revisions

Folds

Folds allow us to break apart the internal structure of a Cyclops data type and execute a function across it's contents. Some typical use cases include

  1. Executing an aggregation function across the contents of a Seq, Vector, ReactiveSeq or other non-scalar data structure
  2. Handling the case where an Option has Some value separately from where it has None.

Examples

Summing the contents of a List (Seq)

int res = Seq.of(1,2,3)
             .foldLeft(0,(a,b)->a+b);
//6

Handling Option.some and Option.none

int defaultValue = -1;
Option<Integer> none = Option.none();
int res = none.fold(some->some,()->defaultValue);
//-1 (defaultValue)

The Folds interface

The Folds interface is implemented by a huge variety of data structures in Cyclops X (including all Persistent Collections, ReactiveSeq and Reactive Collections). Folds extends Iterable and has a large range of methods for processing the internal data of an implementing type to generate a new form.

Conversion methods

  • stream, toArray, bankersQueue, treeSet, hashSet, vector, lazySeq, seq, toHashMap, toMap, toCollection, toList, toSet
  • iterableTo - accepts a function to convert Folds to another form
  • groupBy - group the contents of the Object that implements Folds into a Persistent HashMap

Example iterableTo

ReactiveSeq<Integer> rs = LazySeq.of(1,2,3)
                                 .iterableTo(ReactiveSeq::fromIterable);

Statistical methods

  • count, countDistinct, maxBy, minBy, mode, occurances, mean, median, withPercentiles, atPercentile, variance ,populationVariance, stdDeviation, longStats, intStats , doubleStats ,maximum, minimum, sumInt , sumDouble, sumLong

xMatch allMatch anyMatch noneMatch startsWith endsWith

collect

foldMap foldMap foldLeft foldLeft foldLeft foldLeft foldLeft foldLeft foldRight foldRight foldRight foldMapRight

join join join print print printOut printErr

headOption

firstValue singleOrElse single single takeOne elementAt

indexOf lastIndexOf indexOfSlice lastIndexOfSlice

scheduleStream

Clone this wiki locally