许多类型的String(ByteString)

yai*_*chu 16 haskell bytestring

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

根据(最新的?)"Haskell流行度排名",zlib似乎是一个非常受欢迎的解决方案.zlib的界面使用ByteStrings:

compress :: ByteString -> ByteString
decompress :: ByteString -> ByteString
Run Code Online (Sandbox Code Playgroud)

我使用定期Strings,这也是由所使用的数据类型read,show以及Network.Socket:

sendTo :: Socket -> String -> SockAddr -> IO Int
recvFrom :: Socket -> Int -> IO (String, Int, SockAddr)
Run Code Online (Sandbox Code Playgroud)

所以要压缩我的字符串,我需要一些方法将a转换String为a ByteString,反之亦然.在hoogle的帮助下,我发现:

Data.ByteString.Char8 pack :: String -> ByteString
Run Code Online (Sandbox Code Playgroud)

试着用它:

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")
Run Code Online (Sandbox Code Playgroud)

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

所以基本上:

  • 有几种类型ByteString?什么类型,为什么?
  • Strings 转换为ByteStrings 的"方法"是什么?

顺便说一句,我发现,它并一起工作Data.ByteString.Lazy.Char8ByteString,但我仍然很感兴趣.

Ale*_*nov 10

有两种字节:strict(在Data.Bytestring.Internal中定义)和lazy(在Data.Bytestring.Lazy.Internal中定义).正如您所发现的,zlib使用延迟的字节串.

  • 不.`Char8`模块只为相同的字节串提供不同的接口. (4认同)
  • @Alexey Romanov:还有Char8/Word8的区别吗? (2认同)

fad*_*bee 8

您正在寻找的功能是:

import Data.ByteString as BS
import Data.ByteString.Lazy as LBS

lazyToStrictBS :: LBS.ByteString -> BS.ByteString
lazyToStrictBS x = BS.concat $ LBS.toChunks x
Run Code Online (Sandbox Code Playgroud)

我希望在没有x的情况下可以更简洁地编写.(即没有点,但我是Haskell的新手.)

  • 比如`lazyToStrictBS = BS.concat.LBS.toChunks` (2认同)

Don*_*art 6

更有效的机制可能是切换到完整的基于字节串的层:

  • 用于bytestring套接字的network.bytestring
  • 压缩字的延迟字节串
  • bytestring-show的二进制代替Show/Read

  • 我认为将大块的惰性字节串流入一个单独的字符串中并不太难.它本质上是mapM_ send.fromChunks (3认同)
  • @dons:当使用UDP时,如果你整个或以整体方式发送数据包,它实际上会有所不同.但你是否也说懒惰和严格字节串之间的转换很容易?知道这将是有用的.. (2认同)