Haskell mongodb:将二进制值转换回ByteString
这是一件简单而愚蠢的事情,我不能仅仅看到 如果定义了新类型:Haskell mongodb:将二进制值转换回ByteString,mongodb,haskell,Mongodb,Haskell,这是一件简单而愚蠢的事情,我不能仅仅看到 如果定义了新类型: newtype Binary Constructors Binary ByteString Instances: Eq Binary Ord Binary Read Binary Show Binary Typeable Binary Val Binary 如何解构二进制值以获取ByteString 如果我想将一个二进制数据保存到mongodb中,比如jpg图片,我就能够从文件系统读取的ByteStri
newtype Binary
Constructors
Binary ByteString
Instances:
Eq Binary
Ord Binary
Read Binary
Show Binary
Typeable Binary
Val Binary
如何解构二进制值以获取ByteString
如果我想将一个二进制数据保存到mongodb中,比如jpg图片,我就能够从文件系统读取的ByteString构造Val二进制类型。然后,我将其插入到文档中
当我从数据库中读取数据并将其从文档中取出时,我最终得到的是二进制类型,我很快就被它卡住了。我无法恢复ByteString类型以用于ByteString.writeFile
因此,跳过流中的所有连接内容如下所示:
file <- B.readFile "pic.jpg" -- reading file
let doc = ["file" =: (Binary file)] -- constructing a document to be inserted
run $ insert_ "files" doc -- insert the document
r <- run $ fetch (select [] "files") -- get Either Failure Document back from db
let d = either (error . show) (id ) r -- Get the Document out
let f = at "file" d :: Binary -- Get the data out of the document of type Binary
file假设您的newtype
如下所示
newtype Binary = Binary ByteString
然后,您可以简单地在构造函数上进行模式匹配,以返回ByteString
:
unBinary :: Binary -> ByteString
unBinary (Binary s) = s
假设您的newtype
如下所示
newtype Binary = Binary ByteString
然后,您可以简单地在构造函数上进行模式匹配,以返回ByteString
:
unBinary :: Binary -> ByteString
unBinary (Binary s) = s
谢谢,谢谢,谢谢!!!我知道这很愚蠢。)那么这是通过模式匹配来解构这样的新类型的正常方法吗?您还可以使用newtype Binary=Binary{unBinary::ByteString},这将为您创建函数。这是我通常的做法。@mindreader谢谢。如果我是自己创建newtype,我会做记录,但是newtype Binary是在库中定义的。我假设应该有一个类似于记录语法的反构造函数。但模式匹配也很有效,我真傻错过了这个。谢谢,谢谢,谢谢!!!我知道这很愚蠢。)那么这是通过模式匹配来解构这样的新类型的正常方法吗?您还可以使用newtype Binary=Binary{unBinary::ByteString},这将为您创建函数。这是我通常的做法。@mindreader谢谢。如果我是自己创建newtype,我会做记录,但是newtype Binary是在库中定义的。我假设应该有一个类似于记录语法的反构造函数。但模式匹配也很有效,我真傻错过了这个。