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

前端 未结 4 601
情书的邮戳
情书的邮戳 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 18:07

    For a list with n elements, there are n-1 recursive calls. To make it easier to see, we'll rewrite the function slightly. (We can ignore empty list for this.)

    maximum' [x] = x
    maximum' (x:xs) = if x > maxTail then x else maxTail
                      where maxTail = maximum' xs
    

    A recursive call is made when the tail of the argument is not empty. (Note that a function that was defined for the empty list as well would make n recursive calls on a list with n items.)

    We can expand a call to a 3-item list, for example:

    maximum' [1,2,3] = if 1 > maxTail then 1 else maxTail where maxTail = maximum' [2,3]
     maximum' [2,3] = if 2 > maxTail then 2 else maxTail where maxTail = maximum' [3]
      maximum' [3] = 3
    

提交回复
热议问题