Simon H
Simon H

Reputation: 21047

Lazy bytestring insanity

I'm really struggling to square this circle.

getPostContent uses Wreq to download a blog post and return it.

getPostContent url = do
    let opts = defaults & W.checkStatus .~ (Just $ \_ _ _ -> Nothing)

    postResp <- getWith opts $ baseUrl ++ url
    if postResp ^. W.responseStatus . statusCode == 200
        -- then return $ LEnc.encodeUtf8 $ postResp ^. W.responseBody . _String      -- :: Prism T Text
        then return $ postResp ^. W.responseBody . _String
        else return "error downloading"

This is consumed by parseLBS

do
     page <- getPostContent r -- :: IO String
     let
     -- parseLBS :: Data.ByteString.Lazy.Internal.ByteString -> Text.XML.Document
     cursor = fromDocument $ parseLBS page

As I understand it, getPostContent is providing Data.Text.Text, whereas I need Data.ByteString.Lazy.Internal.ByteString and I cannot work out how to convert them ( thought it should be this, see code snippet above, but it does not compile either).

   Couldn't match expected type ‘Data.ByteString.Lazy.Internal.ByteString’
                with actual type ‘T.Text’
    In the first argument of ‘parseLBS’, namely ‘page’
    In the second argument of ‘($)’, namely ‘parseLBS page’

Compilation message with encode uncommented

Couldn't match type ‘TL.Text’
               with ‘T.Text’
NB: ‘TL.Text’ is defined in ‘Data.Text.Internal.Lazy’
    ‘T.Text’ is defined in ‘Data.Text.Internal’
Expected type: (TL.Text -> Const TL.Text TL.Text)
               -> Data.ByteString.Lazy.Internal.ByteString
               -> Const TL.Text Data.ByteString.Lazy.Internal.ByteString
  Actual type: (T.Text -> Const TL.Text T.Text)
               -> Data.ByteString.Lazy.Internal.ByteString
               -> Const TL.Text Data.ByteString.Lazy.Internal.ByteString
In the second argument of ‘(.)’, namely ‘_String’
In the second argument of ‘(^.)’, namely ‘responseBody . _String’

Upvotes: 1

Views: 144

Answers (1)

MathematicalOrchid
MathematicalOrchid

Reputation: 62868

To summarise: encodeUtf8 is the right way to go. It seems the one you're using is from Data.Text.Lazy.Encoding, which requires a lazy Text. You can use Data.Text.Lazy.fromStrict to convert... Or you can look into Data.Text.Encoding, which works on strict Text (but then gives you a strict ByteString...)

Upvotes: 2

Related Questions