当您静态知道年 + 月 + 日有效时,如何在 Purescript 中简洁地创建日期

How do you concisely create a Date in Purescript, when you know statically that the year + month + date are valid

Data.Date.canonicalDate构造了一个Date值,但是你需要一个YearMonthDay值作为参数:

我目前的解决方案是这样的,这似乎是一个疯狂的 hack:

hackyMakeDate :: Int -> Month -> Int -> Date
hackyMakeDate year month day = fromMaybe (canonicalDate bottom bottom bottom) maybeDate
  where
    maybeDate = do
      year' <- toEnum year
      day' <- toEnum day
      pure $ canonicalDate year' month day'

有没有更简单的方法?

如果您同意在年 and/or 日超出范围时崩溃(我强烈建议您重新考虑这个决定),那么您可以使用 fromJust (which is a partial function) along with unsafePartial 来隐藏偏爱:

makeDate :: Int -> Month -> Int -> Date
makeDate year month day = 
    unsafePartial $ fromJust $ 
       canonicalDate <$> toEnum year <@> month <*> toEnum day

或者,您可以选择不隐藏偏爱:

partialMakeDate :: Partial => Int -> Month -> Int -> Date
partialMakeDate year month day = 
    fromJust $ 
       canonicalDate <$> toEnum year <@> month <*> toEnum day

这样,至少你的消费者会知道这个功能真的很偏。