I've been trying to figure this out for a couple of hours now. I need to calculate how many recursive calls happened using a certain function:
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maximum' xs
Many thanks in advance
This is a digression on Michail's and user2297560's answers.
What if, instead of rewriting the function from scratch to add tracking functionality, we could reuse the original implementation and "instrument" it in some way?
We could write a base function that
fix
.For example:
And then instrument it like this, reusing the original logic:
But perhaps defining functions as "monadic by default" isn't too practical.
Do you love functional programming? Do you love imperative programming? Why not have both! Here's a recursive-imperative way to count the recursion depth.
For a list with
n
elements, there aren-1
recursive calls. To make it easier to see, we'll rewrite the function slightly. (We can ignore empty list for this.)A recursive call is made when the tail of the argument is not empty. (Note that a function that was defined for the empty list as well would make
n
recursive calls on a list withn
items.)We can expand a call to a 3-item list, for example:
You can rewrite your function to carry information about recursion depth in an extra argument, and return it as second (or first, if you so prefer) element of a tuple:
Then you can call the function with
maximum' lst 0
ormaximum' lst 1
depending on whether or not you want the first call to count as a recursion level.It can be done with any recursive function, but it's probably not necessary in your case. As chepner wrote, the answer is known without extra computations.