我在Haskell中有两个简单的数据类型:
data Ticket = Ticket {
tbody :: String,
tauthor :: String,
tcomments :: [TicketComment]
}
data TicketComment = TicketComment {
tcbody :: String,
tcauthor :: String
}
Run Code Online (Sandbox Code Playgroud)
暂时忽略时间戳的缺失,以及字符串与字节串的使用,我只想将注释存储在嵌套在票证中的MongoDB中.
到目前为止,我一直在使用一个相当简单的实例来存储数据:
class MongoIO a where
transout :: a -> [Field]
transin :: [Field] -> (Maybe a)
Run Code Online (Sandbox Code Playgroud)
然后实现看起来像这样:
instance MongoIO Ticket where
transout a = [("body" =: tbody a),
("author" =: tauthor a),
("comments" =: tcomments a)]
transin a = case (,,) <$> look "body" a
<*> look "author" a
<*> look "comments" a of
Nothing -> Nothing
Just (bo,au,co) ->
Just $ Ticket (typed bo) (typed au) (typed co)
Run Code Online (Sandbox Code Playgroud)
正如所料,这打破了("comments" =: tcomments a).我有信心进入Haskell类型的领域,我自己的知识缺乏,所以我很高兴听到其他人会如何处理这个问题.
您还必须翻译嵌入的文档.所以
instance MongoIO Ticket where
transout t = [
"body" =: tbody t,
"author" =: tauthor t,
"comments" =: map transout (tcomments t) ]
transin d = Ticket
<$> lookup "body" d
<*> lookup "author" d
<*> (mapM transin =<< lookup "comments" d)
Run Code Online (Sandbox Code Playgroud)
加上类似的实例TicketComment.
此外,我将使用类型代名词Document了[Field].
| 归档时间: |
|
| 查看次数: |
1018 次 |
| 最近记录: |