Java Reference
In-Depth Information
Function<Function<Double,Double>, Function<Double,Double>>
because it takes a function as argument (for example, (Double x) -> x * x) and returns a function
as result (in this example (Double x) -> 2 * x). We've written this as a function type (the leftmost
Function) to explicitly affirm the fact that you could pass this differentiating function to yet
another function. But it's good to recall that the type for differentiating and the signature
Function<Double,Double> differentiate(Function<Double,Double> func)
say the same thing.
Side effects and higher-order functions
We noted in chapter 7 that functions passed to stream operations should generally be side-effect
free, and we noted the problems that arise otherwise (such as incorrect results, perhaps even
unpredictable results due to race conditions we hadn't thought of). This principle also applies in
general when you use higher-order functions. When writing a higher-order function or method,
you don't know in advance what arguments it will be passed—and if the arguments have side
effects, then what these might do! It becomes far too complicated to reason about what your
code does if it uses functions passed as arguments that make unpredictable changes to the state
of your program; they might even interfere with your code in some hard-to-debug way. So it's a
good design principle to document what side effects you're willing to accept from functions
passed as parameters, and “none” is the best of all!
We now turn to currying : a technique that can help you modularize functions and reuse code.
14.1.2. Currying
Before we give the theoretical definition of currying, let's look at an example. Applications
almost always need to be internationalized, and so converting from one set of units to another
set is a problem that comes up repeatedly.
Unit conversion always involves a conversion factor and from time to time a baseline
adjustment factor. For example, the formula to convert Celsius to Fahrenheit is CtoF(x) = x*9/5
+ 32.
Search WWH ::




Custom Search