string - 文本或字节串

标签 string haskell text

美好的一天。

我现在讨厌 Haskell 的一件事是用于处理字符串的软件包数量。

首先,我使用原生 Haskell [Char] 字符串,但是当我尝试开始使用 hackage 库时,我完全迷失在无休止的转换中。每个包似乎都使用不同的字符串实现,有些采用自己手工制作的东西。

接下来我用 Data.Text 字符串和 OverloadedStrings 扩展重写了我的代码,我选择 Text 因为它有更广泛的功能,但似乎很多项目更喜欢 ByteString
有人可以给出简短的推理为什么要使用其中一种或另一种吗?

PS:顺便问一下,如何从 Text 转换为 ByteString

Couldn't match expected type Data.ByteString.Lazy.Internal.ByteString against inferred type Text Expected type: IO Data.ByteString.Lazy.Internal.ByteString Inferred type: IO Text

我尝试了 Data.Text.Encoding 中的 encodeUtf8,但没有成功:

Couldn't match expected type Data.ByteString.Lazy.Internal.ByteString against inferred type Data.ByteString.Internal.ByteString

更新:

感谢您的回复,*Chunks 的优点看起来不错,但结果让我有些震惊,我原来的函数如下所示:

htmlToItems :: Text -> [Item]
htmlToItems =
    getItems . parseTags . convertFuzzy Discard "CP1251" "UTF8"

现在变成了:

htmlToItems :: Text -> [Item]
htmlToItems =
    getItems . parseTags . fromLazyBS . convertFuzzy Discard "CP1251" "UTF8" . toLazyBS
    where
      toLazyBS t = fromChunks [encodeUtf8 t]
      fromLazyBS t = decodeUtf8 $ intercalate "" $ toChunks t

是的,这个函数不起作用,因为它是错误的,如果我们向它提供Text,那么我们确信该文本已正确编码并可以使用,将其转换为愚蠢的事情这样做,但这样的详细转换仍然必须在 htmltoItems 之外的某个地方进行。

最佳答案

ByteStrings 主要用于二进制数据,但如果您只需要 ASCII 字符集,它们也是处理文本的有效方法。如果需要处理unicode字符串,则需要使用Text。但是,我必须强调,两者都不能替代另一个,并且它们通常用于不同的用途:虽然 Text 表示纯 unicode,但您仍然需要在二进制 ByteString 之间进行编码每当您例如通过套接字或文件传输文本。

这是一篇关于 unicode 基础知识的好文章,它很好地解释了 unicode 代码点 (Text) 和编码的二进制字节 (ByteString) 之间的关系): The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets

您可以使用Data.Text.Encoding在两种数据类型之间进行转换的模块,或 Data.Text.Lazy.Encoding如果您正在使用惰性变体(正如您根据错误消息所做的那样)。

关于string - 文本或字节串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7357775/

相关文章:

json - 仅保留具有字符串值的字段

swift - Swift 中的 DNA 到 RNA 转录

string - 将字符串转换为 Foo(类型字符串)

haskell - 在 Haskell 中设置 argv[0]?

python - 用双引号写出文本 - Linux 上的 Python

python - 在列表项错误之间发出缺少逗号的警告

haskell - 在 Hackage 上寻找反向依赖

haskell - 用于组合 (a->a) 函数而不是 (a->b) 的仿函数/类似应用程序的类型类?

java - Java中的动态文本框

python - 索引错误: list index out of range