[英]Haskell How to Create a Word8?
I want to write a simple function which splits a ByteString
into [ByteString]
using '\\n'
as the delimiter. 我想编写一个简单的函数,它使用
'\\n'
作为分隔符将ByteString
拆分为[ByteString]
。 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. 这会引发错误,因为
'\\n'
是Char
而不是Word8
,这正是Data.ByteString.splitWith
所期望的。
How do I turn this simple character into a Word8
that ByteString
will play with? 如何将这个简单的字符转换为
ByteString
将使用的Word8
?
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
). 你可以只使用数字文字
10
,但如果你想将字符转换的文字,你可以使用fromIntegral (ord '\\n')
该fromIntegral
需要将转换Int
是ord
返回到Word8
)。 You'll have to import Data.Char
for ord
. 你必须为
ord
导入Data.Char
。
You could also import Data.ByteString.Char8
, which offers functions for using Char
instead of Word8
on the same ByteString
data type. 您还可以导入
Data.ByteString.Char8
,它提供在同一ByteString
数据类型上使用Char
而不是Word8
函数。 (Indeed, it has a lines
function that does exactly what you want.) However, this is generally not recommended, as ByteString
s don't store Unicode codepoints (which is what Char
represents) but instead raw octets (ie Word8
s). (实际上,它有一个完全符合你想要的
lines
函数。)但是,这通常不推荐,因为ByteString
不存储Unicode代码点(这是Char
代表的),而是存储原始八位字节(即Word8
)。
If you're processing textual data, you should consider using Text
instead of ByteString
. 如果您正在处理文本数据,则应考虑使用
Text
而不是ByteString
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.