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\' ::
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.
{-# LANGUAGE FlexibleContexts #-}
import Control.Monad.State
maximumWithCount :: (Ord a, MonadState Int m) => [a] -> m a
maximumWithCount xs = case xs of
[] -> error "empty list"
[x] -> return x
(x:xs) -> do
modify (+1) -- increment the counter because we're recursing!
y <- maximumWithCount xs
return $ max x y
λ runState (maximumWithCount [1,2,3,4,5,4,3,2,1]) 0
(5,8)