代理递归函数 [英] Proxying a recursive function
本文介绍了代理递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下一个简单的递归函数, jsdata-hide =falsedata-console =truedata-babel =false>
//一个简单的递归函数.const count = n => n&& 1 + count(n-1); //将代理中的函数包装到仪器输入和输出。函数仪器(fn){return new Proxy(fn,{apply(target,thisArg,argumentsList){console.log输入,... argumentsList); const result = target(... argumentsList); console.log(output,result); return result;}});} //调用instrumented function.instrument(count) (2);
但是,这只记录输入和输出在最高层。我想找到一种方法,使 count
在调用时调用检测版本。
解决方案
函数调用 count
,这就是你需要包装的东西。您可以执行
const count = instrument(n => n&& 1 + count(n-1) );
或
let count = n => n&& 1 + count(n-1);
count = instrument(count);
对于其他一切,您需要将递归调用的函数动态注入到已检测函数中,类似于Y组合器的作用。
Imagine a simple recursive function, which we are trying to wrap in order to instrument input and output.
// A simple recursive function.
const count = n => n && 1 + count(n-1);
// Wrap a function in a proxy to instrument input and output.
function instrument(fn) {
return new Proxy(fn, {
apply(target, thisArg, argumentsList) {
console.log("inputs", ...argumentsList);
const result = target(...argumentsList);
console.log("output", result);
return result;
}
});
}
// Call the instrumented function.
instrument(count)(2);
However, this only logs the input and output at the topmost level. I want to find a way to have count
invoke the instrumented version when it recurses.
解决方案
The function invokes count
, so that is what you need to wrap. You can do either
const count = instrument(n => n && 1 + count(n-1));
or
let count = n => n && 1 + count(n-1);
count = instrument(count);
For everything else, you would need to dynamically inject the function for the recursive call into the instrumented function, similar to how the Y combinator does it.
这篇关于代理递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文