How to write a “which day is it after x days” recursion in Haskell?

三世轮回 提交于 2019-12-25 16:55:39

问题


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   

回答1:


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



回答2:


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



回答3:


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 :-)



来源:https://stackoverflow.com/questions/23481043/how-to-write-a-which-day-is-it-after-x-days-recursion-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!