我想要一个带有时间戳值的类型,它具有适当的Semigroup
实例(最新值获胜)。事实证明Max (Arg UTCTime a)
完全符合我的要求,但直接合作真的很尴尬所以我写了这个:
import Data.Semigroup
import Data.Thyme ()
import Data.Thyme.Clock
newtype Stamped a =
Stamped' (Max (Arg UTCTime a))
deriving (Show, Eq, Semigroup, Functor)
-- Many other useful classes could be added here
pattern Stamped :: UTCTime -> a -> Stamped a
pattern Stamped s v = Stamped' (Max (Arg s v))
unstamp :: Max (Arg a b) -> b
unstamp (Max (Arg _ v)) = v
stamp :: IO a -> IO (Stamped a)
stamp a = do
ts <- getCurrentTime
result <- a
pure (Stamped ts result)
还有其他一些助手:
updateStamped :: TVar (Stamped a) -> Stamped a -> STM ()
updateStamped v n = modifyTVar v (<> n)
updateStamped' :: TVar (Stamped a) -> Stamped a -> STM ()
updateStamped' v n = modifyTVar' v (<> n)
有更好的方法吗?我还没有看到模式同义词与这样的新类型一起使用,所以我觉得我错过了一些更惯用的东西。