无论如何,是否可以更优雅地编写以下函数?
我可以看到一些模式,但不确定如何抽象它们或如何找到一种更简单的编写函数的方法。
type HasRemainder = Boolean
tomorrow :: Date -> Date
tomorrow date = unsafePartial $ canonicalDate y (fst m) (fst d)
where d :: Tuple Day HasRemainder
d = case toEnum $ 1 + fromEnum (day date) of
Just v -> Tuple v false
Nothing -> Tuple (unsafePartial $ fromJust $ toEnum 1) true
m :: Tuple Month HasRemainder
m = if snd d then
case toEnum $ 1 + fromEnum (month date) of
Just v -> Tuple v false
Nothing -> Tuple (unsafePartial $ fromJust $ toEnum 1) true
else Tuple (month date) false
y :: Year
y = if snd m then
case toEnum $ 1 + fromEnum (year date) of
Just v -> v
-- use 2018 arbitrarly if the conversion from int to Date fails
Nothing -> unsafePartial $ fromJust $ toEnum 2018
else (year date)
Run Code Online (Sandbox Code Playgroud)
我会做这样的事情:
import Data.DateTime as DT
import Data.Maybe (maybe)
import Data.Time.Duration (Days(..))
tomorrow :: DT.Date -> DT.Date
tomorrow dt = maybe dt DT.date $ DT.adjust (Days 1.0) (DT.DateTime dt bottom)
Run Code Online (Sandbox Code Playgroud)
尽管在给定的日期不太可能发生的情况下它将返回输入日期top(如果我没有记错的话,它是275759年12月31日)。
有一个adjust功能Time,DateTime因此只是一个遗漏的疏忽Date。