[Haskell-cafe] How to put a string into Data.Binary.Put
John Millikin
jmillikin at gmail.com
Sat Nov 6 10:33:50 EDT 2010
Use one of the Char8 modules, depending on whether you want a strict
or lazy bytestring:
-----------------------------------------------------------------------
import qualified Data.ByteString.Lazy.Char8 as BS
message :: BS.ByteString
message = BS.pack "SOME STRING"
-----------------------------------------------------------------------
See the docs at:
http://hackage.haskell.org/packages/archive/bytestring/0.9.1.7/doc/html/Data-ByteString-Char8.html
http://hackage.haskell.org/packages/archive/bytestring/0.9.1.7/doc/html/Data-ByteString-Lazy-Char8.html
mapping over putWord8 is much slower than putting a single bytestring;
if you want to put a string, pack it first:
-----------------------------------------------------------------------
putString :: String -> Put
putString str = putLazyByteString (BS.pack str)
-- alternative: probably faster
import qualified Data.ByteString.Char8 as B
putString :: String -> Put
putString str = putByteString (B.pack str)
-----------------------------------------------------------------------
On Sat, Nov 6, 2010 at 05:30, C K Kashyap <ckkashyap at gmail.com> wrote:
> Hi,
> I was trying to put a String in a ByteString
>
> import qualified Data.ByteString.Lazy as BS
> message :: BS.ByteString
> message = runPut $ do
> let string="SOME STRING"
> map (putWord8.fromIntegral.ord)
> string -- this ofcourse generates [Put]
>
> How can I convert the list of Put's such that it could be used in the Put monad?
>
> For now I used the workaround of first converting the string to
> ByteString like this -
>
> stringToByteString :: String -> BS.ByteString
> stringToByteString str = BS.pack (map (fromIntegral.ord) str)
>
> and then using putLazyByteString inside the Put monad.
>
> --
> Regards,
> Kashyap
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
More information about the Haskell-Cafe
mailing list