haskell - 多种类型的字符串(ByteString)

标签 haskell bytestring

我希望压缩我的应用程序的网络流量。

根据(最新?)"Haskell Popularity Rankings" , zlib似乎是一个非常受欢迎的解决方案。 zlib的接口(interface)使用ByteStrings:

compress :: ByteString -> ByteString
decompress :: ByteString -> ByteString

我使用常规的String,它们也是readshowNetwork.Socket使用的数据类型:

sendTo :: Socket -> String -> SockAddr -> IO Int
recvFrom :: Socket -> Int -> IO (String, Int, SockAddr)

因此,为了压缩我的字符串,我需要某种方法将 String 转换为 ByteString,反之亦然。 与hoogle在 的帮助下,我发现:

Data.ByteString.Char8 pack :: String -> ByteString

尝试使用它:

Prelude Codec.Compression.Zlib Data.ByteString.Char8> compress (pack "boo")

<interactive>:1:10:
    Couldn't match expected type `Data.ByteString.Lazy.Internal.ByteString'
           against inferred type `ByteString'
    In the first argument of `compress', namely `(pack "boo")'
    In the expression: compress (pack "boo")
In the definition of `it': it = compress (pack "boo")

失败,因为(?)有不同类型的ByteString

所以基本上:

  • ByteString 有多种类型吗?有哪些类型,为什么?
  • String 转换为 ByteString 的“方法”是什么?

顺便说一句,我发现它确实可以与 Data.ByteString.Lazy.Char8ByteString 配合使用,但我仍然很感兴趣。

最佳答案

有两种字节串:严格(在 Data.Bytestring.Internal 中定义)和惰性(在 Data.Bytestring.Lazy.Internal 中定义)。正如您所发现的,zlib 使用惰性字节串。

关于haskell - 多种类型的字符串(ByteString),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1451755/

相关文章:

haskell - :~: and :~~: equalities? 和有什么区别

haskell - 为什么不能在提示中将顶级模块设置为 main

haskell - 隐藏数据类型的构造函数

arrays - 数据类型到 ByteString

haskell - Haskell 中字节流的高效流式传输和操作

list - 是否有一个函数可以展平嵌套的元素列表?

Haskell 添加两个列表模式匹配

haskell - 如何将二进制网络数据包结构映射到 Haskell 标准数据类型(记录)?

performance - 为什么 ByteString 不是 Vector Word8?

haskell - 是否可以在 Haskell 的 HXT 上使用 Text 或 ByteString?