Pass me that function
github.com/deviousdodo
twitter.com/deviousdodo
Adrian Gheorghe
adrian.gheorghe@gmail.com
What is FP ?
treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data
What is a pure function?
No observable side effects
Returns the same value for the same input
const square = (n) => n * n;
const checkAge = (age) => age >= 18;Advantages of pure functions
- self contained
- testable
- referential transparency
- concurrency
const square = (n) => n * n;
square(3);
// equivalent to
const square = {
1: 1,
2: 4,
3: 9
};
square[3];Example of side effects
- changing arguments or global state
- exceptions
- writing to / reading from a file
- inserting into a database
- querying the DOM
- everything else that's actually useful...
Understanding and debugging a function with side effects requires knowledge about the context
Problems with side effects
In the presence of side effects, a program's behaviour may depend on history.
// uses global variable
let minAge = 18;
const checkAge = (age) age >= minAge;
// makes request
const makeRequest = (url) => Ajax.get(url);You can transform some impure functions into pure ones by delaying evaluation
const pureRequest = (url) => () => Ajax.get(url);Imperative programming: computation is implemented with program state and statements that change it.
Declarative programming: computation is represented by expressions that describe the desired result.
// imperative
const a = [1, 2, 3];
let r = [];
for (let i = 0; i < a.length; i++) {
r.push(a[i] * a[i]);
}
// declarative
const r = map(square, [1, 2, 3]);// imperative
function map(fn, arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push( fn(arr[i]) );
}
return result;
}
// declarative
function map(fn, arr) {
if (isEmpty(arr)) return [];
return concat([fn(head(arr))], map(fn, tail(arr)));
}currying
calling a function with fewer arguments will return another function that accepts the remainder of the arguments
const filter = (fn, arr) => arr.filter(fn);
const isEven = n => n % 2 === 0;
const filterEven = arr => filter(isEven, arr);
console.log( filterEven([1, 2, 3]) );
// [ 2 ]// const filter = (fn, arr) => arr.filter(fn);
const filter = curry((fn, arr) => arr.filter(fn));
const isEven = n => n % 2 === 0;
// const filterEven = arr => filter(isEven, arr);
const filterEven = filter(isEven);
console.log( filterEven([1, 2, 3]) );
// [ 2 ]function composition
combining simple functions to produce more complicated ones
const incrementSquare = compose(inc, square);
console.log( incrementSquare(3) );
// 10const downcase = (s) => s.toLowerCase();
const keepLetters = (s) => s.replace(/[^a-z]/g, '');
const slug = (words) =>
join('-', map(keepLetters, map(downcase, words)));
console.log( slug(['Hello', 'World!!!']) );
// hello-worldconst downcase = (s) => s.toLowerCase();
const keepLetters = (s) => s.replace(/[^a-z]/g, '');
// const slug = (words) =>
// join('-', map(keepLetters, map(downcase, words)));
const slug = compose(
join('-'), map(keepLetters), map(downcase)
);
console.log( slug(['Hello', 'World!!!']) );
// hello-worldconst downcase = (s) => s.toLowerCase();
const keepLetters = (s) => s.replace(/[^a-z]/g, '');
// const slug = compose(
// join('-'), map(keepLetters), map(downcase)
// );
const downcaseLetters = compose(keepLetters, downcase);
const slug = compose( join('-'), map(downcaseLetters) );
console.log( slug(['Hello', 'World!!!']) );
// hello-worldSo we have some tools to create programs that pipe data through a series of pure functions.
What about control flow, error handling, asynchronous actions, state and I/O?
Warning:
Simplifications ahead
Functor
A Functor represents a sort of "container", along with the ability to apply a function over its value.
class Container {
constructor(v) {
this._value = v;
}
map(fn) {
return new Container(fn(this._value));
}
}
console.log( new Container(2).map(square) );
// output: ???class Container {
constructor(v) {
this._value = v;
}
map(fn) {
return new Container(fn(this._value));
}
}
console.log( new Container(2).map(square) );
// Container(4)class Container {
constructor(v) {
this._value = v;
}
map(fn) {
return new Container(fn(this._value));
}
}
console.log( new Container(2).map(square) );
// Container(4)
console.log( new Container(2).map(square).map(inc) );
// Container(5)
console.log( map(inc, map(square, new Container(2)) );
// Container(5)
console.log( compose(inc, square), new Container(2) );
// Container(5)
Abstraction over function application
(We ask the container to run the function for us, in any way it wants)
We can express higher-order
concepts
class Maybe {
constructor(v) {
this._value = v;
}
isNothing() {
return (this._value === null || this._value === undefined);
}
map(f) {
return this.isNothing() ?
new Maybe(null) : new Maybe(f(this._value));
}
}
console.log( new Maybe("HELLO WORLD!").map(toLowerCase) );
// Maybe("hello world!")
console.log( map(toLowerCase, new Maybe(null)) );
// Maybe(null)const safeHead = (list) => Maybe.of(list[0]);
const square = (n) => n * n;
var firstSquare = compose(map(square), safeHead);
firstSquare([2, 3]);
// Maybe(4)
firstSquare([]);
// Maybe(null)What if we have a function that takes multiple arguments and we want to pass it multiple wrapped values?
const add = curry( (a, b) => a + b );
const func = map(add, Maybe.of(2));
console.log( func );
// Maybe.of(add(2));
console.log( func(3) );
// Maybe(5)
console.log( func(Maybe.of(3)) );
// NaN
We need a function that can apply functors to each other (the function contents of one functor to the value contents of the other).
Applicative functors
They are functors that will allow us to apply functions wrapped in a container to values wrapped in another container.
class Maybe {
static of(v) {
return new Maybe(v);
}
ap(other_container) {
return other_container.map(this._value);
}
}
const add = curry( (a, b) => a + b );
Maybe.of(2).map(add).ap(Maybe.of(3));
// Maybe(5)
map(add, Maybe.of(2), Maybe.of(3));
// Maybe(5)
Maybe.of(add).ap(2).ap(3);
// Maybe(5)What if we need to chain functions that take normal values and return containers?
const safeHead = (list) => Maybe.of(list[0]);
const squareEven = (n) =>
n % 2 === 0 ? Maybe.of(n * n) : Maybe.of(null);
var firstSquare = compose(map(squareEven), safeHead);
firstSquare([2, 3]);
// Maybe(Maybe(4))
firstSquare([]);
// Maybe(Maybe(null))We need a function that can apply functions that return containers to other containers.
Monads apply a function that returns a value wrapped in a container to another container.
Monads
class Maybe {
join() {
return this.isNothing() ? Maybe.of(null) : this.__value;
}
chain(f) {
return this.map(f).join();
}
}
const safeHead = (list) => Maybe.of(list[0]);
const squareEven = (n) =>
n % 2 === 0 ? Maybe.of(n * n) : Maybe.of(null);
Maybe.of([2, 4]).chain(safeHead).chain(squareEven);
// Maybe(4)
Maybe.of(3).chain(squareEven);
// Maybe(null)Other uses
class IO {
constructor(f) {
this._value = f;
}
static of(x) => new IO(() => x);
map(f) {
return new IO(_.compose(f, this._value));
}
}Thank you!
Questions?
Pass me that function
By Adrian Gheorghe
Pass me that function
- 681