SlideShare a Scribd company logo
Functional
Programming
An Introduction
2015.05.21
1
> Drew Olson
> Braintree
> github.com/drewolson
2
Things to know
> Ask questions
> node
> babeljs.io
3
Reduce/Map/Filter
in Javascript 4
Without State
Without Mutation
What is functional
programming?
5
What are we going to focus on?
> Immutability
> No state
> Higher-order functions
> Lots of code
6
What aren’t we going to focus
on?
> Types
> Monads
> Being tricky to feel smart
7
Why even care?
> Explicitness
> Concurrency / Parallelism
> Understandability
8
Reduce/Map/Filter
in Javascript 9
Without State
> Without Mutation
10
let a = 1;
a = 2;
console.log(a);
// => 2
// :(
11
let a = 1;
a = 2;
console.log(a);
// => 2
// :(
Enforced via discipline :)
Reduce/Map/Filter
in Javascript 12
> Without State
Without Mutation
13
class Foo
  attr_accessor :bar
  def initialize(bar)
    @bar = bar
  end
  def increment(i)
    i + 1
  end
end
foo = Foo.new(1)
# things happen here
# .
# ..
# ...
# what does this return?
p foo.bar
# what does this return?
p foo.increment(2)
Let’s add some numbers!
14
15
let sumIter = function (n) {
  let sum = 0;
  for (let i = 0; i <= n; i++) {
    sum = sum + i;
  }
  return sum;
}
console.log(sumIter(50));
// => 1275
16
let sumIter = function (n) {
  let sum = 0;
  for (let i = 0; i <= n; i++) {
    sum = sum + i;
  }
  return sum;
}
console.log(sumIter(50));
// => 1275
Recursion!
> Base case
> Recursive call
17
18
let sumRec = function (n) {
  if (n === 0) {
    return 0;
  } else {
    return n + sumRec(n - 1);
  }
}
console.log(sumRec(50));
// => 1275
19
let sumRec = function (n) {
  if (n === 0) {
    return 0;
  } else {
    return n + sumRec(n - 1);
  }
}
console.log(sumRec(50000000));
// => RangeError: Maximum call
stack size exceeded
20
// sumRec(5)
// 1 + sumRec(4)
// 1 + (1 + sumRec(3))
// 1 + (1 + (1 + sumRec(2)))
// 1 + (1 + (1 + (1 + sumRec(1))))
// 1 + (1 + (1 + (1 + (1 + sumRec(0)))))
// 1 + (1 + (1 + (1 + (1 + 0))))
// 1 + (1 + (1 + (1 + 1)))
// 1 + (1 + (1 + 2))
// 1 + (1 + 3)
// 1 + 4
// 5
21
let sumTail = function (n, acc=0) {
  if (n === 0) {
    return acc;
  } else {
    return sumTail(n - 1, acc + n);
  }
}
console.log(sumTail(50000000));
// => 1250000025000000
22
// sumTail(5)
// sumTail(5, 0)
// sumTail(4, 1)
// sumTail(3, 2)
// sumTail(2, 3)
// sumTail(1, 4)
// sumTail(0, 5)
// 5
> Reduce/Map/Filter
in Javascript 23
Without State
Without Mutation
Higher-order functions!
> Functions as values
> Take functions as input
> Return functions
24
25
Higher-order functions!
YOU KNOW THIS!!
26
27
File.open("/tmp/setec_astronomy", "w") do |f|
  # do stuff with f
end
[1, 2, 3].map do |i|
  i + 1
end
# => [2, 3, 4]
28
// take a function as an argument
let callMeMaybe = function (f) {
  if (Math.random() < 0.5) {
    return f();
  } else {
    return undefined;
  }
}
for (var i of [1, 2, 3, 4, 5]) {
  console.log(`Try ${i}`);
  callMeMaybe(function () {
    console.log("I GOT CALLED!");
  });
}
29
Try 1
I GOT CALLED!
Try 2
Try 3
I GOT CALLED!
Try 4
I GOT CALLED!
Try 5
30
// return a function
let incrementor = function (n) {
  return function (i) {
    return i + n;
  }
}
let add1 = incrementor(1);
console.log(add1(2));
// => 3
OK! Let’s implement reduce!
> Tail recursion
> Higher-order functions
> No state
> No mutation
31
32
let coll = [1, 2, 3, 4, 5];
let result = reduce(coll, 0, function (i, sum) {
  return sum + i;
});
console.log(result);
// => 15
33
let reduce = function (coll, acc, fn) {
  if (coll.length === 0) {
    return acc;
  }
  let head = coll[0];
  let rest = coll.slice(1, coll.length);
  let newAcc = fn(head, acc);
  return reduce(rest, newAcc, fn);
}
OK! Let’s implement map!
> ONLY USING REDUCE!!?!??!
34
35
let coll = [1, 2, 3, 4, 5];
let result = map(coll, function (i) {
  return i + 1;
});
console.log(result);
// => [2, 3, 4, 5, 6]
36
let map = function (coll, fn) {
  return reduce(coll, [], function (i, acc) {
    return acc.concat(fn(i));
  });
}
OK! Let’s implement filter!
> ONLY USING REDUCE!!?!??!
> This time less shockingly
revealed!!
37
38
let coll = [1, 2, 3, 4, 5];
let result = filter(coll, function (i) {
  return i < 4;
});
console.log(result);
// => [1, 2, 3]
39
let filter = function (coll, fn) {
  return reduce(coll, [], function (i, acc) {
    if (fn(i)) {
      return acc.concat(i);
    } else {
      return acc;
    }
  });
}
Reduce/Map/Filter
in Javascript 40
Without State
Without Mutation
41
Things to check out
> Functional Javascript (book)
> The Little Schemer (book)
> Elixir (language)
42
braintreepayments.com
End Slide_
43
Thanks!
Questions?

More Related Content

PDF
Go Says WAT?
PPTX
Luis Atencio on RxJS
PPTX
Grokking TechTalk #16: Maybe functor in javascript
PDF
RxJS 5 in Depth
PPTX
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
PDF
Meta-objective Lisp @名古屋 Reject 会議
PPTX
Anti patterns
PDF
rx.js make async programming simpler
Go Says WAT?
Luis Atencio on RxJS
Grokking TechTalk #16: Maybe functor in javascript
RxJS 5 in Depth
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
Meta-objective Lisp @名古屋 Reject 会議
Anti patterns
rx.js make async programming simpler

What's hot (20)

PDF
Full Stack Clojure
PDF
ClojureScript for the web
PPTX
Lambda выражения и Java 8
PDF
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
PDF
Reactive Programming Patterns with RxSwift
PDF
Transition graph using free monads and existentials
PDF
ClojureScript loves React, DomCode May 26 2015
PDF
ClojureScript - A functional Lisp for the browser
PDF
PDF
Cascadia.js: Don't Cross the Streams
PDF
The Ring programming language version 1.6 book - Part 81 of 189
PDF
Reactive Programming with RxSwift
PDF
Introduction kot iin
PDF
Functional Reactive Programming / Compositional Event Systems
PDF
Miracle of std lib
PDF
Reactive programming with RxSwift
PDF
Db2 cheat sheet for development
PDF
ECMAScript 2015 Tips & Traps
PDF
Pivorak Clojure by Dmytro Bignyak
PDF
Gogo shell
Full Stack Clojure
ClojureScript for the web
Lambda выражения и Java 8
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Reactive Programming Patterns with RxSwift
Transition graph using free monads and existentials
ClojureScript loves React, DomCode May 26 2015
ClojureScript - A functional Lisp for the browser
Cascadia.js: Don't Cross the Streams
The Ring programming language version 1.6 book - Part 81 of 189
Reactive Programming with RxSwift
Introduction kot iin
Functional Reactive Programming / Compositional Event Systems
Miracle of std lib
Reactive programming with RxSwift
Db2 cheat sheet for development
ECMAScript 2015 Tips & Traps
Pivorak Clojure by Dmytro Bignyak
Gogo shell
Ad

