Functionals

Higher-Order Functions

Daniel Jackson

Iteration Abstractions

  • Functionals: functions that take functions
  • Iteration abstractions: roll your own loops
  • Advantages: simplicity & rep independence

Twice

  • A function that applies its argument twice

Happy Times

  • In Ruby, could make this a method: 4.times(hi)

An Iteration Abstraction

  • Roll your own looping constructs!
  • Efficiency? Sadly no tail call optimization in ES6

Applying from to

  • Let's clean up our sum function
  • Use our functional instead of for
  • A bit simpler: some bug chances gone

Iterating over Elements

  • We can do better: iterate over elements, not indexes
  • Note (again) free variable in 'loop body' function
  • Array forEach method works like this

Composing Iteration Abstractions

  • How to build a testing framework
  • Indexing would make this ugly

List Functionals

  • Classic functionals for immutable lists
  • Applied to JavaScript arrays

Signatures

  • map: ([a], (a=>b)) => [b]
  • reduce: ([a], (a, b)) => b, b) => b
  • filter: ([a], (a => bool)) => [a]

Map

  • Apply a function to each element
  • ... and construct a new array from results

Filter

  • Choose elements based on a predicate

Reduce

  • Distribute a function across the elements

Exercise: sum

  • Implement the sum function with a functional

Iterators & Generators

  • A different kind of iteration abstraction
  • Iterator: a protocol with next method
  • Generator: a function that returns more than once

The Iterator Protocol

  • An iterator is an object {next: ...}
  • The next slot holds a function that returns {value: ..., done: ...}
  • Note: tricky to maintain state (more on how this works later)

Using an Iterator (1)

  • Can of course use directly
  • Just exploiting a pattern here

Using an Iterator (2)

  • Special for/of syntax
  • Expects an iterable: object with [Symbol.iterator] slot...
  • ... holding a function that returns an iterator (!)
  • A hassle to make but nice to use

Generators

  • A much easier way to iterate
  • Note * after function keyword
  • Generator yields multiple times in one execution

What Generator Returns

  • Actually returns an iterable object...
  • ... that is also an iterator
  • Iterator slot holds function that returns this

THE END