Functional Programming

What is functional programming ?

What is functional programming

console.log(`hello, {name}`)

// I thik the functional programming
function hello(name) {
  console.log(`hello, {name}`)
}

hello('Neo')

What is functional programming

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

What is functional programming

Functional programming is declarative rather than imperative, and application state flows through pure functions.

Functional programming

  • Pure function
  • Function composition
  • Avoid shared state
  • Avoid mutating state
  • Avoid side effects

Pure function

  • Given the same input, will always return the same output
  • No side effects

Pure function

const x = {
  val: 2
}
const add = (x) => x.val += 1; //x.val = 3
const mcl = (x) => x.val *= 2;

add(x) //x.val = 3
mcl(x) //x.val = 6

add(x) //x.val = 7
mcl(x) //x.val = 14

const y = {
  val: 2
}

const addFP = (y) => Object.assign({}, y, { val: y.val + 1})
const mclFP = (y) => Object.assign({}, y, { val: y.val * 2})

mclFP(addFP(y)) //y.val = 6
mclFP(addFP(y)) //y.val = 6

Pure function

let list = [1,2,3,4,5]

// non-pure function
list.splice(0,3)
//=> [1,2,3]

list.splice(0,3)
//=> [4,5]

list.splice(0,3)
//=> []


// pure function
list.slice(0,3)
//=> [1,2,3]

list.slice(0,3)
//=> [1,2,3]

list.slice(0,3)
//=> [1,2,3]

Pure function

// non-pure function
const minVersion = 630

var checkVersion = (version) => version >= minVersion


// pure function
var checkVersion = (version) => {
  const minVersion = 630
  return version >= minVersion
}

Function composition

Function composition is the process of combining two or more functions in order to produce a new function or perform some computation.

Function composition

const compose = (f,g) => {
  return (x) => f(g(x))
}
const toUpperCase = (x) => x.toUpperCase()
const appendString = (x) => `${x}'Hello, Neo !`
const printString = compose(appendString, toUpperCase);

printString("Hello world!");

Function composition - Curry

const add = (x) => {
  return (y) => x + y
}

const increment = add(1);
const addTen = add(10);

increment(2);
// 3

addTen(2);
// 12

 Avoid shared state

immutable data structures and pure calculations to derive new data from existing data.

Avoid mutating state - Immutable

Base functional programming

  • forEach
  • Map
  • Filter
  • Reduce

deck

By Neo Hsu

deck

  • 623