FP 101

github.com/deviousdodo

twitter.com/deviousdodo

Adrian Gheorghe

adrian.gheorghe@gmail.com

What is FP ?

treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data

is so called because its fundamental operation is the application of functions

to arguments

First-class functions

  • arguments to other functions
  • returned from other functions
  • assigned to variables
  • stored in data structures

Higher-order functions

and / or

Return a function as a result

Take one or more functions as arguments

const square = n => n * n;

map(square, [2, 3]);
// [4, 9]

Ramda

__

all, any, none - filter, reject - flatten

curry - chain, compose, map, reduce - tap

  • functions do not mutate their input!
  • all functions are curried by default!

Pure functions

  • no observable side effects
  • returns the same value for the same input

Side effects

  • changing arguments or global state
  • exceptions
  • writing to / reading from a file
  • inserting into a database
  • querying the DOM
  • everything else that's actually useful...
  • understanding and debugging a function with side effects requires knowledge about the context
  • in the presence of side effects, a program's behaviour may depend on history.

Problems with side effects

// Pure or impure?

const changesArgs = s => { s.foo = 'hmm'; };
// Impure: changes arguments
// Pure or impure?

const fileExists = path => File.exists?(path);
// Impure: access to filesystem
// Pure or impure?

const getLocation = () => window.location;
// Impure: global variable
// Pure or impure?

const checkAge = (age) => age >= 18;
// Pure (only call with numbers :) )
// Pure or impure?

const randomResult = n => Math.random() * n;
// Impure: different results for same arguments
// Pure or impure?

const makeRequest = (url) => Ajax.get(url);
// Impure: making a request can have varying results
// Pure or impure?

const requestFn = (url) => () => Ajax.get(url);
// Pure: fullfills both conditions

You can transform impure functions into pure ones by delaying evaluation

Why write pure functions?

  • self contained
  • testable
  • referential transparency
  • concurrency
const square = (n) => n * n;

square(3);

// equivalent to

const square = {
  1: 1,
  2: 4,
  3: 9
};

square[3];

Currying

Calling a function with fewer arguments will return another function that accepts the remainder of the arguments.

const adder = (a, b, c) => a + b + c;

const curriedAdder = curry(adder);

curriedAdder(3, 2, 5) === curriedAdder(3)(2)(5);
const filter = (fn, arr) => arr.filter(fn);
const isEven = n => n % 2 === 0;

const filterEven = arr => filter(isEven, arr);

console.log( filterEven([1, 2, 3]) );
// [ 2 ]
// const filter = (fn, arr) => arr.filter(fn);
const filter = curry((fn, arr) => arr.filter(fn));
const isEven = n => n % 2 === 0;

// const filterEven = arr => filter(isEven, arr);
const filterEven = filter(isEven);

console.log( filterEven([1, 2, 3]) );
// [ 2 ]

Function composition

Combining simple functions to produce more complicated ones.

const incrementSquare = compose(inc, square);

console.log( incrementSquare(3) );
// 12
const squareIncrement = pipe(inc, square);

console.log( squareIncrement(3) );
// 16

Example:

slug generator

const downcase    = (s) => s.toLowerCase();
const keepLetters = (s) => s.replace(/[^a-z]/g, '');

const slug = (words) =>
  join('-', map(keepLetters, map(downcase, words)));

console.log( slug(['Hello', 'World!!!']) );
// hello-world
const downcase    = (s) => s.toLowerCase();
const keepLetters = (s) => s.replace(/[^a-z]/g, '');

// const slug = (words) =>
//   join('-', map(keepLetters, map(downcase, words)));

const slug = compose(
  join('-'), map(keepLetters), map(downcase)
);

console.log( slug(['Hello', 'World!!!']) );
// hello-world
const downcase    = (s) => s.toLowerCase();
const keepLetters = (s) => s.replace(/[^a-z]/g, '');

// const slug = compose(
//  join('-'), map(keepLetters), map(downcase)
// );

const downcaseLetters = compose(keepLetters, downcase);

const slug = compose( join('-'), map(downcaseLetters) );

console.log( slug(['Hello', 'World!!!']) );
// hello-world

program state and statements that change it

expressions that describe the desired result

