Slide 1

Slide 1 text

Thinking in Functions Improve Your Javascript Through Functional Programming Techniques By - Anupam Jain

Slide 2

Slide 2 text

Software Design There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. - C.A.R. Hoare, 1980 ACM Turing Award Lecture

Slide 3

Slide 3 text

Good Design

Slide 4

Slide 4 text

Good Design??

Slide 5

Slide 5 text

Two Equivalent Programs var total = 0, count = 1; while (count <= 10) { total += count; count += 1; } total = sum(range(1, 10)); Which is more likely to contain a bug?

Slide 6

Slide 6 text

Abstraction The “shared” vocabulary that allows us to write concise, high level, programs

Slide 7

Slide 7 text

Shared Vocabulary var total = 0, count = 1; while (count <= 10) { total = total + count; count = count + 1; } total = sum(range(1, 10));

Slide 8

Slide 8 text

Add the elements of an array var array = [1,2,3,4]; var sum = 0; for(var i=0; i

Slide 9

Slide 9 text

Multiply the elements of an array var array = [1,2,3,4]; var product = 1; for(var i=0; i

Slide 10

Slide 10 text

Sum var array = [1,2,3,4]; var result = 0; for(var i=0; i

Slide 11

Slide 11 text

Product var array = [1,2,3,4]; var result = 1; for(var i=0; i

Slide 12

Slide 12 text

Abstraction Array.prototype.reduce = function(operation, value) { var result = value; for(var i=0; i

Slide 13

Slide 13 text

Sum function plus(a,b) { return a+b; } var sum = array.reduce(plus, 0);

Slide 14

Slide 14 text

Product function mult(a,b) { return a*b; } var sum = array.reduce(mult, 1);

Slide 15

Slide 15 text

Why?

Slide 16

Slide 16 text

Is any boolean true? function or(a,b) { return a || b; } var anytrue = array.reduce(or, false);

Slide 17

Slide 17 text

Are all booleans true? function and(a,b) { return a && b; } var alltrue = array.reduce(and, true);

Slide 18

Slide 18 text

Are all elements larger than 3? function check(prev,elem) { return prev && (elem > 3); } var allsatisfy = array.reduce(check, true);

Slide 19

Slide 19 text

Are all elements digits? function check(prev,elem) { return prev && (elem >= '0' && elem <= '9'); } var allsatisfy = array.reduce(check, true);

Slide 20

Slide 20 text

Do we have another pattern emerging?

Slide 21

Slide 21 text

More Abstraction! Array.prototype.reduceMap= function(operation, value, modify) { var result = value; for(var i=0; i

Slide 22

Slide 22 text

Are all elements larger than 3? function and(a,b) { return a && b; } function islarger(elem) { return elem > 3; } var alllarger = array.reduceMap(and, false, islarger);

Slide 23

Slide 23 text

Are all elements digits? function and(a,b) { return a && b; } function isdigit(elem) { return elem >= '0' && elem <= '9'; } var alldigits = array.reduceMap(and, false, isdigit);

Slide 24

Slide 24 text

Why ● Easy to understand what's going on ● Cleanly separated “logic” (and and isdigit ) ● Common machinery (reduceMap ) added to Array prototype to be easily reused ● Easy to test functions in isolation

Slide 25

Slide 25 text

But.. ● reduceMap has 3 arguments that are not easy to remember ● It's harder to generalise this pattern. Should we keep on adding arguments to reduce/reduceMap ?

Slide 26

Slide 26 text

We can abstract further Array.prototype.reduceMap = function(operation, value, modify) { ... result = operation(..., modify(...)); ... }

Slide 27

Slide 27 text

2 Arg Function Composition Function.prototype.compose2 = function(func) { return function(a,b) { this(a, func(b)); }.bind(this); }

Slide 28

Slide 28 text

Refactored reduceMap Array.prototype.reduceMap = function(operation, value, modify) { ... result = (operation.compose2(modify))(..., ...); ... }

Slide 29

Slide 29 text

Refactored reduceMap (contd.) Array.prototype.reduceMap = function(operation, value) { ... result = operation(..., ...); ... } When we set operation = operation.compose2(modify)) But that's just reduce again!

Slide 30

Slide 30 text

Are all elements larger than 3? function and(a,b) { return a && b; } function islarger(elem) { return elem > 3; } var alllarger = array.reduce(and.compose2(islarger), false);

Slide 31

Slide 31 text

Are all elements digits? function and(a,b) { return a && b; } function isdigit(elem) { return elem >= '0' && elem <= '9'; } var alldigits = array.reduce(and.compose2(isdigit), false);

Slide 32

Slide 32 text

Much Better ● We removed an extra function (reduceMap) which was actually not needed ● Our existing machinery (reduce) turned out to be powerful enough to support our logic ● We reduced code complexity by introducing another “orthogonal” and “generic” shared vocabulary (compose2)

Slide 33

Slide 33 text

Perfection Perfection is attained not when there is nothing more to add, but when there is nothing more to remove - Antoine de Saint Exupéry

Slide 34

Slide 34 text

We Can Go Deeper ● Generic Currying ● Generic Composition ● Generic “folds”

Slide 35

Slide 35 text

Compose & Curry

Slide 36

Slide 36 text

Curry Function.prototype.curry = function() { return function(arg) { return this.bind(undefined, arg); }.bind(this); } function add(a,b) { return a+b; } var add5 = add.curry()(5); add5(10) // => 15

Slide 37

Slide 37 text

Flip Curry Function.prototype.flip = function() { return function(a) { return function(b) { return this(b)(a); }.bind(this); }.bind(this); }; function minus(a, b) { return a-b; } var minus10 = minus.curry().flip()(10); minus10(15) // => 5

Slide 38

Slide 38 text

Compose Function.prototype.compose = function(f) { return function(a) { return this(f(a)); }.bind(this); } var add15 = add.curry()(5).compose(add.curry()(10)); add15(10) // => 25

Slide 39

Slide 39 text

Are all elements digits? array.reduce(and.curry().compose(isdigit).flip(), false) Because - f.compose2(g) ====> f.curry().compose(g).flip();

Slide 40

Slide 40 text

Thinking of functions as Data Transformers ===> f.curry().compose(g).flip() f(a,b) = f(a, b) f.curry(a)(b) = f(a, b) f.curry().compose(g)(a)(b) = f(g(a), b) f.curry().compose(g).flip()(a)(b) = f(g(b), a)

Slide 41

Slide 41 text

Point of Diminishing Returns ● There's a point when the abstracted approach becomes more cumbersome than the “native” approach ● Recognizing when that point happens will make you a better programmer

Slide 42

Slide 42 text

Recursive Look at reduce Array.prototype.head = function() { return this[0]; } Array.prototype.tail = function() { return this.slice(1); } Array.prototype.reduce = function(operation, value) { if(!this.length) return value; return operation(this.head(), this.tail().reduce(operation, value);); }

Slide 43

Slide 43 text

Any Recursive Data Structure Can Be “Reduced” function Person(name, children) { this.name=name; this.children=children || []; } Person.prototype.reduce = function() …?

Slide 44

Slide 44 text

reducePerson Person.prototype.reduce = function(personop, childrenop, value) { return personop(this.name, reduceChildren(this.children)); function reduceChildren(children) { if(!children.length) return value; return childrenop(children.head().reduce(...), reduceChildren(personOpchildren.tail()); } }

Slide 45

Slide 45 text

Get names of all descendents function append(val, array) { if(typeof val === 'string') val = [val]; return [val].concat(array); } Person.prototype.descendents = function() { return this.reduce(append, append, []); };

Slide 46

Slide 46 text

Uppercase all descendent names function person(name, children) { return new Person(name, children); } function upper(str) { return str.toUpperCase(); } Person.prototype.upperNames = function() { return this.reduce(person.compose(upper), append, []); };

Slide 47

Slide 47 text

Another simple example of Abstraction

Slide 48

Slide 48 text

Find the midpoint // Get the midpoint of range which satisfies the given predicate function midpoint(minx, maxx, f) { for(x = minx; x < maxx; x++) { if(!f(x)) { mid = minx + x; if(mid % 2) mid = (mid-1)/2; else mid = mid/2; return mid; } } } // Find a point on the circle loop: for(cx = 0; cx < width; cx++) for(cy = 0; cy < height; cy++) if(isBlack(cx, cy)) break loop; // X coordinate midpoint(cy, height, isBlack.curry()(cx)); // Y coordinate midpoint(cx, height, isBlack.flip().curry()(cy));

Slide 49

Slide 49 text

Takeaways ● Abstract general higher order functions which can be combined with specialized “logic” ● Immutable Data helps Abstraction ● Think in terms of data being manipulated instead of “actors” that do the manipulation ● Compose simple functions together to build more complex logic

Slide 50

Slide 50 text

Thank You! Questions?