An Introduction to Functional Programming with Javascript
-
Upload
doug-sparling -
Category
Technology
-
view
382 -
download
0
Transcript of An Introduction to Functional Programming with Javascript
An Introduction toFunctional Programming
With Javascript, the world’s mostpopular (functional) language
Outline
• What is functional programming?• Why should we learn it?• What features are necessary to support it?• What patterns are common?– Underscore/Lo-Dash
• Examples• Future topics
What is Functional Programming?
A programming paradigm/style where thebasic unit of abstraction is the function
Motivation for Learning
• Become a better programmer• Be prepared for future technologies• Understand KVDB• Avoid defects• Write clearer code
FP Ciriculum
• Tuples• Lists• Handling Side-
Effects• Closure• Nested Functions• First-Class
Functions• Higher-Order
Functions• Anonymous
Functions• Tail Recursion• Folding• Partially-Applied
Functions• Immutability• Memoization• Function
Composition• Pattern Matching• Currying
• Generics• Lazy Evaluation• Delimited
Continuations• Lambda Calculus• Higher Kinds• Monads• Monad
Comprehension• State-Passing Style
FP Ciriculum
• Tuples• Lists• Handling Side-
Effects• Lexical Closure• Nested Functions• First-Class
Functions• Higher-Order
Functions• Anonymous/
Literal Functions• Tail Recursion• Folding• Partially-Applied
Functions• Immutability• Memoization• Function
Composition• Pattern Matching• Currying
• Generics• Lazy Evaluation• Delimited
Continuations• Lambda Calculus• Higher Kinds• Monads• Monad
Comprehension• State-Passing Style
Functional StyleImperative/OO FunctionalTell the computer what to do Describe what you want doneAbstraction via objects/data structures
Abstraction via functions
Re-use via classes/inheritence Re-use via compositionIteration/looping Recursionfunction factorial(n) {
var result = 1;while (n > 1) {
result *= n;n--;
}return result;
}
function factorial(n) { if (n < 2) return 1; else return n * factorial(n - 1);}
Mandatory FP Features
• Anonymous functions / function literals (λ)• First-class functions• Lexical closure• Higher-order functions
Why Javascript?
• Fully supports the functional paradigm• Javascript not well understood by users• Benefits of FP align well with JS users’ needs• Guide us down a better path
Anonymous Functions /Function Literals
x = function(a) {// ... do something with ‘a’ ...
}
// typeof x === ‘function’
First-Class Functions
var mathFuncs = [ function(a) { return a * 2 }, function(b) { return b * b }, function(c) { return c + 2 }];
mathFuncs[1](3); // => 9
Lexical Closure
var complete = false;function doSomethingOnce() {
if (!complete) {// ... somethingcomplete = true;
}}
Higher-Order Functions
function doTwice(action) {action();action();
}
doTwice(function() {console.log('called!');
})
Higher-Order Functions
function multiplyBy(num) {return function(i) {
return i * num; }}
var times10 = multiplyBy(10);times10(5); // 50
Higher-Order Functions
function map(array, func) { var result = []; for (var i = 0; i < array.length; i++) { result[i] = func(array[i]); } return result;}
function multiplyBy(num) { ... }
var array = map([1,2,3], multiplyBy(10));
Fold/Reduce
var sum = fold( 0, [1, 2, 3, 4], function(value, item) { return value + item; }); // sum === 10
Fold/Reduce
Parameters to functionValue Item Returns Remains0 (initial) 1 0 + 1 = 1 [2, 3, 4]1 2 1 + 2 = 3 [3, 4]3 3 3 + 3 = 6 [4]6 4 6 + 4 = 10 []
Fold/Reduce
function fold(init, array, folder) { var result = init; for (var i = 0; i < array.length; i++) { var curr = array[i]; result = folder(result, curr); } return result;}
Map as Fold
function map(array, func) { return foldLeft([], array, function(a, x) { a.push(func(x)); return a; });}
var a = map([1,2,3], multiplyBy(10));
Map as Fold
Parameters to functionValue Item Returns Remains [] (initial) 1 [10] [2, 3][10] 2 [10, 20] [3][10, 20] 3 [10, 20, 30] []
Data Encapsulation through Closure
function makeCounter() {var i = 0;return function() {
i++;return i;
}}
var counter = makeCounter();counter(); // 1counter(); // 2
Underscore.js
“... the tie to go along with jQuery's tux, and Backbone.js's suspenders.”
-- http://underscorejs.org
Underscore.js Basics
e.g.: _.<method>(<array>, <function>)
var array = ["hello", "world"];_.each(array, function(x) { console.log(x);});
Underscore.js Chaining
e.g.: _.chain(<array>) .<method1>(<function>) .<method2>(<function>) .value();
Underscore.js Chaining_.chain([1, 2, 3, 4, 5])
.map(function(n) { return n * n }) // [1, 4, 9, 16, 25]
.filter(function(n) { return n % 2 === 0 }) // [4, 16]
.reduce(function(t, n) { return t + n }, 0) // [20]
.value(); // 20
Underscore.js Chaining
_.chain([1, 2, 3, 4, 5]) .map(function(n) { return n * n }) .filter(function(n) { return n % 2 === 0 }) .reduce(function(t, n) { return t + n }, 0) .value();
Next Steps
• Functional Javascript:– http://shop.oreilly.com/product/0636920028857.do
• Literate underscore.js code:– http://underscorejs.org/docs/underscore.html
• When you get bored with underscore:– http://lodash.com/
• When something doesn’t make sense:– JavaScript: The Good Parts
Questions?