Haskell How to Create a Word8?

巧了我就是萌 提交于 2019-12-09 14:45:44

问题


I want to write a simple function which splits a ByteString into [ByteString] using '\n' as the delimiter. My attempt:

import Data.ByteString

listize :: ByteString -> [ByteString]
listize xs = Data.ByteString.splitWith (=='\n') xs

This throws an error because '\n' is a Char rather than a Word8, which is what Data.ByteString.splitWith is expecting.

How do I turn this simple character into a Word8 that ByteString will play with?


回答1:


You could just use the numeric literal 10, but if you want to convert the character literal you can use fromIntegral (ord '\n') (the fromIntegral is required to convert the Int that ord returns into a Word8). You'll have to import Data.Char for ord.

You could also import Data.ByteString.Char8, which offers functions for using Char instead of Word8 on the same ByteString data type. (Indeed, it has a lines function that does exactly what you want.) However, this is generally not recommended, as ByteStrings don't store Unicode codepoints (which is what Char represents) but instead raw octets (i.e. Word8s).

If you're processing textual data, you should consider using Text instead of ByteString.



来源:https://stackoverflow.com/questions/8966439/haskell-how-to-create-a-word8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!