gpt4 book ai didi

haskell - 将 Haskell 类型与 MongoDB 嵌套数据一起使用的 'right way' 是什么?

转载 作者:行者123 更新时间:2023-12-02 05:20:26 27 4
gpt4 key购买 nike

我在 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 的类似实例。

此外,我会使用类型同义词 Document 来表示 [Field]

关于haskell - 将 Haskell 类型与 MongoDB 嵌套数据一起使用的 'right way' 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4410428/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com