Question

I am starting to learn Haskell and I'm trying to get this code to work but I cannot understand where is my mistake. I would really appreciate it if you could explain it to me. :) I want to type for example Mon 8 and get Tue.

data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun < - [1..7]

next :: Day -> Day
next Mon = Tue
next Tue = Wed
next Wed = Thu
next Thu = Fri
next Fri = Sat
next Sat = Sun
next Sun = Mon

gez n :: (Ord a) => a -> a -> Bool
  | n > 7   = n - 7
  | n <= 7  = n   
Was it helpful?

Solution 2

You don't have worry about the modulo math if you use automatic deriving of the Enum and Bounded typeclasses.

data Day = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Show, Eq, Enum, Bounded) 

next :: (Eq a, Enum a, Bounded a) => a -> a
next d = if d == maxBound then minBound else succ d

back :: (Eq a, Enum a, Bounded a) => a -> a
back d = if d == minBound then maxBound else pred d

applyN:: Int -> (a -> a) -> (a -> a)
applyN n _ | n < 1 = id
applyN n f = (applyN (n-1) f) . f

*Main> applyN 9 next Sunday
Tuesday

OTHER TIPS

With a derived Enum instance for Day you can translate this idea of "counting modulo N" quite directly:

next :: Int -> Day -> Day
next n = toEnum . flip mod 7 . (+n) . fromEnum

n days after today is n - 1 days after tomorrow. Hence:

days_after :: Integer -> Day -> Day
days_after 0 day  = day
days_after n day  = days_after (n - 1) (next day)

Of course, if you're intersted in 1234567890 days after Sunday, or -1 days after Sunday, take one of the other solutions :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top