Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Elapsed days between two dates

Tags:

haskell

I'm working on a small haskell program that I gave the name the "Haskel-dator", hahaha....anyway, heres my current progress on the code for it, and the run-time errors that followed:

Code

data Date = Date Int Int Int 
type Date = (Int,Int,Int)  

sum :: Int -> Int -> Int 
sum x y | let x - y = z 
        | where z > 0

diff :: Date -> Date -> Int   -- Difference between the two dates 
diff (a,b,c) (x,y,z) = if a < x && b < y && c < z   
        then do sum
        else return 0 


Errors

*ERROR "myprogram.hs": - Multiple declarations of type constructor "Date" *

Basically, I want my program to have the following assumptions:

  • Definition type Date = (Int,Int,Int) where the tuple (1,2,2010) denotes 1st Feb 2010.
  • The first argument (date) should be earlier than the second argument (date). If not, return 0.
  • Assume that dates are correctly formatted. For instance, there is no need to check for invalid dates like (32,13,2010).
  • Leap years must be taken into account.

I want my program to achieve an output that should look something like this:
Example Output

diff (1,1,2010) (10,1,2010) => 9
diff (2,2,2011) (2,2,2012) => 365
diff (28,2,2012) (1,3,2012) => 2

Any ideas?

like image 835
yamis7190 Avatar asked Jul 18 '26 11:07

yamis7190


1 Answers

You should look at the standard time package.

The diffDays function is exactly what you want. It returns the number of days between two dates.

diffDays :: Day -> Day -> Integer

The dates are defines with as Day.

Day instances can be build by using the fromGregorian function.

The complete example can be found here.

Keep in mind that calculating the number of days between two dates correctly is a very complex task.

like image 137
ErMejo Avatar answered Jul 20 '26 22:07

ErMejo