ShocKwav3_
ShocKwav3_

Reputation: 1760

How to count the recursion times in Haskell?

I am trying to write a function, given two dates, calculates the distance (in days) between the two dates, using recursion. The function dateDistance takes two dates and uses nextDate to find the next valid date. goodDate makes sure its a valid date.

I am trying to get the result by counting recursions and returning the count. Each time the recursion happens the count variable n should increase and at the end of the recursion when it reaches the end condition (fy == sy && fm == sm && sd == fd) = n it shall return the n.

   leapYear x = if ((x `mod` 4) == 0) && ((x `mod` 100) /= 0) || ((x `mod` 400) == 0) 
                 then True
                 else False

    goodDate (y,m,d)
        | (d<1 || m>12 || m<1 || y==0) = False
        | m `elem` [1,3,5,7,8,10,12] = d<32
        | m `elem` [4,6,9,11] = d<31
        | leapYear y = d<30
        | otherwise= d<29 

    nextDate (y,m,d) =
      if goodDate(y,m,(d+1)) 
      then (y,m,(d+1))
      else if goodDate(y,(m+1),1)
           then (y,(m+1),1)
           else ((y+1),1,1)



    dateDistance (fy,fm,fd) (sy,sm,sd) 
    |(fy == sy && fm == sm && sd == fd) = n
    |otherwise = dateDistance nextDate (fy,fm,fd) (sy,sm,sd)
     where n = 0

Upvotes: 1

Views: 1561

Answers (2)

sdx23
sdx23

Reputation: 168

Actually, you don't need to remember it, even though you could do so, by passing it from call to call as an argument.

Let's answer two questions:

  1. What is the base case of your recursion? Exactly, when both dates are equal; the distance is 0 then.

  2. What is one recursion step? Well, if the dates f and s are not equal, we search for the nextDate (rather next-day!), lets call it f1. f1 is one day distant from f, but one day nearer to s. f2 ( = nextDate f1) is two days from f, but even nearer to s. So: dateDistance f s = 1 + dateDistance f1 s and dateDistance f1 s = 1 + dateDistance f2 s.

Upvotes: 2

Paul Johnson
Paul Johnson

Reputation: 17786

You need to pass the "n" explicitly through the recursive calls. Make it an extra parameter of your dateDistance function and put n+1 in the recursive call. Then call it with an initial value of 0.

You can rename the dateDistance function to something else and rewrite dateDistance to call it with the initial value of 0.

Upvotes: 1

Related Questions