字符串 - > ByteString和反向

时间:2016-05-09 16:53:33

标签: haskell bytestring

在我的Haskell程序中,我需要使用Strings和ByteStrings:

import Data.ByteString.Lazy as BS  (ByteString)
import Data.ByteString.Char8 as C8 (pack)
import Data.Char                   (chr)

stringToBS :: String -> ByteString
stringToBS str = C8.pack str

bsToString :: BS.ByteString -> String
bsToString bs = map (chr . fromEnum) . BS.unpack $ bs

bsToString工作正常,但stringToBS会在编译时出现以下错误:

Couldn't match expected type ‘ByteString’
                with actual type ‘Data.ByteString.Internal.ByteString’
    NB: ‘ByteString’ is defined in ‘Data.ByteString.Lazy.Internal’
        ‘Data.ByteString.Internal.ByteString’
          is defined in ‘Data.ByteString.Internal’
    In the expression: pack str
    In an equation for ‘stringToBS’: stringToBS str = pack str

但我需要ByteString Data.ByteString.Lazy as BS (ByteString)来代替我的代码中的其他工作函数。

知道如何解决我的问题吗?

2 个答案:

答案 0 :(得分:3)

您正在使用两种不同类型的严格ByteStrings和lazy ByteStrings。

此导入:

import Data.ByteString.Lazy as BS  (ByteString)

使ByteString引用惰性字节索引,因此stringToBS的类型签名与其定义不匹配:

stringToBS :: String -> ByteString  -- refers to lazy ByteStrings
stringToBS str = C8.pack str        -- refers to strict ByteStrings

我认为最好像这样使用import qualified

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

并使用BS.ByteStringLBS.ByteString来引用严格/懒惰的ByteStrings。

答案 1 :(得分:1)

您可以使用fromStricttoStrict在惰性和非延迟版本之间进行转换(两个函数都在lazy bytestring模块中)。