Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell How to convert Char to Word8

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?

like image 653
Andrew Avatar asked May 16 '12 17:05

Andrew


3 Answers

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.

like image 127
Don Stewart Avatar answered Nov 20 '22 17:11

Don Stewart


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 ()
like image 17
grwlf Avatar answered Nov 20 '22 16:11

grwlf


People looking for a simple Char -> Word8 with base library:

import Data.Word

charToWord8 :: Char -> Word8
charToWord8 = toEnum . fromEnum
like image 3
Hussein AIT LAHCEN Avatar answered Nov 20 '22 16:11

Hussein AIT LAHCEN