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

前端 未结 4 597
情书的邮戳
情书的邮戳 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 17:59

    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.

提交回复
热议问题