Haskell 如何创建 Word8?

发布于 2024-12-28 10:13:41 字数 595 浏览 3 评论 0原文

我想编写一个简单的函数,使用 '\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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三生殊途 2025-01-04 10:13:41

您可以只使用数字文字 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文