gpt4 book ai didi

haskell - ByteString 到惰性文本,反之亦然

转载 作者:行者123 更新时间:2023-12-04 22:21:15 25 4
gpt4 key购买 nike

我在将 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
[..]

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

最佳答案

您正在混合 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

关于haskell - ByteString 到惰性文本,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com