cyclops java : Lists and Tuples by example
cyclops defines a number of useful interfaces for manipulating Lists in a Functional style they are :-
ListX : for j.u.List
LinkedListX : for persistent lists
VectorX : for persistent vectors
The examples below work across all 3 types of extended List. A common interface IndexedSequenceX can also be used to represent ListX, LinkedListX and VectorX instances.
Creation
The examples below cover some factory methods for creating extended Lists.
Appending to Lists
append and plusAll can be used to append to a List.
Adding / removing
Add and remove work, plus and minus are more idiomatic.
Take / drop
Take : takes a set number of elements (or sets a limit on the number of accepted elements)
Drop : drops a set number of elements (or skips them)
cycle
cycle allows us to build a repeating list.
head / tail
Lists can be defined recurisively as a head element and a tail list.
lazy / eager / materialize
By default Lists operate eagerly, which can give a performance benefit by reducing iteration over the List. The lazy / eager operators can switch between lazy and eager modes.
On occasion it is a good idea to call the materialize method. This materializes a lazy list.
In this example, materializing the list ensures that the zipping operation is applied only once and that the map operations that create the nums and chars lists work of the already materialized List instance.
reactive materialization
When Lists are creating from an underlying reactive Stream type (such as those in cyclops-react, RxJava or Reactor), materialize will call the terminal operation of that Stream so that the asynchronous population begins.
reverse
foldLeft / foldRight
foldLeft and foldRight allow us to apply a function to across the values in a list accumulating a result.
intersperse
Interperse adds a value between each pair of elements in a list
iterate
takeWhile
unfold
sliding / grouping
List Comprehensions
List Transformer
Remove odd values from a list of lists
Tuples
The map ‘catamorphism’
Tuples in cyclops-react come from Jooλ. They are Objects where each field has a parameterized type and an index, they are roughly equivalent to case classes in Scala and are pattern matchable via the ‘map’ method.
zipping
Tuples are the default operation on zip methods that do not accept a zipping function. As shown in the materialize example, zipping two lists can result in a Tuple. Tuple elements are accessible via an index v1 and v2.
