Haskell How to convert Char to Word8

Andrew picture Andrew · May 16, 2012 · Viewed 13.4k times · Source

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?

Answer

Don Stewart picture Don Stewart · May 16, 2012

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.