gpt4 book ai didi

haskell - 从 `Char` 获取 `ByteString`

转载 作者:行者123 更新时间:2023-12-02 18:43:44 25 4
gpt4 key购买 nike

有没有办法在 O(1) 时间内获取 ByteString 中的第一个 UTF-8 Char ?我正在寻找类似的东西

headUtf8 :: ByteString -> Char
tailUtf8 :: ByteString -> ByteString

我还没有被限制使用严格或惰性ByteString,但我更喜欢严格。对于懒惰的 ByteString,我可以通过 Text 拼凑一些东西,但我不确定这有多高效(尤其是空间复杂度方面)。

import qualified Data.Text.Lazy as T
import Data.Text.Lazy.Encoding (decodeUtf8With, encodeUtf8)
import Data.Text.Encoding.Error (lenientDecode)

headUtf8 :: ByteString -> Char
headUtf8 = T.head . decodeUtf8With lenientDecode

tailUtf8 :: ByteString -> ByteString
tailUtf8 = encodeUtf8 . T.tail . decodeUtf8With lenientDecode

如果有人感兴趣的话,当使用 Alex 制作支持 UTF-8 字符的词法分析器时会出现这个问题1

<小时/>

1 我知道从 Alex 3.0 开始,您只需要提供 alexGetByte (这太棒了!),但我仍然需要能够获取其他字符词法分析器中的代码。

最佳答案

您想要Data.Bytestring.UTF8 utf8-string 包中的模块。它包含一个具有以下签名的 uncons 函数:

uncons :: ByteString -> Maybe (Char, ByteString)

然后您可以定义:

headUtf8 :: ByteString -> Char
headUtf8 = fst . fromJust . uncons

tailUtf8 :: ByteString -> ByteString
tailUtf8 = snd . fromJust . uncons

关于haskell - 从 `Char` 获取 `ByteString`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414452/

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