Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

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

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  

Many thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can rewrite your function to carry information about recursion depth in an extra argument, and return it as second (or first, if you so prefer) element of a tuple:

maximum' :: (Ord a) => [a] -> Int -> (a, Int)
maximum' [] _ = error "maximum of empty list"  
maximum' [x] n = (x, n)
maximum' (x:xs) n   
    | x > fst maxTail = (x, snd maxTail)
    | otherwise = maxTail  
    where maxTail = maximum' xs (n + 1)

Then you can call the function with maximum' lst 0 or maximum' lst 1 depending on whether or not you want the first call to count as a recursion level.

It can be done with any recursive function, but it's probably not necessary in your case. As chepner wrote, the answer is known without extra computations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...