What is Functional Programming? Let's break down some of its core characteristics, and learn how using these techniques can make you a better programmer.
immutable reference "world" is injected into the function # "add_person" returns a copy of "world" with "person" added to it # the original "world" ref remains safe! world = add_person(world, person)
var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; } var f = compose(negate, square, mult2, add1); f(2); // -> 9 Bring yo’ own composition Javascript
def compose(*args) head, *tail = args head = _procify(head) if args.size <= 2 ->(*xs) { head.(_procify(tail[0]).(*xs)) } else ->(*xs) { head.(compose(*tail)) } end end def _procify(obj) case obj when Symbol method(obj).to_proc else obj.to_proc end end end (mult(5) | add(1) | negate).(3) #=> -16 Bring yo’ own composition Ruby
var values = [1, 2, 3, 4, 5]; var newValues = []; for(var i=0; i < values.length; i++) { newValues.push(square(values[i])); } newValues // -> [1, 4, 9, 16, 25] Map Transforms a list into another list using a function
b }; var values = [1, 2, 3, 4, 5]; var sumOfValues = 0; for(var i=0; i < values.length; i++) { sumOfValues = sum(sumOfValues, values[i]); } sumOfValues // -> 15 Reduce/Fold/Inject “Folds” a list into a single value, using an accumulator
b }; var values = [1, 2, 3, 4, 5]; sumOfValues = values.reduce(sum, 0); // -> 15 Reduce/Fold/Inject “Folds” a list into a single value, using an accumulator
of an expression until its final value is needed • Avoids repetitive evaluation (as in the previous example) • You can potentially construct infinite data structures (Streams say “hi!”)
a list to process it • Because of immutability, laziness and tail-call optimization, recursing tends to be much more performant than in imperative languages