Viewers also liked (12)

PDF
SPANISH PROJECT FOR GOOD GRADE
PPT
Michael Polombo | Delicious Burgers
PDF
Georgia Truck Accident Attorney
PPTX
for Gca
PDF
Chicago Elixir - Elixir Intro
PPTX
Question 2
PPTX
Human chimp skeleton
PPTX
Harry brown analysis
PDF
Composable Queries with Ecto
PPTX
Web series horror pitch
PDF
#GivingTuesday is Over, Now What?
PPTX
Importance of Quality Management Systems ISO 9001
SPANISH PROJECT FOR GOOD GRADE
Michael Polombo | Delicious Burgers
Georgia Truck Accident Attorney
for Gca
Chicago Elixir - Elixir Intro
Question 2
Human chimp skeleton
Harry brown analysis
Composable Queries with Ecto
Web series horror pitch
#GivingTuesday is Over, Now What?
Importance of Quality Management Systems ISO 9001
Ad

Similar to Functional Programming: An Introduction (20)

PPTX
Functional Programming in Javascript - IL Tech Talks week
PPTX
An Introduction to Functional Programming with Javascript
PDF
Map, Reduce and Filter in Swift
PPTX
A Skeptics guide to functional style javascript
PPTX
Functionnal programming
PDF
379008-rc217-functionalprogramming
PDF
JSDC 2014 - functional java script, why or why not
PDF
Functional programing in Javascript (lite intro)
PPTX
Functional Programming
PDF
A taste of Functional Programming
PDF
Functional Programming in JavaScript
PPTX
Functional programming
PDF
Functional Programming with Javascript
PPTX
ECMA5 and ES6 Promises
PPTX
Functional Programming in JavaScript by Luis Atencio
PDF
Christian Gill ''Functional programming for the people''
PDF
7 Habits For a More Functional Swift
PPTX
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
PDF
Functional programming
PPTX
Declarative JavaScript concepts and implemetation
Functional Programming in Javascript - IL Tech Talks week
An Introduction to Functional Programming with Javascript
Map, Reduce and Filter in Swift
A Skeptics guide to functional style javascript
Functionnal programming
379008-rc217-functionalprogramming
JSDC 2014 - functional java script, why or why not
Functional programing in Javascript (lite intro)
Functional Programming
A taste of Functional Programming
Functional Programming in JavaScript
Functional programming
Functional Programming with Javascript
ECMA5 and ES6 Promises
Functional Programming in JavaScript by Luis Atencio
Christian Gill ''Functional programming for the people''
7 Habits For a More Functional Swift
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
Functional programming
Declarative JavaScript concepts and implemetation

Recently uploaded (20)

PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PDF
Digital Strategies for Manufacturing Companies
PPTX
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
PDF
System and Network Administration Chapter 2
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
PPTX
Transform Your Business with a Software ERP System
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PDF
top salesforce developer skills in 2025.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Build Multi-agent using Agent Development Kit
PPTX
ai tools demonstartion for schools and inter college
PPTX
Presentation of Computer CLASS 2 .pptx
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PDF
Become an Agentblazer Champion Challenge Kickoff
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Digital Strategies for Manufacturing Companies
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
System and Network Administration Chapter 2
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Online Work Permit System for Fast Permit Processing
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
Transform Your Business with a Software ERP System
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
top salesforce developer skills in 2025.pdf
PTS Company Brochure 2025 (1).pdf.......
ManageIQ - Sprint 268 Review - Slide Deck
Softaken Excel to vCard Converter Software.pdf
Build Multi-agent using Agent Development Kit
ai tools demonstartion for schools and inter college
Presentation of Computer CLASS 2 .pptx
The Role of Automation and AI in EHS Management for Data Centers.pdf
Become an Agentblazer Champion Challenge Kickoff

Functional Programming: An Introduction