views:

158

answers:

2

What is the best way to convert a String to a ByteString in Haskell?

My gut reaction to the problem is

import qualified Data.ByteString as B
import Data.Char (ord)

packStr = B.pack . map (fromIntegral . ord)

But this doesn't seem satisfactory.

+11  A: 

Data.ByteString[.Lazy].Char8.pack

You can typically use hoogle to find functions.

TomMD
+1  A: 

Data.ByteString.UTF8.fromString is also useful. The Char8 version will lose the unicode-ness and UTF8 will make a UTF8-encoded ByteString. You have to choose one or the other.

Peaker
In case the question comes up: this function is not located by Hoogle because it only indexes a small set of libraries (those shipped with GHC). Expanding the set of libraries indexed by Hoogle has came up several times but hasn't been done I think due to time constraints of the Hoogle developer (Neil).FYI, the function discussed here is from the utf8-string package.
TomMD
@TomMD: Hayoo addresses this: http://holumbus.fh-wedel.de/hayoo/hayoo.html#0:String%20-%3E%20ByteString
Peaker
@peaker: Not to my satisfaction. Hayoo does a poor job at type search, particularly when the type is general or polymorphic.
TomMD