如何“包装”monadic返回值

时间:2015-06-16 10:35:33

标签: haskell monads

我有以下代码:

data APNSIdentifier = NoIdentifier | Identifier Word32 deriving (Show, Eq)
newtype APNSItem = Item Put

createNotificationIdentifierItem :: APNSIdentifier -> APNSItem   <--- here
createNotificationIdentifierItem (Identifier identifier) = do
    putWord8 3
    putWord16be 4
    putWord32be identifier

如何用Put“包裹”APNSItem monad?我是否必须使APNSItem成为Monad类型类的实例,或者是否有更简单的解决方案?

1 个答案:

答案 0 :(得分:0)

createNotificationIdentifierItem :: APNSIdentifier -> APNSItem
createNotificationIdentifierItem (Identifier identifier) = Item $ do
    putWord8 3
    putWord16be 4
    putWord32be identifier

createNotificationIdentifierItem :: APNSIdentifier -> APNSItem
createNotificationIdentifierItem (Identifier identifier) = do
    Item $ putWord8 3
    Item $ putWord16be 4
    Item $ putWord32be identifier

APNSItem Monad的实例后(您可以使用GeneralizedNewtypeDeriving执行此操作,但是您需要修复APNSItem才能拥有单个类型变量第一)