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.
- Why is this the case?
- What is the best way to convert a ByteString to an Int?
Showis used to create aStringrepresentation of something, that is useful for debugging and plain-text serialization. TheShowtypeclass is not just a fancy way of converting anything into aString. That's whyByteStringadds quotes to the string: because it's arguably easier to read it that way when debugging or deserializing a data stream.You can use the
Data.ByteString.Char8.unpackfunction to convert aByteStringto aString, but note that this unpacks theByteStringbyte-per-byte, which messes up high-value Unicode characters or other characters that are stored as more than one byte; if you want to do something other than usingreadon the result, I'd recommend converting theByteStringtoTextinstead, which offers more flexibility in this situation. Assuming that your encoding is UTF8 in this case (As should be the default in Snap), you can use theData.Text.Encoding.decodeUtf8function for this. To then convert aTextvalue to aStringwith correct Unicode symbols, you useData.Text.unpack.Once you have a
String, you are free toreadit as much as you want; alternatively, you can choose to read aTextvalue directly using the functions in theData.Text.Readmodule.