ByteString为惰性文本,反之亦然

时间:2013-09-12 14:30:21

标签: haskell text types bytestring

将ByteString转换为Text时出现问题,反之亦然。这是代码:

{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Web.ClientSession

import Data.Text.Lazy (Text, toStrict, fromStrict)
import Data.Text.Lazy.Encoding (encodeUtf8, decodeUtf8)
import Data.ByteString (ByteString)

import Data.Monoid ((<>))

initCookies :: IO (Text -> ActionM ())
initCookies = do
  key <- getDefaultKey
  return $ setCookie key
  where
    setCookie k id = encryptIO k (encode id) 
      >>= (\x -> header "Set-Cookie" ("sid=" <> decode x <> ";"))

encode :: Text -> ByteString
encode = encodeUtf8 . toStrict

decode :: ByteString -> Text
decode = fromStrict . decodeUtf8

和错误消息:

foo.hs:16:35:
Couldn't match expected type `bytestring-0.10.0.2:Data.ByteString.Internal.ByteString'
with actual type `ByteString'
In the return type of a call of `encode'
In the second argument of `encryptIO', namely `(encode id)'
In the first argument of `(>>=)', namely `encryptIO k (encode id)'

foo.hs:17:18:
Couldn't match type `ActionM' with `IO'
Expected type: IO ()
Actual type: ActionM ()
In the return type of a call of `header'
In the expression: header "Set-Cookie" ("sid=" <> decode x <> ";")
In the second argument of `(>>=)', namely
`(\ x -> header "Set-Cookie" ("sid=" <> decode x <> ";"))'

foo.hs:17:56:
Couldn't match expected type `ByteString'
with actual type `bytestring-0.10.0.2:Data.ByteString.Internal.ByteString'
In the first argument of `decode', namely `x'
In the first argument of `(<>)', namely `decode x'
In the second argument of `(<>)', namely `decode x <> ";"'

所以,我猜这个错误与ClientSession实际使用的内容有关,在他们的源代码中他们似乎使用普通的字符串,这应该与我的实现一起使用。看这里:

[..]
import qualified Data.ByteString as S
[..]
encryptIO :: Key -> S.ByteString -> IO S.ByteString
[..]

那么为什么我会得到所有这些错误?感谢。

2 个答案:

答案 0 :(得分:9)

您正在混合Data.ByteString.ByteStringData.ByteString.Lazy.ByteString。因为类型名称相等,GHC可以(并且确实)产生可怕的错误消息。我使用ByteStringText的显式导入对其进行了重写,希望它现在更加明显:

{-# LANGUAGE OverloadedStrings #-}

import Web.Scotty
import Web.ClientSession

import Control.Monad.Trans (liftIO)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.ByteString as B
import qualified Data.ByteString as BL

import Data.Monoid ((<>))

initCookies :: IO (TL.Text -> ActionM ())
initCookies = do
  key <- getDefaultKey
  return $ setCookie key
  where
    setCookie k id = liftIO (encryptIO k (encode id))
      >>= (\x -> header "Set-Cookie" ("sid=" <> decode x <> ";"))

encode :: TL.Text -> B.ByteString
encode = T.encodeUtf8 . TL.toStrict

decode :: B.ByteString -> TL.Text
decode = TL.fromStrict . T.decodeUtf8

答案 1 :(得分:2)

Data.String.Conversions包使用单个cs转换函数抽象出该知识,根据调用的上下文调用该版本(即输入和预期类型)。

相关问题