“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Share an essay about functional programming before feeling is not in place, there are a lot of the key points in the functional programming and did not involve, and functional programming is learning is a kind of thought, we’re not imitate or derivative, and need our methodology or through learning and thinking the thoughts into our code, Becoming helps us solve the practical problems around us.

What is functional programming

  • It’s not new, functional programming has been around since the 50-60s
  • Not a language, certainly not a language, just a programming style
  • Neither imperative nor object-oriented programming, javascript can also be viewed as a functional programming language
  • Not a perfect solution to every problem
  • Not difficult

What is functional programming

  • invariance
  • Higher-order functions, that is, functions that can be passed as variables and arguments to a function, and functions that can be used as return values from another function
  • There are no states in the function, that is, there are no states inside the function, because different states result in different outputs from the same input
  • Reference transparency, which means that the output of the function is deterministic, means that the function is easy to test
  • recursive
  • Pattern recognition
  • stateless
  • Mondas

Which languages are good for functional programming

  • Functional programming languages (Haskell, Erlang, Elm, etc.)
  • .net – c# F#, etc
  • Javascript

When is functional programming appropriate

  • The data processing
  • Parallel system
  • serverless

In what situations is functional programming not appropriate

  • UI
  • External interaction
  • IO
  • High performance system

Why functional programming

  • Introduction to the
  • readability
  • Easy to test
  • Support parallel
  • robustness
  • interesting

Going currying

Currying is a process in functional programming that transforms a function with multiple arguments into a series of nested functions that take only one argument, and every time a function is returned, the argument that the function takes is the next argument.

For example, currying, which translates as currying, is a word that is literally translated according to its pronunciation. It means curry in the dictionary. The dictionary also gives the meaning of adding fat, but that’s not necessarily the case, but also refers to storing food

Return function will hold to perform this function when accepted parameters, then like peeling Onions, know all the parameters are used to, before not to the last parameter, the other parameters are formed by the “live” to accept this parameter function of closure, when to return to the last function and implement, all parameters would be used, So Currying is a procedure in functional programming. For some abstract concepts with brief language to explain clearly, it does need to have a certain language foundation, here is not much to say, we directly on the code. I think with code examples, you’ll get a better idea.

function fn(a,b){}

function multiply(a,b,c){
    return a * b * c;
}

multiply(1.2.3);
Copy the code

The function multiply takes three arguments and returns the result as the function’s return value. Next explains how to use currying to allocate arguments to a series of adjustment functions, each of which takes only one argument.

function curried_multiply(a){
    return (b) = > {
        return (c) = >{
            return a * b * c;
        }
    }
}

curried_multiply(1) (2) (3);
Copy the code

The multiply(1,2,3) function call now becomes multiply(1)(2)(3) multiple function calls. It’s taking a function and turning it into a series of functions. To get the multiplication of the numbers 1, 2, and 3, the parameter values are passed one after the other, and each parameter value can be used by the subsequent function.

const mul1 = curried_multiply(1);
const mul2 = mul1(2);
const result = mul2(3);
console.log(result); / / 6
Copy the code

Now to explain in more detail, you can skip this if you get bored and pass 1 to the curried_multiply function

return (b) = > {
        return (c) = > {
            return a * b * c
        }
    }
Copy the code

Partial functions and currying

function add(a){
    return (b) = > a + b
}

const add2 = add(2)

res = add2(3);
console.log(res)
Copy the code
const githubFavicon = buildUri('https'.'github.com'.'favicon.ico')
const githubFavicon =  buildHttpsUri('github.com'.'favicon.ico')
Copy the code

Since most sites start with HTTPS, typing · HTTPS every time for the buildUri function seems like a bit of repetitive work. But if hardcoded like buildHttpsUri, it’s not so elegant to drive. Now, we can use partial functions to solve the real problem.

function buildUri(baseUrl){
  return function(website,path){
    //}}Copy the code

The application of currying

With the Redux JavaScript library, the Reason syntax extension and toolchain, and the Cycle JavaScript framework all clearly using functional programming, functional programming is becoming more and more important in the JavaScript language. Two important ideas that come from functional thinking are currying. Take a look at using currying in practice next.

Write small code modules that can be easily reused and configured

Functions can be used to store state or policies, such as sales strategies, that use the same sales strategy for multiple items

function discount(price, discount) {
    return price * discount
}
Copy the code
const price = discount(500.0.10);
const price = discount(50.0.10);
const price = discount(300.0.10);
Copy the code

As you can see from the above code, although the prices of the items are different, these items have the same discount rate in the promotion.

function discount(discount) {
    return (price) = > {
        returnprice * discount; }}const tenPercentDiscount = discount(0.1);
Copy the code

Avoid calling functions frequently with arguments of the same value

Let’s define the function volume to take three parameters l, w and h, which are length, width and height respectively, and then calculate the volume

function volume(l, w, h) {
    return l * w * h;
}
Copy the code

So even though we’re calculating the volume here, it’s 100 for the height, which means we’re calling the function with the same argument

volume(200.30.100) // 2003000l
volume(32.45.100); //144000l
volume(2322.232.100) // 53870400l
Copy the code
function volume(h) {
    return (w) = > {
        return (l) = > {
            return l * w * h
        }
    }
}
Copy the code

Define a specific function hCylinderHeight for the cache height so that you can avoid calling a function frequently with the same parameters.

const hCylinderHeight = volume(100);
hCylinderHeight(200) (30); / / 600000 l
hCylinderHeight(2322) (232); // 53,870,400l
Copy the code

The common form of Currying

function curry(fn, ... args) {
    return (. _arg) = > {
        returnfn(... args, ... _arg); }}Copy the code
function curry(func) {

  return function curried(. args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return function(. args2) {
        return curried.apply(this, args.concat(args2)); }}}; }Copy the code
function curry(func) {

    return function curried(. args) {
      if (args.length >= func.length) {
        return func.apply(this, args);
      } else {
        return function(. args2) {
          return curried.apply(this, args.concat(args2)); }}}; }function sum(a, b, c) {
    return a + b + c;
  }
  
  let curriedSum = curry(sum);
  
  console.log( curriedSum(1.2.3));// 6, the normal form of every currying function
  console.log( curriedSum(1) (2.3));// 6, partial currying
  console.log( curriedSum(1) (2) (3));// 6, completely curring
Copy the code

conclusion

In JavaScript, currying is implemented based on closures, with the ability to preserve the state of functions that have been executed, giving us the ability to create factory functions that can add specific values to their arguments.

It can be a bit confusing for beginners, but once you understand closures, it’s not really that hard to understand, and with a little practice you’ll be able to take the idea of going ever farther, and it’s worth it.

reference

See Understand currying in Javascript blog

Reference curring blog