Home > Enterprise >  How to convert Data.Text.Internal.Text to Data.ByteString.Lazy.Bytestring (Text to Lazy Bytestring)?
How to convert Data.Text.Internal.Text to Data.ByteString.Lazy.Bytestring (Text to Lazy Bytestring)?

Time:09-17

I vaguely recall a textual conversion table for Haskell textual type, but I can't find this anymore.

How can convert to do the conversion for Data.Text.Internal.Text -> Data.ByteString.Lazy.ByteString? Hoogle unfortunately shows no results.

CodePudding user response:

The elements of a Text are Char, which are unicode code points. The elements of a ByteString are eight bit words. So in order to convert Text to ByteString we will need to choose an encoding. This is almost always UTF-8, hence encodeUtf8:

% ghci
> :m  Data.Text
> :m  Data.Text.Encoding
> :m  Data.ByteString.Lazy
> let t = Data.ByteString.Lazy.fromStrict (encodeUtf8 (Data.Text.pack "Qi Baishi 齊白石"))
> t
"Qi Baishi \233\189\138\231\153\189\231\159\179"

CodePudding user response:

import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL

import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T


f1 :: T.Text -> TL.Text
f1 = TL.fromStrict

f2 :: TL.Text -> BL.ByteString
f2 = TL.encodeUtf8

f3 :: T.Text -> BL.ByteString
f3 = f2 . f1 
  • Related