Haskell计数函数调用的次数 [英] Haskell counting number of function call
问题描述
concat :: String - >字符串 - >串
。所以, var :: String
var = concat(concatab)c) - abc
现在我有一个函数可以用来计算多少次concat被称为:
func ::(String-> String-> String) - > Int
因此, func var
应该返回2 。
我该如何得到这个值并同时执行concat?
正确的做法是替换 concat :: String - >字符串 - >字符串
与 concatA :: String - >字符串 - > f(String)
,对于某些适当的 Applicative
f
。例如,您可以使用 Writer
:
concatW :: String - >字符串 - > Writer Int String
concatW s1 s2 = Writer(s1 ++ s2,Sum 1)
现在
concatW s1 s2>>> = concatW s3>> = concatW s4
$ b $或者
$ $ p $(<=> )< $> concatW s1 s2 * concatW s3 s4
会为您计算物品。
如果您对调用函数的次数感兴趣,可能需要使用 trace
Debug.Trace
。您可能还想使用分析器并将该功能注释为成本中心。如果你疯了,你甚至可以使用 unsafePerformIO
。但这些不是通常应该出现在已发布程序中的内容。
Say I have a function concat :: String -> String -> String
. So,
var :: String
var = concat (concat "a" "b") "c") -- "abc"
Now, I have a function which I want to use to calculate how many times concat is called:
func :: (String->String->String) -> Int
So, func var
should return 2.
How should I get this value and at the same time perform the concat?
The right way to do this is to replace concat :: String -> String -> String
with concatA :: String -> String -> f (String)
, for some appropriate Applicative
f
. For example, you could use Writer
:
concatW :: String -> String -> Writer Int String
concatW s1 s2 = Writer (s1++s2, Sum 1)
Now
concatW s1 s2 >>= concatW s3 >>= concatW s4
Or
(<=) <$> concatW s1 s2 <*> concatW s3 s4
will count things for you.
If you are interested in how many times your function is called for debugging purposes, you may want to use trace
from Debug.Trace
. You may also want to use the profiler and annotate the function as a cost center. You could even use unsafePerformIO
if you're crazy. But these are not things that should generally appear in a released program.
这篇关于Haskell计数函数调用的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!