cyclops java : Functions by example
Intro to functions
Below are some examples of function definition and application in Java.
Currying
Currying takes a multiple parameter function (e.g. a BiFunction or Fn2) and converts to a chain of single parameter (Function or Fn1) functions.
Partial Application
Partial application is different from currying and refers to applying one or more of a functions parameters (but not all of them) to produce another Function which accepts the remainder of the parameters.
In the example below we take a BiFunction that accepts a String and an Integer, partially apply an Integer as the second parameter (10). This results in a Function that accepts a String. When we apply the String “hello” the entire function is executed resulting in hello + “ “ + 10 (hello 10).
Composing Functions
When the output of one function matches the input to another, the two functions can be composed (or chained together).
Additional composition options
Direct input to output chaining is not the only way to join functions together. The fanIn and product operators make use of sum and tuple types in cyclops-react.
Higher Order Functions
Functions that accept or return functions are higher order. These types of functions are profilerating through APIs these days — map / filter / flatMap all accept Higher Order Functions.
//this is a pretty standard way to define a function as parameter in //Java 8Function<? super T, ? extends R> fn;//after a while you may see it as something more like thisFunction standardFunctionDefinition;
zipping
An Fn2 (or 2 parameter function) can be used to join data structures.
memoization / caching
The Monad for Functions
The Reader Monad provides flatMap and map operations to make function composition even more powerful (see Dependency Injection with the Reader Monad for more details).
The Monad for Suppliers
Suppliers (or zero parameter functions) capture laziness, Eval is the monad for Laziness.
(very) Advanced suppliers!
Trampoline can be implemented as Free Monad for Suppliers.
