当前位置:网站首页>Two ways to write Coriolis (understand 'fn.length' and 'FN. Tostring()')
Two ways to write Coriolis (understand 'fn.length' and 'FN. Tostring()')
2022-04-22 10:12:00 【Juntong】
Two ways of writing in curry
Write it at the front
currying , An interesting noun , I can't guess what it is literally !?
Today, I'd like to share with you two ways to write Coriolis of functions , Understand thoroughly fn.length And fn.toString()
In computer science , currying (Currying) It is to transform a function that accepts multiple parameters into a single parameter ( First parameter of the original function ) Function of , And return the technique of taking the remaining arguments and returning the result of the new function . This technology was developed by Christopher Strachey With logicians Haskell Curry Named , Even though it is Moses Schnfinkel and Gottlob Frege Invented .【 From Baidu Encyclopedia 】
- for instance
let add1 = (a, b, c) => {
return a + b + c
}
let add2 = (a) => {
return b => {
return c => {
return a + b + c
}
}
}
console.log(add1(1, 2, 3));
console.log(add2(1)(2)(3));
- We put
add1It's written inadd2It's called the corellization of a function - In general, Coriolis will get some parameters to generate a new function , Then use the new function to receive the remaining parameters
- such , We can fix some parameters , Generate some finer grained functions , This is more convenient for us to program ( Like functional programming )
Two ways of writing in curry
Some students saw the above code , Will say , Coritization is not easy , Just take it apart and write it .
however , If there are more and more parameters , The one above Terraced writing It is difficult to meet our needs , And it's cumbersome and not elegant enough
- therefore , For this cumbersome and repetitive step , We'll think about using
recursiveTo achieve - that , The problem is coming. , First we have to find the recursive exit of the function
- Introduce a knowledge point
fn.lengthIndicates the number of parameters required by a function , So we judge that the parameter is less thanfn.lengthJust recursion , Otherwise, execute the function
- Introduce a knowledge point
- that , How to save the previous parameters ?
- Our recursive function can use
ES6Mediumrest ParametersTo save the previous parameters
- Our recursive function can use
- that , How to get the parameters of the current function ?
- Our recursive function will return a function , Of internal functions
rest ParametersThe parameters of the current function are
- Our recursive function will return a function , Of internal functions
- therefore , The total parameter of our function is
let _args=[...args,...params]( It's used hereES6The extension operator of )
- Next question , What if the parameters of our corellized function are uncertain ?
fn.lengthNot sure , The previous method will not work- It's really a question , Simply put, by rewriting
fn.toString()Get the result by implicit conversion
The following is divided into fn.length Known and unknown bring you two ways to write Coriolis
fn.length It is known that
- There are many known ways of writing described above
- 1. We used higher-order functions , In this way, you can get the previous parameters and the current parameters , So as to get all the current parameters
- 2. If the length of the current parameter is greater than or equal to
fn.length, We will carry outfnfunction- We need to pass in the parameters and use
apply, Because it didn't usethisThe pointer , The first parameter here isnull
- We need to pass in the parameters and use
- 3. If the length of the current parameter is less than
fn.length, We execute recursively_curryfunction- Again , We need to pass in parameters , Here, because the parameter passed in is not an array , So we use... In the form of parameter list
call
- Again , We need to pass in parameters , Here, because the parameter passed in is not an array , So we use... In the form of parameter list
callandapplyOne difference is whether the second parameter is an array !(callIt's a list of parameters , Separate parameters one by one )- They can be converted by extension operator !
fn.apply(null,_args)
fn.call(null,...args)
// These two are the same
function curry (fn, len = fn.length) {
function _curry (fn, len, ...args) {
return function (...params) {
let _args = [...args, ...params]
if (_args.length >= len) {
return fn.apply(null, _args)
} else {
return _curry.call(null, fn, len, ..._args)
}
}
}
return _curry(fn, len)
}
function fn (a, b, c, d) {
console.log(a, b, c, d);
}
let _fn = curry(fn)
_fn(1, 2, 3)(4) // 1 2 3 4
_fn(4)(5, 6)(7, 8) // 4 5 6 7
_fn(4)(5,6)(7)(8) // Report errors
Let's see the results
- The first coritization was successful
- The second one is also reflected in our code , We will not calculate the exceeded parameters
- The third one is wrong , Why? ?
- The first three brackets , We end recursion , The next time you pass in parameters , Let's go up to the next floor
returnIs not a function , That's why I made a mistake - This actually belongs to
fn.lengthUnknown category , So how do we deal with this situation ? Keep looking down !
- The first three brackets , We end recursion , The next time you pass in parameters , Let's go up to the next floor
fn.length Unknown
- In the unknown , If we want to save the transfer of parameters, we can only use
recursive - But because we don't have to judge when to call
fn, We use closures to store our parameters - So finally we
returnThe result will be aFunctionfunction- The most magical place is here , We can judge
res==15The returned result istrue,res The type of is aFunction, The reason is that there isImplicit conversion - Say something simple. , Is to automatically call
toString()Method , So we can rewritetoString()Method to solvefn.lengthUnknown problem
- The most magical place is here , We can judge
- We rewrite
toString()function , Usedreduce, This makes it easy to get all the parameters , Then we can write the logic
function add () {
let args = [...arguments]
let inner = function () {
args.push(...arguments)
return inner
}
inner.toString = () => {
return args.reduce((pre, cur) => {
return pre + cur
})
}
return inner
}
const res = add(1)(2)(3)(4)(5)
console.log(res == 15); // true
console.log(res.toString()); // 15
- It's addition , It can also be written as multiplication or other logic !
Put a colored egg !
- If the inner function of the second method is written as
Anonymous functionsWhat will happen ?- We often say
ES6Anonymous functions are convenient , Very elegant , Is there a problem with using it here ?
- We often say
function add () {
let args = [...arguments]
let inner = () => {
// Changes have been made here , Change to anonymous function !!!
args.push(...arguments)
return inner
}
inner.toString = () => {
return args.reduce((pre, cur) => {
return pre + cur
})
}
return inner
}
- Although the anonymous function seems to write less code, it is very natural , But not here
- Write it as an anonymous function , result
add(1)(2)(3)(4)(5)==5It turned out to be wrong- Internal function
push了arguments - Anonymous functions
argumentsIt's a mess - If you don't believe it, look at the following function
- Internal function
function test () {
console.log(arguments);
}
let test2 = () => {
console.log(arguments[0]);
}
test() //[Arguments] {}
test2() // For a long , So want to use arguments Don't use anonymous functions !
版权声明
本文为[Juntong]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220958320754.html
边栏推荐
- MySQL multi instance installation method I
- Linux Installation Oracle 19C Full Version (graphics + silent installation)
- 5.嵌入式控制器(Embedded Controller,EC)学习 PS/2协议
- adroid SQLiteOpenHelper数据表结构升级
- linux7静默安装oracle11g
- Generalized Robust Regression for Jointly Sparse Subspace Learning
- L2-033 simple calculator (25 points)
- Unity3D build时错误提示:Missing Project ID in Unity 解决方案
- idea写sparksql程序local[*]模式可以运行,提交到spark yarn运行出现ClassNotFoundException
- idea 线程池debug断点跳不进去
猜你喜欢

自学编程千万别再傻傻地读理论书,程序员:这都是别人玩剩下的

Various location codes applied in transformer model

DPU 芯片头部企业云豹智能加入 openEuler社区,为数字中国基础设施助力

Drop down refresh and pull-up load of product list of uni app project

Nacos

Depth first search (I): middle order traversal of binary tree (force buckle)

Writing to remember the ~ goal and

【SQL server】SQL 概览

一款简易的自定义数字键盘输入控件

Leapftp: 425 failed to establish connection solution
随机推荐
【濡白的C语言】初学者-从零开始-5(模块化设计——函数,传值和传址)
VLAN - virtual LAN overview
Intermediary model
5.嵌入式控制器(Embedded Controller,EC)学习 PS/2协议
企业级 Web 开发的挑战
Shell gets random number and echo - E '\ 033 [word background color; font color M string \ 033 [0m'
Softing datafeed OPC Suite: empowering industrial equipment to connect to the Internet of things
leetcode771. 宝石与石头
formDate保存数据
How to realize synchronous monitoring of etcd
超越iTerm! 号称下一代终端神器,功能贼强大!
Project training - newspaper reading zombie
Beyond iterm! Known as the next generation terminal artifact, I can't put it down after using it!
Command ‘yum‘ not found, but can be installed with: apt install yum
OGG-00663 OCI Error ORA-02396: exceeded maximum idle time
Tensorflow Experiment 4 -- Boston house price forecast
【无标题】
Memory management-
[flutter topic] 125 illustrated autobiography ace_ ICON. Ttf Icon Library
NavigationView的使用