- Currie,
- Currization in Lodash — Curry ()
- case
- Simulation of the Currization principle
- Corrified summary
- Functional programming overall design
Before, we talked about the preknowledge of functions. Functional programming (I) — preknowledge
And the knowledge of pure functions functional programming (2) — pure functions
Now we can move on to the basics of functional programming — curritization.
Currie,
Solve the hard coding problem
// The following code solves the problem of impure functions, but it is hard coded
function checkAge (age) {
let mini = 18
return age >= mini
}
// a plain pure function
function checkAge (min, age) {
return age >= min
}
console.log(checkAge(18.20)) //true
console.log(checkAge(18.24)) //true
console.log(checkAge(20.24)) //true
// Always use 18, this code is repeated. To avoid repetition
function checkAge (min) {
return function (age) {
return age >= min
}
}
let checkAge18 = checkAge(18)
let checkAge20 = checkAge(20)
console.log(checkAge18(20)) //true
console.log(checkAge18(24)) //true
Copy the code
Corrification: We can modify a function when it has more than one parameter. We can call a function, pass only part of the argument (which will never change), and have the function return a new function. The new function passes the remaining arguments and returns the corresponding result.
// ES6
let checkAge = min= > (age= > age >= min)
// Same output
Copy the code
Currization in Lodash — Curry ()
_.curry(func)
- Function: creates a function that takes one or more arguments to func, executes func if all required arguments are provided and returns the result of the execution. Otherwise continue to return the function and wait for the remaining arguments to be received.
- Parameters: functions that require currization
- Return value: The currified function
const _ = require('lodash')
// The parameters are one unary function and two binary functions
// It is possible to transform a function of several variables into a function of one variable
function getSum (a, b, c) {
return a + b + c
}
// Define a Currization function
const curried = _.curry(getSum)
// If all parameters are entered, the result is returned immediately
console.log(curried(1.2.3)) / / 6
// If a partial argument is passed in, it returns the current function and waits to receive the remaining arguments in getSum
console.log(curried(1) (2.3)) / / 6
console.log(curried(1.2) (3)) / / 6
Copy the code
case
Match (/\s+/g) {match(/\s+/g);
But if we write a method to remove whitespace from an array, the code above cannot be reused. So how do we write it functionally
function match(reg, str) {
return str.match(reg)
}
Copy the code
The expression of reg is repeated. How to corrify the function above is as follows:
// Currization
const _ = require('lodash')
// Using Lodash's curry function, the first argument is a matching rule, and the second argument is a string, to generate a match function
const match = _.curry(function (reg, str) {
return str.match(reg)
})
// haveSpace is a function that matches Spaces according to the rule
const haveSpace = match(/\s+/g)
console.log(haveSpace("hello world")) / / / '
console.log(haveSpace("helloworld")) //null
// Check if there are Spaces in the string
// What about numbers?
// By rule haveNumber is a function that matches numbers
const haveNumber = match(/\d+/g)
console.log(haveNumber('abc')) // null
// How do arrays match elements with Spaces
const filter = _.curry(function(func, array) {
return array.filter(func)
})
// The filter function, the first argument passes whether there is a space in the matched element
// The second argument is the specified array
console.log(filter(haveSpace, ['John Connor'.'John_Donne'])) // [ 'John Connor' ]
// If the above is still too much trouble, then you can wrap another function
// Filter can pass a parameter and return a function
// findSpace is a function that matches if there is a space in an array element
const findSpace = filter(haveSpace)
console.log(findSpace(['John Connor'.'John_Donne'])) // [ 'John Connor' ]
Copy the code
As a small summary of the above ideas, the advantage of currization is that we can reuse our functions to the maximum extent possible.
const _ = require('lodash')
// The match function returns the result of a match based on a string of re's
const match = _.curry(function (reg, str) {
return str.match(reg)
})
//haveSpace is a function that matches Spaces
const haveSpace = match(/\s+/g)
// The haveNumber function is a function that matches numbers
const haveNumber = match(/\d+/g)
The filter function defines an array and a filter rule, and returns an array that matches the matching rule
const filter = _.curry(function(func, array) {
return array.filter(func)
})
The findSpace function is a function that matches an array element with a space and returns an array that matches that
const findSpace = filter(haveSpace)
Copy the code
Simulation of the Currization principle
Let’s look at an example that we did before
const _ = require('lodash')
function getSum (a, b, c) {
return a + b + c
}
const curried = _.curry(getSum)
console.log(curried(1.2.3)) / / 6
console.log(curried(1) (2.3)) / / 6
console.log(curried(1.2) (3)) / / 6
Copy the code
Implementing a Coriolization transformation function requires analysis
- Call-in and call-out: The call passes a pure function argument and returns a Corrified function when completed
- Analysis of entry conditions:
- If the curried call passes the same number of arguments as the getSum function, it executes immediately and returns the result of the call
- If the arguments passed by the Curried call are partial arguments to getSum, you need to return a new function and wait to receive the other arguments to getSum
- Focus on:
- Gets the arguments to the call
- Check if the numbers are the same
// Simulate the Currization function
function curry (func) {
// The name is used when the argument is smaller than the parameter
return function curriedFn(. args) {
// Determine the number of arguments and parameters
if(args.length < func.length) {
return function() {
Return func if the remaining function argument plus the previous argument equals the parameter
// The first part of the argument is in args, the second part of the argument is in arguments, merge the two and expand the pass (using...).
// The concat function merges two arrays. Arguments are pseudo-arrays, so use array. from to convert
returncurriedFn(... args.concat(Array.from(arguments)))}}// If the argument is greater than or equal to the number of parameters
// args is the remaining argument, which is an array, and is returned to be expanded (using...).
returnfunc(... args) } }// test
const curriedTest = curry(getSum)
console.log(curriedTest(1.2.3)) / / 6
console.log(curriedTest(1) (2.3)) / / 6
console.log(curriedTest(1.2) (3)) / / 6
Copy the code
Corrified summary
- Corrification allows us to pass fewer arguments to a function and get a new function that remembers some of the fixed arguments (for example, the match function is regenerated as a haveSpace function that uses closures and remembers the arguments to the regular expression that we passed).
- This is a ‘cache’ of function arguments (using closures)
- 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
Functional programming overall design
- Functional programming (I) – Pre-knowledge
- Functional programming (II) – pure functions
- Functional programming (iii) – Coriolization
- Functional programming (4) – function composition
- Functional programming (5) – functors