I want to split ByteString
to words like so:
import qualified Data.ByteString as BS
main = do
input <- BS.getLine
let xs = BS.split ' ' input
But it appears that GHC can't convert a character literal to Word8
by itself, so I got:
Couldn't match expected type `GHC.Word.Word8'
with actual type `Char'
In the first argument of `BS.split', namely ' '
In the expression: BS.split ' ' input
Hoogle doesn't find anything with type signature of Char -> Word8
and Word.Word8 ' '
is invalid type constructor. Any ideas on how to fix it?
The Data.ByteString.Char8 module allows you to treat Word8
values in the bytestrings as Char
. Just
import qualified Data.ByteString.Char8 as C
then refer to e.g. C.split. It's the same bytestring under the hood, but the Char
-oriented functions are provided for convenient byte/ascii parsing.
In case you really need Data.ByteString (not Data.ByteString.Char8), you could do what Data.ByteString itself does to convert between Word8 to Char:
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BS (c2w, w2c)
main = do
input <- BS.getLine
let xs = BS.split (BS.c2w ' ') input
return ()
People looking for a simple Char -> Word8
with base library:
import Data.Word
charToWord8 :: Char -> Word8
charToWord8 = toEnum . fromEnum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With