an introduction to functional programming with javascript

28
An Introduction to Functional Programming With Javascript, the world’s most popular (functional) language

Upload: doug-sparling

Post on 06-May-2015

382 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: An Introduction to Functional Programming with Javascript

An Introduction toFunctional Programming

With Javascript, the world’s mostpopular (functional) language

Page 2: An Introduction to Functional Programming with Javascript

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

Page 3: An Introduction to Functional Programming with Javascript

What is Functional Programming?

A programming paradigm/style where thebasic unit of abstraction is the function

Page 4: An Introduction to Functional Programming with Javascript

Motivation for Learning

• Become a better programmer• Be prepared for future technologies• Understand KVDB• Avoid defects• Write clearer code

Page 5: An Introduction to Functional Programming with Javascript

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

Page 6: An Introduction to Functional Programming with Javascript

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

Page 7: An Introduction to Functional Programming with Javascript

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);}

Page 8: An Introduction to Functional Programming with Javascript

Mandatory FP Features

• Anonymous functions / function literals (λ)• First-class functions• Lexical closure• Higher-order functions

Page 9: An Introduction to Functional Programming with Javascript

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

Page 10: An Introduction to Functional Programming with Javascript

Anonymous Functions /Function Literals

x = function(a) {// ... do something with ‘a’ ...

}

// typeof x === ‘function’

Page 11: An Introduction to Functional Programming with Javascript

First-Class Functions

var mathFuncs = [ function(a) { return a * 2 }, function(b) { return b * b }, function(c) { return c + 2 }];

mathFuncs[1](3); // => 9

Page 12: An Introduction to Functional Programming with Javascript

Lexical Closure

var complete = false;function doSomethingOnce() {

if (!complete) {// ... somethingcomplete = true;

}}

Page 13: An Introduction to Functional Programming with Javascript

Higher-Order Functions

function doTwice(action) {action();action();

}

doTwice(function() {console.log('called!');

})

Page 14: An Introduction to Functional Programming with Javascript

Higher-Order Functions

function multiplyBy(num) {return function(i) {

return i * num; }}

var times10 = multiplyBy(10);times10(5); // 50

Page 15: An Introduction to Functional Programming with Javascript

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));

Page 16: An Introduction to Functional Programming with Javascript

Fold/Reduce

var sum = fold( 0, [1, 2, 3, 4], function(value, item) { return value + item; }); // sum === 10

Page 17: An Introduction to Functional Programming with Javascript

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 []

Page 18: An Introduction to Functional Programming with Javascript

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;}

Page 19: An Introduction to Functional Programming with Javascript

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));

Page 20: An Introduction to Functional Programming with Javascript

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] []

Page 21: An Introduction to Functional Programming with Javascript

Data Encapsulation through Closure

function makeCounter() {var i = 0;return function() {

i++;return i;

}}

var counter = makeCounter();counter(); // 1counter(); // 2

Page 22: An Introduction to Functional Programming with Javascript

Underscore.js

“... the tie to go along with jQuery's tux, and Backbone.js's suspenders.”

-- http://underscorejs.org

Page 23: An Introduction to Functional Programming with Javascript

Underscore.js Basics

e.g.: _.<method>(<array>, <function>)

var array = ["hello", "world"];_.each(array, function(x) { console.log(x);});

Page 24: An Introduction to Functional Programming with Javascript

Underscore.js Chaining

e.g.: _.chain(<array>) .<method1>(<function>) .<method2>(<function>) .value();

Page 25: An Introduction to Functional Programming with Javascript

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

Page 26: An Introduction to Functional Programming with Javascript

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();

Page 27: An Introduction to Functional Programming with Javascript

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

Page 28: An Introduction to Functional Programming with Javascript

Questions?