【发布时间】:2010-11-14 00:15:44
【问题描述】:
假设我有一个递归函数,我想知道该函数在每个输入值中调用了多少次。与其放置 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)]
【问题讨论】:
标签: f#