本文介绍了如何计算这个 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 函数中发生了多少递归调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 13:30