gpt4 book ai didi

string - Haskell 如何创建 Word8?

转载 作者:行者123 更新时间:2023-12-04 00:57:05 24 4
gpt4 key购买 nike

我想写一个简单的函数来分割 ByteString进入 [ByteString]使用 '\n'作为分隔符。我的尝试:

import Data.ByteString

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

这会引发错误,因为 '\n'Char而不是 Word8 ,这就是 Data.ByteString.splitWith 期待。

如何将这个简单的字符变成 Word8ByteString会玩吗?

最佳答案

您可以只使用数字文字 10 , 但是如果你想转换字 rune 字你可以使用 fromIntegral (ord '\n') (需要 fromIntegral 才能将 Int 返回的 ord 转换为 Word8 )。您必须导入 Data.Char对于 ord .

您也可以导入 Data.ByteString.Char8 ,它提供了使用 Char 的功能而不是 Word8在同一个 ByteString数据类型。 (确实,它有一个 lines 函数,可以完全满足您的需求。)但是,通常不建议这样做,因为 ByteString s 不存储 Unicode 代码点(Char 表示的内容),而是原始八位字节(即 Word8 s)。

如果您正在处理文本数据,您应该考虑使用 Text 而不是 ByteString .

关于string - Haskell 如何创建 Word8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8966439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com