Alex Rivera | Logout

What is the best way to convert a ByteString to an Int?

Asked 2012-01-16T23:25:52.547
11

I always run into the following error when trying to read a ByteString:
Prelude.read: no parse

Here's a sample of code that will cause this error to occur upon rendering in a browser:

factSplice :: SnapletSplice App App
factSplice = do
    mbstr <- getParam "input" -- returns user input as bytestring
    let str = maybe (error "splice") show mbstr
    let n = read str :: Int
    return [X.TextNode $ T.pack $ show $ product [1..n]]

Or perhaps more simply:

simple bs = read (show bs) :: Int

For some reason, after show bs the resulting string includes quotes. So in order to get around the error I have to remove the quotes then read it. I use the following function copied from the internet to do so:

sq :: String -> String
sq s@[c]                     = s
sq ('"':s)  | last s == '"'  = init s
            | otherwise      = s
sq ('\'':s) | last s == '\'' = init s
            | otherwise      = s
sq s                         = s

Then simple bs = read (sq.show bs) :: Int works as expected.

  1. Why is this the case?
  2. What is the best way to convert a ByteString to an Int?
Edit
Report

1 Answer

13

What the best way to convert a ByteString to an X is depends onX. If you have a good conversion from String, going via Data.BytString.Char8.unpack can be good, if it's an ASCII ByteString. For UTF-8 encoded ByteStrings, the utf8-string package contains the conversion function toString. For some specific types, like Int, as mentioned in the title, special faster conversions exist. For example Data.ByteString.Char8.readInt and readInteger.

answered 2012-01-16T23:40:42.287

Your Answer