[英]What is the 'right way' to use Haskell types with MongoDB nested data?
我在Haskell中有兩個簡單的數據類型:
data Ticket = Ticket {
tbody :: String,
tauthor :: String,
tcomments :: [TicketComment]
}
data TicketComment = TicketComment {
tcbody :: String,
tcauthor :: String
}
暫時忽略時間戳的缺失,以及字符串與字節串的使用,我只想將注釋存儲在嵌套在票證中的MongoDB中。
到目前為止,我一直在使用一個相當簡單的實例來存儲數據:
class MongoIO a where
transout :: a -> [Field]
transin :: [Field] -> (Maybe a)
然后實現看起來像這樣:
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)
正如預期的那樣,這會在("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)
加上TicketComment
類似實例。
我也會使用[Field]
的類型同義詞Document
。
看起來你只是在你的實例中顛倒了transin
和transout
實現。 你的transin
拿一張Ticket
並返回Field
的列表; 但那是transout
的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.