Functional Programming Patterns
Functional Composition:
Functional Composition is a pattern where you combine two or more functions to produce a new function. It allows you to create complex behaviors by composing simpler functions.
Example of Functional Composition:
In this example, addOne.andThen(multiplyByTwo)
creates a composed function that first adds one to the input and then multiplies the result by two.
Currying:
Currying is a technique where a function takes multiple arguments and transforms it into a sequence of functions, each taking a single argument. It simplifies function composition and partial application.
Example of Currying:
In this example, curriedAddition
is a curried function. curriedAddition.apply(2)
partially applies the function, creating a new function addTwo
that adds 2 to its input.
Memoization:
Memoization is an optimization technique where the results of expensive function calls are cached, so that if the same inputs occur again, the cached result is returned instead of recalculating the result.
Example of Memoization:
In this example, factorial
is a memoized function. The computeIfAbsent
method of ConcurrentHashMap
is used to cache the results. When factorial.apply(n)
is called, it calculates the factorial of n
and caches the result, preventing redundant calculations for the same input.
These functional programming patterns provide powerful tools for creating expressive, composable, and efficient code in Java. Functional composition, currying, and memoization enhance code readability, maintainability, and performance by encouraging the use of pure functions and immutable data.
Last updated