【发布时间】:2012-08-14 01:54:00
【问题描述】:
所以,我已经用头撞墙至少一个小时了。这是我的问题:
我的一个函数返回[(Text, Text)]。
现在我想使用这个元组列表在 Data.Bson 中填充 Document。
打开扩展名OverloadedStrings,并导入Data.Text 以及Data.Bson,我会这样做(这部分是从原始帖子编辑的,我粘贴了实际上没有的代码的调试版本使用累加器):
tuplesToBSON :: [(Text, Text)] -> Document
tuplesToBSON xs = L.foldr (\v acc -> merge [fst v =: snd v] acc) [] xs
merge 来自 Data.Bson 包,=: 也是如此。
运气不好。它抱怨:无法将预期类型 Label 与实际类型 Text 匹配。 (为了清楚起见,下面也是一个编辑)如果我尝试:
tuplesToBSON xs = L.foldr (\v acc -> merge [(fst v) =: (String (snd v))] acc ) [] xs
不幸的是,这个名为 String 的构造函数实际上是来自 Bson 包的构造函数(我认为......),用于名为“Value”的数据类型。 http://hackage.haskell.org/packages/archive/bson/0.2.1/doc/html/src/Data-Bson.html
这仍然不起作用-但出现不同的错误消息:
No instance for (Val Value) arising from a use of `=:'
Possible fix: add an instance declaration for (Val Value)
In the expression: (fst v) =: (String (snd v))
In the first argument of `merge', namely `[(fst v) =: (String (snd v))]'
In the expression: merge [(fst v) =: (String (snd v))] acc
还有:
Couldn't match expected type `Label' with actual type `Text'
Expected type: [(Label, text-0.11.2.0:Data.Text.Internal.Text)] Actual type: [(Text, Text)]
In the third argument of `L.foldr', namely `xs'
In the expression: L.foldr (\ v acc -> merge [(fst v) =: (String (snd v))] acc) [] xs
我知道 Value 是 Bson 包中的一种数据类型,但我真的不知道 Val 是什么。
===== 不相关部分的开始 =====
正如下面的答案之一指出的那样,在原始帖子中,我的代码中有:: String 将Text“转换”为String,就像在前奏中一样。我实际上以为:: String 指的是Bson 包中提到的那个,但无论如何我完全错了,因为(我认为)String 实际上是一个构造函数。
我怀疑 GHC 类型推断在某种程度上被混淆了,因为以下工作正常:
testDocument :: Document
testDocument = [(fst ("asdf", "awef") :: Label) =: ("asdf" :: String)]
编辑:这可行,但必须是因为 Bson 自动进行了一些正确的类型处理,因为在包含 import Prelude hiding (String) 行之后,它给了我一个错误。
所以我终于解决了这个问题。对不起之前的混乱版本——我很沮丧。
【问题讨论】:
-
顺便说一句,您正在将
acc丢在地板上。也许您打算使用((fst v) := (snd v)) : acc而不是只返回一个 1 元素列表? -
哦,是的,那实际上还是调试代码 :)
标签: haskell