递归函数

问题描述 投票:0回答:2

想象一个简单的递归功能,我们正在尝试将其包装以进行仪器输入和输出。

// 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);

,但是,这仅在最高级别记录输入和输出。我想找到一种方法,以便在复发时调用仪器版本。

我今天随机考虑了这一点,并提出了以下方法来解决此问题。问题是词汇范围,因此我们无法像“正常”的东西那样解决递归功能。这是我想到的:

count
javascript ecmascript-6 es6-proxy
2个回答
0
投票
jsfiddle:

Https://jsfiddle.net/gol0hz6k/

    

功能调用// declare this so we can reference it in the recursive body let proxiedCount; // A simple recursive function. const count = (n) => n && 1 + proxiedCount(n-1); // Wrap a function in a proxy to instrument input and output. function instrument(fn) { const proxy = new Proxy(fn, { apply(target, thisArg, argumentsList) { console.log("inputs", ...argumentsList); const result = target(...argumentsList); console.log("output", result); return result; } }); return proxy; } proxiedCount = instrument(count); // now this is assigned // Call the instrumented function. proxiedCount(2);

,因此您需要包装。你可以做

-1
投票
count

or

const count = instrument(n => n && 1 + count(n-1));
对于其他所有内容,您需要将递归调用的功能动态注入仪器功能,类似于Y组合器的方式。
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.