How to calculate how many recursive calls happened in this Haskell function?

前端 未结 4 599
情书的邮戳
情书的邮戳 2021-01-15 17:30

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\' ::         


        
4条回答
  •  别那么骄傲
    2021-01-15 18:05

    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)
    

提交回复
热议问题