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.Char8的ByteString,但我仍然很感兴趣.
Ale*_*nov 10
有两种字节串:strict(在Data.Bytestring.Internal中定义)和lazy(在Data.Bytestring.Lazy.Internal中定义).正如您所发现的,zlib使用延迟的字节串.
您正在寻找的功能是:
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的新手.)
更有效的机制可能是切换到完整的基于字节串的层: