如何计算函数调用次数(FP方法) [英] How to count the number of times a function was called, the FP way
问题描述
我目前正在与Haskell合作通过 SICP .练习1.15询问一个函数被调用了多少次.这个想法可能是您应该使用替换方法,但是我想知道如何在代码中使用它.
I am currently working through SICP with Haskell. Exercise 1.15 asks how many times a function is called. The idea is probably that you should use the substitution method, but I would like to know how to do so in code.
在命令式语言中,可以保留一个全局变量,并在每次调用该函数时对其进行递增.但是,您将如何在Haskell中进行操作(或使用纯功能性方法)?
In an imperative language one can keep a global variable and increment it every time the function is called. But how would you go about it in Haskell (or the pure functional way)?
推荐答案
您可以使用Writer
monad来完成此操作,前提是可以将对相关功能的所有调用归为一个do
块. :
You can use the Writer
monad to accomplish this, provided that all of the calls to the function in question can be grouped together into a do
block:
import Control.Monad.Writer
myFunc :: Int -> Int -> Writer (Sum Int) Int
myFunc a b = tell (Sum 1) >> return (a + b)
callMyFunc :: ((Int, Int, Int), Sum Int)
callMyFunc = runWriter $ do a <- myFunc 2 3
b <- myFunc 8 7
c <- myFunc 3 5
return (a, b, c)
main = putStrLn $
"myFunc was called "
++ show (getSum $ snd callMyFunc)
++ " times and produced "
++ show (fst callMyFunc)
哪个输出:
myFunc was called 3 times and produced (5,15,8)
这篇关于如何计算函数调用次数(FP方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!