如何计算 Haskell 中的递归次数? [英] How to count the recursion times in Haskell?

查看:48
本文介绍了如何计算 Haskell 中的递归次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,给定两个日期,使用递归计算两个日期之间的距离(以天为单位).函数 dateDistance 接受两个日期并使用 nextDate 来查找下一个有效日期.goodDate 确保它是一个有效的日期.

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.

我试图通过计算递归并返回计数来获得结果.每次递归发生时,计数变量 n 应该增加,并且在递归结束时,当它达到结束条件 (fy == sy && fm == sm &&; sd == fd) = n 它将返回 n.

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

推荐答案

实际上,您不需要记住它,即使您可以通过将其作为参数从一个调用传递到另一个调用来记住它.

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

让我们回答两个问题:

  1. 你的递归的基本情况是什么?确切地说,当两个日期相等时;那么距离为 0.

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

什么是递归步骤?好吧,如果日期 f 和 s 不相等,我们搜索 nextDate(而不是第二天!),我们称之为 f1.f1 距离 f 一天,但离 s 近一天.f2 ( = nextDate f1) 距离 f 两天,但更接近 s.所以:dateDistance f s = 1 + dateDistance f1 sdateDistance f1 s = 1 + dateDistance f2 s.

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.

这篇关于如何计算 Haskell 中的递归次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