3. Key concepts of functional programming
Higher-order / first class functions
Functions that take other functions as arguments or return functions as results
Pure functions
Referential transparency, idempotence, reversible order (thread safe)
Recursion
Function that invoke itself over and over until the base case is reached
Immutable state
Function execution is independent from the program state and doesn’t change it
4. Key concepts of functional programming
Partial Application
The process of applying a function to some of its arguments
Curry
Transform a functions with multiple parameters as input into a function
with exactly one parameter
MORE! MORE!
5. Pure functions
● No side-effects
● Stateless
● Idempotent
● Self-contained
● Thread-safe
● Composable
● Easy testability!
6. <?php
$memoize = function ($func) {
return function () use ($func) {
static $cache = [];
$args = func_get_args();
$key = md5(serialize($args));
if (!isset($cache[$key])) {
$cache[$key] = call_user_func_array($func, $args);
}
return $cache[$key];
};
};
$sum = $memoize('sum');
echo $sum(2, 3) . PHP_EOL;
Memoization is a caching
technique used to store the
results of function calls and
returning them if called with
the same input.
8. <?php
$numbers = [1, 2, 3, 4, 5];
$sum = function ($x, $y) {
return $x + $y;
};
function sumArray($array) : callable {
return function ($sumFunction) use ($array): int {
return array_reduce($array, $sumFunction);
};
}
echo sumArray($numbers)($sum) . PHP_EOL;
The program’s state doesn’t
change during the execution.
It’s immutable.
If we compose pure functions
we are sure that this is true on
every execution, on every
machine, on every scale.
9. let add = (a, b) => a + b;
let increment = add.bind(null, 1);
increment(2);
// 3
let add = x => y => x + y;
let increment = add(1);
increment(2);
// 3
add(1)(2);
Partial application
Currying
10. <?php
$numbers = [1, 2, 3, 4, 5];
$sum = function ($x, $y) {
return $x + $y;
};
function sumArray($array) : callable {
return function ($sumFunction) use ($array): int {
return array_reduce($array, $sumFunction);
};
}
echo sumArray($numbers)($sum) . PHP_EOL;
Currying is transforming a
function that takes multiple
arguments into a chain of
functions each with a single
argument
This leads to function
composition.