将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实际使用的内容有关,在他们的源代码中他们似乎使用普通的bytestring,它应该与我的实现一起使用.看这里:
[..] import qualified Data.ByteString as S [..] encryptIO :: Key -> S.ByteString -> IO S.ByteString [..]
那么为什么我会得到所有这些错误?谢谢.
解决方法
您正在混合Data.ByteString.ByteString和Data.ByteString.Lazy.ByteString.因为类型名称相等,GHC可以(并且确实)产生可怕的错误消息.我使用ByteString和Text的显式导入重新编写它,希望它现在更加明显:
{-# 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。