Haskell 如何创建 Word8?
我想编写一个简单的函数,使用 '\n'
作为分隔符将 ByteString
拆分为 [ByteString]
。我的尝试:
import Data.ByteString
listize :: ByteString -> [ByteString]
listize xs = Data.ByteString.splitWith (=='\n') xs
这会引发错误,因为 '\n'
是 Char
而不是 Word8
,这就是 Data.ByteString.splitWith
< /a> 正在等待。
如何将这个简单的字符转换为 ByteString
可以使用的 Word8
?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以只使用数字文字
10
,但如果您想转换字符文字,可以使用fromIntegral (ord '\n')
(fromIntegral<需要 /code> 将
ord
返回的Int
转换为Word8
)。您必须为ord
导入Data.Char
。您还可以导入
Data.ByteString.Char8
,它提供了在相同
ByteString
数据类型上使用Char
而不是Word8
的函数。 (事实上,它有行
函数完全符合您的要求。)但是,通常不推荐这样做,因为ByteString
不 em> 存储 Unicode 代码点(这就是Char
代表),而是原始八位字节(即Word8
)。如果您正在处理文本数据,则应考虑使用
Text
而不是ByteString
。You could just use the numeric literal
10
, but if you want to convert the character literal you can usefromIntegral (ord '\n')
(thefromIntegral
is required to convert theInt
thatord
returns into aWord8
). You'll have to importData.Char
forord
.You could also import
Data.ByteString.Char8
, which offers functions for usingChar
instead ofWord8
on the sameByteString
data type. (Indeed, it has alines
function that does exactly what you want.) However, this is generally not recommended, asByteString
s don't store Unicode codepoints (which is whatChar
represents) but instead raw octets (i.e.Word8
s).If you're processing textual data, you should consider using
Text
instead ofByteString
.