Reputation: 1965
See this related SO question: Automatic conversion between String and Data.Text in haskell
Given a string of type Text
, I want to produce a lazy bytestring.
This works, but I wondered whether it's optimal, given the fact that both Text
and the lazy bytestring have the property of being "string-like" and I still use the not-generic unpack
:
import qualified Data.ByteString.Lazy (ByteString)
import Data.Text (Text, unpack)
import Data.String (fromString)
import Data.Text (unpack)
convert :: IsString str => Text -> str
convert = fromString . unpack
I found the package string-conversions that offers the polymorphic function
convertString :: a -> b
as part of the ConvertibleStrings
typeclass.
While it works fine, I am suspicious: Why would I need an extra package for that? Couldn't there be already a typeclass like IsString
that offers a toString
method and in combination a universal convert function fromString . toString
?
Upvotes: 1
Views: 786
Reputation: 1965
[Ok, while I was editing my question, a possible answer dawned to me]
On the hackage-page of string-conversions it says:
Assumes UTF-8 encoding for both types of ByteStrings.
So there are assumptions that go along with conversions and a universal conversion of string-like types might not be desirable. Also performance probably depends on the input and output types and a universal conversion would pretend that it's all the same.
So my take on best practice is now this, being explicit rather than polymorphic:
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as ByteString
import qualified Data.Text.Encoding as Text
convert :: Text -> ByteString
convert = ByteString.fromStrict . Text.encodeUtf8
Upvotes: 2