Alex Rivera | Logout

How to count the number of times a function was called, the FP way

Asked 2012-03-29T06:26:10.623
14

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.

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)?

Edit
Report

1 Answer

17

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)

Which outputs:

myFunc was called 3 times and produced (5,15,8)
answered 2012-03-29T09:28:44.213

Your Answer