Skip to content

Instantly share code, notes, and snippets.

@mindscratch
Last active December 17, 2021 18:01
Show Gist options
  • Save mindscratch/8263097 to your computer and use it in GitHub Desktop.
Save mindscratch/8263097 to your computer and use it in GitHub Desktop.
functional programming notes

Functional Thinking

Miscellaenous

think about results, not steps

  • First-Class Functions
    • Functions can appear anywhere language primitives can appear.

What Every Hipster Should Know About Functional Programming

  • http://vimeo.com/68331937

  • First-class functions

    • like any other value, they can be passed around
  • Functors

    • a collection of X that can apply a function f: X -> Y over itself to create a collection of Y.
// f is a function that takes a single argument and returns a value
// list is a collection of values to map over
// @return a collection of values
function map(f, list) {
  var newList = [], length = list.length, i;
  for (i = 0; i < length; i++) {
    newList.push(f(list[i]));
  }
  return newList;
}
  • Catamorphism
  • Higher order functions
    • functions can take other functions as arguments
    • functions can create other functions
// this is a the Higher Order Function
// takes a function, f, that takes one argument and returns one value
// @return a function that takes two arguments
function mapReducer(f) {
  return function(a, b) {
    return a.concat(f(b));
  }
}
function caps(s) { return s.toUpperCase(); }
function reduce(f, list, initial) {
  var result = initial;
  for (var i = 0; i < list.length; i++) {
    result = f(result, list[i]);
  }
  return result;
}

reduce(mapReducer(caps), ['orange', 'red', 'blue'], []);
// ['ORANGE', 'RED', 'BLUE']
  • Combinators
    • A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments. Wikipedia
  • Composition
    • combining functions to make new functions
function caps(s) { return s.toUpperCase(); }
function hello(s) { return "Hello " + s; }
// shoutHello demonstrates composition
function shoutHello(f, g) {
  return function(value) {
    return g(f(value));
  }
};
shoutHello(hello, caps)("world"); // HELLO WORLD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment