Immutability and Pure Functions
Or how to become a first-class citizen
About Me
Fullstack developer at SparkFabrik
@edodusi on twitter
Contact me!
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
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!
Pure functions
● No side-effects
● Stateless
● Idempotent
● Self-contained
● Thread-safe
● Composable
● Easy testability!
<?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.
Immutability
<?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.
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
<?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.
this.http
.get(uri, { params })
.then(data => doThis(data))
.then(data => doThat(data))
.then(() => log())
.catch(e => handleError(e))
Promises
this.http
.get<Response>(uri, { params })
.pipe(
filter(data => isPositive(data)),
map(data => doSomething(data)),
catchError(error => {
console.error(error);
handleError(error)});
})
)
Promises (pipe)
parallel([
readFile(‘./file’),
http.get(‘url’),
db.get(‘user.name’)
], () => {
console.log(file);
console.log(user);
});
List of tasks
tasks = [
readFile(‘./file’),
http.get(‘url’),
db.get(‘user.name’)
];
file = tasks[0].then();
Promises.all(tasks).then();
With promises
export interface State {
page: Page;
loaded: boolean;
loading: boolean;
validated: boolean;
components: Array<any>;
}
function reducer(state = initialState): State {
return {
...state,
loaded: false,
loading: true
};
}
Redux state
Animation credits Hristo Georgiev: https://www.pluralsight.com/guides/building-a-redux-application-with-angular-2-part-1

Immutability and pure functions

  • 1.
    Immutability and PureFunctions Or how to become a first-class citizen
  • 2.
    About Me Fullstack developerat SparkFabrik @edodusi on twitter Contact me!
  • 3.
    Key concepts offunctional 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 offunctional 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 ● Noside-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.
  • 7.
  • 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.
  • 11.
    this.http .get(uri, { params}) .then(data => doThis(data)) .then(data => doThat(data)) .then(() => log()) .catch(e => handleError(e)) Promises
  • 12.
    this.http .get<Response>(uri, { params}) .pipe( filter(data => isPositive(data)), map(data => doSomething(data)), catchError(error => { console.error(error); handleError(error)}); }) ) Promises (pipe)
  • 13.
  • 14.
    tasks = [ readFile(‘./file’), http.get(‘url’), db.get(‘user.name’) ]; file= tasks[0].then(); Promises.all(tasks).then(); With promises
  • 15.
    export interface State{ page: Page; loaded: boolean; loading: boolean; validated: boolean; components: Array<any>; } function reducer(state = initialState): State { return { ...state, loaded: false, loading: true }; } Redux state
  • 16.
    Animation credits HristoGeorgiev: https://www.pluralsight.com/guides/building-a-redux-application-with-angular-2-part-1