簡體   English   中英

將Haskell類型與MongoDB嵌套數據一起使用的“正確方法”是什么?

[英]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

看起來你只是在你的實例中顛倒了transintransout實現。 你的transin拿一張Ticket並返回Field的列表; 但那是transout的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM