我正在尝试在 JS 中构建一个函数,该函数的返回值由基于用户传递的参数的不同嵌套函数组成。
function addA(otherFunction)
{
//gets the result from some base function and modifies it
//e.g. +1
}
function addB(otherFunction)
{
//does the same thing as addA, except different values. Consider it a variation of addA.
//eg. -1
}
function constr(input)
{
//based on the chars in input, we will recursively select a new function to be applied.
//the value of this function should be a function
if (...) return addA(constr(shorterInput))
if (*last char) return addA
if (*last char) return addB
if (...) return addB(constr(shorterInput))
}
到目前为止,我的脚本将 addA 和 addB 识别为函数。但是,例如,当它将两个函数串在一起时
addB(addA)
类型变得未定义。谁能告诉我为什么它不注册为函数和/或返回嵌套函数的正确方法。谢谢!
编辑:这是真正的代码:
function cons(a,b)
{
return function (selector) {
return selector(a,b);
};
}
function a(list)
{
function aHelper(a,b)
{
return a
}
return list(aHelper);
}
function d(list)
{
function dHelper(a,b)
{
return b
}
return list(dHelper);
}
function abc(input)
{
if (input.length==0 || input==null) return null;
var x=input.charAt(input.length-1);
if (x==='a')
{
if (input.length>1)
{
var z=a(abc(input.substr(0,input.length-1)));
return z;
}
return a;
}
if (x==='d')
{
if (input.length>1)
{
var z=d(abc(input.substr(0,input.length-1)));
return z;
}
return d;
}
}
function show(list) {
var sval;
if (list == null) return '()';
else if (typeof list!='string')
{
sval = '(' + show(a(list)) + ' ' + show(d(list)) + ')';
}
else
{
sval=list;
}
return sval;
}
var func=abc('ad');
var func2=abc('a');
var list=cons('a',cons('b','c'));
console.log(typeof func);
console.log(typeof func2);
console.log(typeof list);
console.log(typeof func2(list));
console.log(typeof func(list));
最佳答案
您的函数abc
应该返回一个可以处理列表的函数,例如a
或d
。但是,您仅在 7 种情况中的 2 种匹配该签名:
返回 a
、返回 d
都可以返回 null
- 这不是可调用值z = d(…); return z
确实返回一个列表z = a(…); return a
确实返回列表的一个元素(无论什么类型)d(abc(…))
和a(abc(…))
使用abc
就好像它会返回一个列表<
正确的实现如下所示:
function abc(directions) {
if (directions.length == 0) {
return function id(list) { return list; }; // a function that does nothing
}
var f = directions[0] == 'a' ? car : cdr; // ignoring other values, you might also throw an error
var processRest = abc(input.slice(1));
return function(list) { // make a function to process a list
var z = f(list); // do the current operation
return processRest(z); // do the rest of operations
};
}
或者在高阶函数组合的帮助下甚至更好/更短:
function id(x) { return x; }
function compose(f, g) {
if (f == id) return g;
if (g == id) return f;
return function(x) { return f(g(x)); };
}
function abc(dirs) {
return !dirs.length ? id : compose(abc(dirs.slice(1)), dirs[0]=='a'?car:cdr);
}
关于javascript - 递归返回函数以形成嵌套函数 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39550890/