我已经尝试解决了几个小时。
我需要计算使用某个函数发生了多少个递归调用:

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


提前谢谢了

最佳答案

您喜欢函数式编程吗?您喜欢命令式编程吗?为什么没有两者!这是一种计算递归深度的递归命令方法。

{-# 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)

关于haskell - 如何计算此Haskell函数中发生了多少个递归调用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41781460/

10-09 19:27