Imperative programming

Declarative programming

// imperative

const a = [1, 2, 3];
let r = [];

for (let i = 0; i < a.length; i++) {
  r.push(a[i] * a[i]);
}

// declarative

const r = map(square, [1, 2, 3]);
// imperative

function map(fn, arr) {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    result.push( fn(arr[i]) );
  }
  return result;
}

// declarative

function map(fn, arr) {
  if (isEmpty(arr)) return [];
  return concat(
    [ fn(head(arr)) ],
    map(fn, tail(arr))
  );
}

Real-world example

const data = {
  viewer: {
    __dataID__: 'Vmlld2VyOjE=',
    DomainAndProjectName: { // section
      __dataID__: 'UHJvamVjdDoxMzE0ODA=',
      project_url: 'amazon.de', // field
      project_name: 'amazon.de', // field
      project_id: 131480, // field
    },
  },
};

const defaults = { isDirty: false, isValid: true };

const mapFields = value => ({ value, ...defaults });

const mapSections = fields => ({
  fields: map(mapFields, omit(['__dataID__'], fields)),
  ...defaults,
});

const result = {
  ...map(mapSections, omit(['__dataID__'], data.viewer)),
  ...defaults,
};
{
    DomainAndProjectName: {
        fields: {
            project_id: {
                isDirty: false,
                isValid: true,
                value: 131480
            },
            project_name: {
                isDirty: false,
                isValid: true,
                value: "amazon.de"
            },
            project_url: {
                isDirty: false,
                isValid: true,
                value: "amazon.de"
            }
        },
        isDirty: false,
        isValid: true
    },
    isDirty: false,
    isValid: true
}
const defaults = { isDirty: false, isValid: true };

const mapFields = value => ({ value, ...defaults });

const mapSections = fields => ({
  fields: map(mapFields, omit(['__dataID__'], fields)),
  ...defaults,
});

const result = {
  ...map(mapSections, omit(['__dataID__'], data.viewer)),
  ...defaults,
};
const formFlags = { isDirty: false, isValid: true };

const addFlags = value => ({ value, ...formFlags });
const omitData = omit(['__dataID__']);

const mapSections = fields => ({
  fields: map(addFlags, omitData(fields)),
  ...formFlags,
});

const result = {
  ...map(mapSections, omitData(data.viewer)),
  ...formFlags,
};
const formFlags = { isDirty: false, isValid: true };

const addFlagsToField = value => ({ value, ...formFlags });
const addFlagsToSection = fields => ({ fields, ...formFlags });
const addFlagsToObject = merge(formFlags);
const omitData = omit(['__dataID__']);

const mapSections = fields => ({
  fields: map(addFlagToField, omitData(fields)),
  ...formFlags,
});

const result = {
  ...map(mapSections, omitData(data.viewer)),
  ...formFlags,
};
const formFlags = { isDirty: false, isValid: true };

const addFlagsToFields = value => ({ value, ...formFlags });
const addFlagsToSections = fields => ({ fields, ...formFlags });
const addFlagsToObject = merge(formFlags);
const omitData = omit(['__dataID__']);

compose(
  addFlagsToObject,
  map(addFlagsToSections),
  map(compose(map(addFlagsToFields), omitData)),
  omitData,
)(data.viewer);
const formFlags = { isDirty: false, isValid: true };

const addFlagsToField = value => ({ value, ...formFlags });
const addFlagsToSection = fields => ({ fields: omitData(fields), ...formFlags });
const addFlagsToObject = merge(formFlags);
const omitData = omit(['__dataID__']);

compose(
  addFlagsToObject,
  map(addFlagsToSection),
  map(map(addFlagsToField)),
  omitData,
)(data.viewer);
const formFlags = { isDirty: false, isValid: true };

const addFlagsToField = value => ({ value, ...formFlags });
const addFlagsToSection = fields => ({ fields, ...formFlags });
const addFlagsToObject = merge(formFlags);
const omitData = omit(['__dataID__']);

compose(
  addFlagsToObject,
  map(compose(
    addFlagsToSection,
    map(addFlagsToField),
    omitData
  )),
  omitData,
)(data.viewer);

Thanks!

Made with Slides.com