How to go from String to Data.ByteString.Lazy in existing Haskell code?

I have Haskell code that uses a lot of String, and when profiling it, it looks like the code uses a lot of memory to store lists []. One solution to this problem is to use Data.ByteString.Lazy instead of String, but

what do i need to do during this?

What part of the code should I look carefully at: fold, map, ...?

thanks for the answer

+4
source share
2 answers

You should know that ByteString really bad for things like iterating over them, but better for Concatation, etc.

If you want to work with ByteStrings, you need to convert String to ByteString, just do something like

 import Data.ByteString.Lazy as B 

and stick with B before every function that works with them - most functions for String also exist for ByteString . Please note: you need to convert the strings you use in ByteString with some features.

If you use Data.ByteString.Lazy.Char8 , you can easily use pack , but all characters greater than 255 will be truncated. In addition, this type is more suitable for binary data and safe memory.

Edit:. You must use package text if you want to work with text strings. Look here for more details.

+2
source

The OverloadedStrings extension can be convenient if you use GHC and convert code with a lot of string literals. Just add the following to the top of the source file:

 {-# LANGUAGE OverloadedStrings #-} 

And you do not need to use B.pack for any string literals in your code. You may have the following, for example:

 equalsTest :: B.ByteString -> Bool equalsTest x = x == "Test" 

Without the extension, this would give an error, since you cannot use == on ByteString and a [Char] . With the extension, string literals are of type (IsString a) => a , and ByteString is an instance of IsString , so "Test" is entered here as ByteString and there is no error.

+5
source

All Articles