说我有一个递归函数,我想知道函数每次输入值调用它自己的次数。而不是把printf表达式或改变返回类型以包含调用次数,是否有可能用另一个“包装”这个函数来实现这个功能?我希望包装函数返回函数调用的数量和原始函数的结果。它应该可以跨不同的功能重用。包装一个递归函数来计算函数调用的数量
这是我有,它不工作。
open System
open System.IO
open System.Collections.Generic
/// example recursive function
let rec getfilenames dir =
seq {
yield Directory.GetFiles dir
for x in Directory.GetDirectories dir do yield! getfilenames x}
/// function to count the number of calls a recursive function makes to itself
let wrapped (f: 'a -> 'b) =
let d = new Dictionary<'a, int>()
fun x ->
let ok, res = d.TryGetValue(x)
if ok then d.[x] <- d.[x] + 1
else
d.Add(x, 1)
d, f x
> let f = wrapped getfilenames
let calls, res = f "c:\\temp";;
val f : (string -> Dictionary<string,int> * seq<string []>)
val res : seq<string []>
val calls : Dictionary<string,int> = dict [("c:\temp", 1)]
我被困在2点,注释掉字典,现在应该去哪里类型?在包装函数最后一行f recfun x我不明白这是如何工作:( – yanta 2010-11-13 16:25:27
字典:与以前一样(唯一的区别是,现在f的类型是'('a - >'b) - > 'a - >'b',因为它期望'recfun')。'recfun'表示在子目录中应该由'f'调用的函数(因为'f'不是递归的)。这让你使用计数函数来处理子目录 – 2010-11-13 16:30:29
let calls,counted_body = wrap body ;; 错误FS0030:值限制。当'_a:> seq –
yanta
2010-11-13 16:38:14