本文介绍了如何计算此Haskell函数中发生了多少个递归调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经尝试解决了几个小时.我需要使用某个函数计算发生了多少个递归调用:
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
非常感谢
推荐答案
您喜欢函数式编程吗?您喜欢命令式编程吗?为什么没有两者!这是一种计算递归深度的递归命令方法.
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)
这篇关于如何计算此Haskell函数中发生了多少个递归调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!