Definition: Used to describe mappings between data (functions). (Can be understood as an abstraction of the operation process)

Learning significance:

  • Functional programming is getting more attention with the popularity of React
  • Vue 3 also began to embrace functional programming
  • Functional programming can discard this
  • Better use of Tree Shaking to filter out useless code during packaging
  • Convenient for testing and parallel processing
  • There are many libraries to help us with functional development: Lodash, underscore, Ramda
// Non-functional
let num1 = 2 
let num2 = 3 
let sum = num1 + num2 

/ / function type
function add (n1, n2) {
    return n1 + n2 
}
let sum = add(2.3)
Copy the code

Front knowledge

  • The function is a first-class citizen
  • Higher-order functions
  • closure

The Function is first-class Function:

  1. Functions can be stored in variables (declarative functions);
  2. Functions can be arguments;
  3. A function can be a return value;
// The method of a function is assigned to another method
const BlogController = {
  index(posts){
    return Views.index(posts)
  }
};
/ / is equivalent to
const BlogController = {
  index:Views.index
};
 
Copy the code

Higher-order Function:

  • You can pass a function as an argument to another function
  • You can treat a function as the return result of another function
    • Function as argument:
// forEach can be used as a parameter: the following is a custom forEach function, fn as a parameter, so the custom forEach function is a higher-order function
function forEach(array,fn){
  for(let value ofarray){ fn(value); }}let arr = [1.2.3.5.8]
forEach(arr,item= > {
  console.log(item)
})
Copy the code
    • Function as the return value:
Since makeFn returns a function, makeFn()() can also be called
function makeFn(){
  let msg = "hello world!"
  return function(){
    console.log(msg); }}let fn1 = makeFn()
fn1()
Copy the code
// Composite case: a function that executes only once
function once(fn){
  let done = false;
  return function(){
    if(! done){ done =true;
      fn.apply(this.arguments)}}}let pay = once(function(money){
  console.log('Paid' + money + '元');
})
pay(1888)
pay(2000)// Will not be executed
Copy the code

Higher-order functions are commonly used

  • forEach
  • map
  • fifilter
  • every
  • some
  • fifind/fifindIndex
  • reduce
  • sort

Closure:

Definition: You can call an inner function of a function in another scope and access members of that function’s scope
// makeFn internal scope extended
function makeFn () { 
    let msg = 'Hello function' 
    return function () { 
        console.log(msg) 
    } 
}
const fn = makeFn() 
fn()

Copy the code
  • The essence of closures is that functions are put on an execution stack at the time of execution and then removed from the execution stack when the function completes execution, but

    Scoped members on the heap cannot be freed because they are referenced externally, so the inner function can still access the members of the outer function

  • Closure cases:

// Call to power the function: the inner function accesses the power argument of the outer function, so the outer function is not released
function makePower(power){
  return function(number) {
    return Math.pow(number,power)
  }
}
let pow2 = makePower(2)
let pow3 = makePower(3)
console.log(pow2(2))/ / print 4
console.log(pow3(3))/ / print 27

// Ask for employee salary
function makeSalary(salary) {
  return function(performance) {
    return salary + performance
  }
}
let sal2 = makeSalary(20000)
let sal3 = makeSalary(30000)
console.log(sal2(2000))/ / print 22000
console.log(sal3(3000))/ / print 33000
Copy the code

Pure functions

Definition: The same input always produces the same output ** without any observable side effects
  • Example: Arrays of slice and splice are pure and impure functions, respectively
  • Slice returns the specified portion of the array without altering the original array
  • Splice operates on an array and returns that array, changing the original array

Currie, (Haskell Brooks Curry)

  • When a function has more than one argument, it is called by passing some of the arguments (the arguments never change), and then returns a new function that takes the rest of the arguments and returns the result
  • Conclusion:

    • Corrification allows us to pass in fewer arguments to a function and get a new function that has memorized some of the fixed arguments

    • This is a kind of ‘cache’ of function parameters

    • Make the function more flexible, make the function smaller granularity

    • You can convert multivariate functions into unary functions, and you can combine functions to produce powerful functions

Function composition

  • Pure functions and Currization are easy to write onion code h(g(f(x)).

    • Take the last element of the array and convert it to uppercase,.toUpper(.first(_.reverse(array)))
  • Function composition allows us to recombine fine-grained functions to generate a new function

  • Compose: For a function that requires multiple functions to compose a final value, the intermediate function can be composed

    The functions of the procedure are merged into one function

    • A function is like a pipeline of data, and a combination of functions connects these pipes, allowing data to pass through multiple pipes to form the final result
    • Function combinations are executed from right to left by default
  • Combinatorics in Lodash: Combinatorics flow() or flowRight(), both of which can combine multiple functions (flflowRight() runs from right to left, more commonly).

  • The combination of functions must satisfy associativity:

    • We can either combine g with H, or f with g, and it’s the same thing
    // Associativity
    let f = compose(f, g, h) 
    let associative = compose(compose(f, g), h) == compose(f, compose(g, h)) // true
    Copy the code

Functor (Functor)

What is a Functor

  • Container: contains values and deformation relations of values (the deformation relations are functions)
  • Functor: a special container implemented by an ordinary object that has a map method that runs a function to manipulate values (deformation relationships)

Functor Functor

class Container { 
    // of static methods that create objects without the new keyword
    static of (value) { 
        return new Container(value) 
    }
    constructor (value) { 
        this._value = value 
    }
    // the map method, passing in the deformation relation, maps each value in the container to another container
    map (fn) { 
        return Container.of(fn(this._value)) 
    } 
}
/ / test
Container.of(3) 
    .map(x= > x + 2) 
    .map(x= > x * x)
Copy the code
  • Conclusion:
    • The operations of functional programming do not operate directly on values, but are performed by functors
    • A functor is an object that implements the Map contract
    • We can think of a functor as a box that encapsulates a value
    • To process the values in the box, we need to pass a value-handling function (pure function) to the box’s Map method, which will process the values
    • The final map method returns a box containing the new value (functor)
Common functors:
  • Maybe functor: can handle external null cases (control side effects within permissible limits)

  • Either functor:

    • Either of the two, similar to if… else… The processing of
    • Exceptions make functions impure, and Either functors can be used for exception handling
  • IO functor:

    • The _value in the IO functor is a function, and we’re treating the function as a value
    • IO functors can store impure actions in _value, delay the execution of the impure operation (lazy execution), and wrap the current operation pure
    • Leave impure operations to the caller
  • Pointed functor:

    • The Conservative functor is a functor that implements the of static method

    • The “of” method is used to avoid using new to create objects. The deeper meaning is that the “of” method is used to put values into context

    • Context (putting values into containers, using maps to process values)

  • Monad functor:

    • The Monad functor is a Pointed functor that can be flattened, IO(IO(x))

    • A functor is a Monad if it has both join and of methods and obeies some laws


Conclusion: all the above content is recorded by hand when learning, no copy and paste, all original, I hope you can bring harvest to your friends, if there are mistakes or questions welcome to leave a message, thank you for reading!


I wish you a bright future in front of the program ape, all the way to the north!