問題描述
編寫一個可任意調用次數的 curried javascript 函數,該函數在最後一次函數調用時返回一個值 (Writing a curried javascript function that can be called an arbitrary number of times that returns a value on the very last function call)
我目前正在處理我個人時間的一個編程問題,要求我製作一個可以以這種方式調用的 javascript 函數。
add(1) // 1
add(1)(2) // 3
add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15
我無法弄清楚如何使其在最後一次調用時返回一個值。
例如,為了使 add(1)(2)
工作,然後 add(1)
必須返回一個函數,但是根據指令 add(1)
自己調用時會返回 1
.
I' m 假設您可以克服這個問題的一種方法是弄清楚 add
函數連續調用了多少次,但我想不出一種方法來實現這一點。有沒有人有任何提示可以為我指明正確的方向?
我已經閱讀了這兩篇文章(1, 2) 關於函數柯里化,我理解它們,但我不確定在處理可變數量的參數時如何進行柯里化。
com/2015/01/14/gettin‑freaky‑functional‑wcurried‑javascript/" rel="nofollow">2) 關於函數柯里化,我理解它們,但我不知道什麼時候做柯里化處理可變數量的參數。com/2015/01/14/gettin‑freaky‑functional‑wcurried‑javascript/" rel="nofollow">2) 關於函數柯里化,我理解它們,但我不知道什麼時候做柯里化處理可變數量的參數。參考解法
方法 1:
It is impossible to curry a variadic function with an unknown number of arguments.
Where add
is a variadic function, you could do something like
var add5 = curryN(add, 5);
add5(1)(2)(3)(4)(5); //=> 15
var add3 = curryN(add, 3);
add3(1)(2)(3); //=> 6
There's simply no avoiding this tho because a curried function will continue to return a function until the last argument is received, at which point the computation is run.
The only other option is to create some way to "short‑circuit" the arguments and notify the function that the arguments are done being sent. That would require something like
var xadd = curryUntilUndefined(add);
xadd(1)(2)(3)(4)(5)(undefined); //=> 15
Here, the undefined
signals the end of the variadic arguments. I don't really recommend this tho because of the other problems it can create for you. Not to mention, it's not particularly nice to look at.
方法 2:
It is not impossible, use valueOf().
function add(initNum) {
var sum = initNum;
var callback = function (num) {
sum += num;
return callback;
};
callback.valueOf = function () {
return sum;
};
return callback;
};
console.log(add(1)(2)==3); //true
console.log(add(1)(1)+1); //3
console.log(add(1)(2)(3).valueOf()); //6
(by m0meni、Mulan、epascarello)