Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I save a variable as a bytestring?

Ik this is a dumb question, but if I have this:

a :: B.ByteString
a = "a"

I get an error that says "Couldn’t match type B.ByteString with type [Char]". I know what’s the problem but I don’t know how to fix it, could you help? thx.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Character string literals in Haskell, by default, are always treated as String, which is equivalent to [Char]. Most string-like data structures define a function called pack to convert from, and the bytestring package is no exception (Note that this is pack from Data.ByteString.Char8; the one in Data.ByteString converts from [Word8]).

import Data.ByteString.Char8(pack)

a :: B.ByteString
a = pack "a"

However, GHC also supports an extension called OverloadedStrings. If you’re willing to enable this, ByteString implements a typeclass called IsString. With this extension enabled, the type of a string literal like "a" is no longer [Char] and is instead forall a. IsString a => a (similar to how the type of numerical literals like 3 is forall a. Num a => a). This will happily specialize to ByteString if the type is in scope.

{-# LANGUAGE OverloadedStrings #-}

a :: B.ByteString
a = "a"

If you go this route, make sure you understand the proviso listed in the docs for this instance. For ASCII characters, it won’t pose a problem, but if your string has Unicode characters outside the ASCII range, you need to be aware of it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading