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

What is functional programming?
Why should we learn it?
What features are necessary to support it?
What p...
What is Functional Programming?

A programming paradigm/style where the
basic unit of abstraction is the function
Motivation for Learning
•
•
•
•
•

Become a better programmer
Be prepared for future technologies
Understand KVDB
Avoid de...
FP Ciriculum
• Tuples
• Lists
• Handling SideEffects
• Closure
• Nested Functions
• First-Class
Functions
• Higher-Order
F...
FP Ciriculum
• Tuples
•
• Lists
•
• Handling Side•
Effects
• Lexical Closure •
• Nested Functions •
• First-Class
•
Functi...
Functional Style
Imperative/OO

Functional

Tell the computer what to do

Describe what you want done

Abstraction via obj...
Mandatory FP Features
•
•
•
•

Anonymous functions / function literals (λ)
First-class functions
Lexical closure
Higher-or...
Why Javascript?
•
•
•
•

Fully supports the functional paradigm
Javascript not well understood by users
Benefits of FP ali...
Anonymous Functions /
Function Literals

x = function(a) {
// ... do something with ‘a’ ...
}
// typeof x === ‘function’
First-Class Functions
var mathFuncs =
function(a)
function(b)
function(c)
];

[
{ return a * 2 },
{ return b * b },
{ retu...
Lexical Closure
var complete = false;
function doSomethingOnce() {
if (!complete) {
// ... something
complete = 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);
t...
Higher-Order Functions
function map(array, func) {
var result = [];
for (var i = 0; i < array.length; i++) {
result[i] = f...
Fold/Reduce
var sum = fold(
0,
[1, 2, 3, 4],
function(value, item) {
return value + item;
}
); // sum === 10
Fold/Reduce
Parameters to function
Value
Item
0 (initial) 1
1
2
3
3
6
4

Returns
0+1=1
1+2=3
3+3=6
6 + 4 = 10

Remains
[2,...
Fold/Reduce
function fold(init, array, folder) {
var result = init;
for (var i = 0; i < array.length; i++) {
var curr = ar...
Map as Fold
function map(array, func) {
return foldLeft([], array,
function(a, x) {
a.push(func(x));
return a;
});
}
var a...
Map as Fold
Parameters to function
Value
Item
[] (initial)
1
[10]
2
[10, 20]
3

Returns
[10]
[10, 20]
[10, 20, 30]

Remain...
Data Encapsulation through Closure
function makeCounter() {
var i = 0;
return function() {
i++;
return i;
}
}
var counter ...
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) {
con...
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...
Underscore.js Chaining
_.chain([1, 2, 3, 4, 5])
.map(function(n) { return n * n })
.filter(function(n) { return n % 2 === ...
Next Steps
• Functional Javascript:
– http://shop.oreilly.com/product/0636920028857.do

• Literate underscore.js code:
– h...
Questions?
Upcoming SlideShare
Loading in …5
×

An Introduction to Functional Programming with Javascript

797 views
639 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
797
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
22
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • associated with esoteric languages like Haskell, Scheme, Erlang, etc.Those are functional languages, but they aren’t the only road to functional programming.FP is a fundamental style (or paradigm) enabled by language features.Just as oo-languages use objects as the basic unit of abstraction, usually through classes.Just as we can encapsulate behaviour and data behind an object’s interface, using a functional language we can encapsulate behaviour and data in functions. Functions can also be treated as data.
  • So what do we get by thinking in functions?Better: Functional paradigm can be applied to almost any language. E.g. CollectionUtil at MBC. LINQ in C# comes up a lot. Libraries available for non-functional languages.If you are working on a non-trivial web application, you should be using a functional programming. Learning FP will make you a better Javascript programmerFuture: Some people think that functional programming is going to be the next big paradigm, and the jump is ever bigger than the one from imperative to OO. So learning FP now will prepare you for that scenario.Kvdb: KVDB, the technology behind Protunity, uses Scala, a functional language.Defects: because functional programs tend to be composed of small functions, may of them built in, you leave fewer places for bugs to hide.
  • L&amp;L part of a series of FP topics. Sorted by strength of headache you might get by looking at them.
  • We’re starting out with these introductary topics, and skipping a few because Javascript either doesn’t directly support them, such as in the case oftuples and lists (JS only has arrays), and we only have an hour anyway.
  • Aside from features, what do programs written in this style look like?
  • What features must a language have to support programming in a functional style?Function literals: shorthand for creating anonymous or named function values.First-class: functions are just regular values. Anywhere regular values or expressions are allowed, functions can appear.Lexical closure: functions have access to surrounding scopes, even after it has finished executing.Higher-order: can be passed into and returned from other functionsWhen all of these features combine, you can do some really powerful stuff with functions.
  • Functions are one of the things JS gets mostly right- history of JS: management said “make it look like Java or C” and Brendan Eich did so, but thankfully smuggled in FPJS is a functional programming language that almost all of us are forced to use.Not well understood: most of us learned from fragments. Find code snippets on stackoverflow that do what we wanted. - lots of frustration comes from broken JS features, but lots more comes from cross-browser issues with the DOM and CSS. Functions work consistently across browsers.Lots of Javascript out there is crap. Better to learn the principles than go looking online for examples.JS users’ needs: - maintainability: FP helps to abstract behaviour out into reusable chunks, which form libraries like underscore/lo-dashFunctional programming (especially via common libraries) helps you write understandable codeGuide: give programmers a task and a language and they generally say “okay, I know how I would implement this.” Not so with JS. There are no self-professed “Javascript programmers”, which is a shame.
  • Lets you package up some code into a function and use it anywhere an expression might appear.
  • Builds on the idea of a function literal: functions can be treated like data, stuffed into arrays, etc. and consistently invoked at any time.Functions are treated like any other values in the language. Especially true in Javascript, the language is based heavily on functions. Get sick of typing function all the time…Useful in building things like lists of event handlers (in case you wanted to sidestep the existing event model),
  • Parens in red denote the scope of the function, but it can access ‘complete’ outside of it.The function is packaged up along with its environment, even after those variables have gone out of scope.
  • Here’s where everything comes together and we get to build what are called higher-order functions:Defn: A function that either takes a function as a parameter or returns a function.Start with the first situation: function as parameter
  • Example of returning a function from a function. We also make use of a closure in the inner function (num).multiplyBy returns a new function that multiplies its argument by a specific number.
  • Let’s put these two together to create a new function: map. Map is common to many functional languages.Result is powerful, abstractions like map or multiplyBy that are easier to rid of bugs.
  • Something a bit more powerful: fold, also known as reduce, takes an array and reduces it to a single value.Start with an initial value (e.g. 0), then apply the function to everything in the array and pass in the last returned value, then return the result.Comes in two flavours: left and right. Determines the order (left is forward, right is backward) in which the items are visited.
  • Steps during the fold.
  • Another way to look at fold.
  • Another usage of fold.
  • Steps during the fold.
  • This might make experienced functional programmers cringe a bit, but here’s a neat trick that turns out to be really useful inJavascript.
  • Just like the methodsjQuery provides, you wouldn’t want to write all of these utilities yourself. Adds functional programming support to Javascript without breaking anything else.
  • _ : a global object
  • Because it doesn’t modify the base array object, you can use “chain” to wrap an array and invoke multiple underscore functions on it.
  • Chain: wraps the arrayMap: squaresFilter: predicate filters out oddsReduce: Alias for fold, sums up the
  • Here’s how it would appear normally. There’s a lot going on but it’s still compact and readable.
  • An Introduction to Functional Programming with Javascript

    1. 1. An Introduction to Functional Programming With Javascript, the world’s most popular (functional) language
    2. 2. 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
    3. 3. What is Functional Programming? A programming paradigm/style where the basic unit of abstraction is the function
    4. 4. Motivation for Learning • • • • • Become a better programmer Be prepared for future technologies Understand KVDB Avoid defects Write clearer code
    5. 5. FP Ciriculum • Tuples • Lists • Handling SideEffects • 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
    6. 6. 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
    7. 7. Functional Style Imperative/OO Functional Tell the computer what to do Describe what you want done Abstraction via objects/ data structures Abstraction via functions Re-use via classes/inheritence Re-use via composition Iteration/looping Recursion function 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); }
    8. 8. Mandatory FP Features • • • • Anonymous functions / function literals (λ) First-class functions Lexical closure Higher-order functions
    9. 9. 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
    10. 10. Anonymous Functions / Function Literals x = function(a) { // ... do something with ‘a’ ... } // typeof x === ‘function’
    11. 11. First-Class Functions var mathFuncs = function(a) function(b) function(c) ]; [ { return a * 2 }, { return b * b }, { return c + 2 } mathFuncs[1](3); // => 9
    12. 12. Lexical Closure var complete = false; function doSomethingOnce() { if (!complete) { // ... something complete = true; } }
    13. 13. Higher-Order Functions function doTwice(action) { action(); action(); } doTwice(function() { console.log('called!'); })
    14. 14. Higher-Order Functions function multiplyBy(num) { return function(i) { return i * num; } } var times10 = multiplyBy(10); times10(5); // 50
    15. 15. 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));
    16. 16. Fold/Reduce var sum = fold( 0, [1, 2, 3, 4], function(value, item) { return value + item; } ); // sum === 10
    17. 17. Fold/Reduce Parameters to function Value Item 0 (initial) 1 1 2 3 3 6 4 Returns 0+1=1 1+2=3 3+3=6 6 + 4 = 10 Remains [2, 3, 4] [3, 4] [4] []
    18. 18. 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; }
    19. 19. 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));
    20. 20. Map as Fold Parameters to function Value Item [] (initial) 1 [10] 2 [10, 20] 3 Returns [10] [10, 20] [10, 20, 30] Remains [2, 3] [3] []
    21. 21. Data Encapsulation through Closure function makeCounter() { var i = 0; return function() { i++; return i; } } var counter = makeCounter(); counter(); // 1 counter(); // 2
    22. 22. Underscore.js “... the tie to go along with jQuery's tux, and Backbone.js's suspenders.” -- http://underscorejs.org
    23. 23. Underscore.js Basics e.g.: _.<method>(<array>, <function>) var array = ["hello", "world"]; _.each(array, function(x) { console.log(x); });
    24. 24. Underscore.js Chaining e.g.: _.chain(<array>) .<method1>(<function>) .<method2>(<function>) .value();
    25. 25. 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
    26. 26. 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();
    27. 27. 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
    28. 28. Questions?

    ×