在Javascript中递归调用curried函数

问题描述 投票:-3回答:1

作为玩具示例,我们可以说我们有这个功能及其用法:

const map = (f = n => n + 1) => (lst = [1,2,3]) => {
    if(lst.length === 0)
        return [];
    else
        return [f(...lst.splice(0,1)), ...map(f)(lst)];
}
const inc = n => n + 1;
const map_inc = map(inc);
map_inc([1,2,3]) // => (produces) [2,3,4]

在咖喱功能图中,我通过调用map(f)(lst)来使用“递归”。

上面的示例在可以调用之前重建该函数。

是否可以在不重建函数的情况下执行此递归?

我知道这种方式:

y = (f = (f, ...args) => [...args],
     ...args) => f(f, ...args);

const map = (mapper = n => n + 1) => (self = mapper, lst = [1,2,3]) => {
    if(lst.length === 0)
        return [];
    else
        return [mapper(...lst.splice(0,1)), ...self(self, lst)];
}
const inc = n => n + 1;
const map_inc = (...args) => y(map(inc), ...args);
map_inc([1,2,3]) // => (produces) [2,3,4]

我真的不喜欢这需要将函数传递给自己。

这可以在没有y函数的情况下完成并且不将函数传递给它自己吗?这可以用更无点的风格来完成吗?

javascript currying pointfree
1个回答
2
投票

如果我正确理解你的问题,你不能返回命名的箭头函数,但是你可以返回一个命名的常规函数​​并像这样递归调用它:

const reducer = k => function recurse(a, item) {
//...
    const s_res = _.split(item, k, 1);
    return recurse(a.withMutations(a => {
        a.push(s_res[0]);
        let a_element = document.createElement('a');
        a_element.setAttribute('href', '#');
        a_element.addEventListener('click', () => display_gen_element(k, obj));
        a.push(a_element);
    }), s_res[1]);
};

附:为了便于阅读,请不要使用单字母变量名称,除非它明显地显示它们的用途,例如: for循环中的计数器等

© www.soinside.com 2019 - 2024. All rights reserved.