How to go from String to Data.ByteString.Lazy in an existing Haskell code?
I have a Haskell code which use a lot of String, while profilling it, it appear that the code use a lot of memory to store Lists []. One solution to this problem is to use Data.ByteString.Lazy instead of String, but
what I have to care about while doing this ?,
which part of the code have to be 开发者_如何学Clook carefully : fold, map, ... ?
thanks for reply
The OverloadedStrings extension can be handy if you're using GHC and are converting code with a lot of string literals. Just add the following to the top of your source file:
{-# LANGUAGE OverloadedStrings #-}
And you don't have to use B.pack
on any string literals in your code. You could have the following, for example:
equalsTest :: B.ByteString -> Bool
equalsTest x = x == "Test"
Without the extension this would give an error, since you can't use ==
on a ByteString
and a [Char]
. With the extension, string literals have type (IsString a) => a
, and ByteString
is an instance of IsString
, so "Test"
here is typed as a ByteString
and there's no error.
You should know, that a ByteString
is really bad for things like iteration over it elements, but better for Concatation, etc.
If you want to work with ByteStrings, you have to convert the String to a ByteString, just do something like
import Data.ByteString.Lazy as B
and stick a B
in front of each function which works with them - most functions for String
also exists for ByteString
. Please notice - you have to convert the Strings you use to a ByteString with some functions.
If you use Data.ByteString.Lazy.Char8
instead, you can easily use pack
, but all chars greater than 255 will be truncated. Also, this type is more suitable for binary data and safes memory.
Edit: You should consider using the package text, if you want to work on text-strings. Look here for further details.
精彩评论