Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String -> ByteString and reverse

In my Haskell Program I need to work with Strings and ByteStrings:

import Data.ByteString.Lazy as BS  (ByteString)
import Data.ByteString.Char8 as C8 (pack)
import Data.Char                   (chr)

stringToBS :: String -> ByteString
stringToBS str = C8.pack str

bsToString :: BS.ByteString -> String
bsToString bs = map (chr . fromEnum) . BS.unpack $ bs

bsToString works fine, but stringToBS results with following error at compiling:

Couldn't match expected type ‘ByteString’
                with actual type ‘Data.ByteString.Internal.ByteString’
    NB: ‘ByteString’ is defined in ‘Data.ByteString.Lazy.Internal’
        ‘Data.ByteString.Internal.ByteString’
          is defined in ‘Data.ByteString.Internal’
    In the expression: pack str
    In an equation for ‘stringToBS’: stringToBS str = pack str

But I need to let it be ByteString from Data.ByteString.Lazy as BS (ByteString) for further working functions in my code.

Any idea how to solve my problem?

like image 282
Martin Fischer Avatar asked May 09 '16 16:05

Martin Fischer


2 Answers

You are working with both strict ByteStrings and lazy ByteStrings which are two different types.

This import:

import Data.ByteString.Lazy as BS  (ByteString)

makes ByteString refer the lazy ByteStrings, so the type signature of your stringToBS doesn't match it's definition:

stringToBS :: String -> ByteString  -- refers to lazy ByteStrings
stringToBS str = C8.pack str        -- refers to strict ByteStrings

I think it would be a better idea to use import qualified like this:

import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as BS

and use BS.ByteString and LBS.ByteString to refer to strict / lazy ByteStrings.

like image 101
ErikR Avatar answered Oct 29 '22 17:10

ErikR


You can convert between lazy and non-lazy versions using fromStrict, and toStrict (both functions are in the lazy bytestring module).

like image 38
jamshidh Avatar answered Oct 29 '22 18:10

jamshidh