gpt4 book ai didi

Haskell 字节串 : How to pattern match?

转载 作者:行者123 更新时间:2023-12-01 21:13:18 25 4
gpt4 key购买 nike

我是 Haskell 新手,在弄清楚如何模式匹配 ByteString 时遇到了一些麻烦。我的函数的 [Char] 版本如下所示:

dropAB :: String -> String
dropAB [] = []
dropAB (x:[]) = x:[]
dropAB (x:y:xs) = if x=='a' && y=='b'
then dropAB xs
else x:(dropAB $ y:xs)

正如预期的那样,这会过滤掉字符串中所有出现的“ab”。但是,我在尝试将此应用于 ByteString 时遇到问题。

天真的版本

dropR :: BS.ByteString -> BS.ByteString
dropR [] = []
dropR (x:[]) = [x]
<...>

产量

Couldn't match expected type `BS.ByteString'
against inferred type `[a]'
In the pattern: []
In the definition of `dropR': dropR [] = []

[] 显然是罪魁祸首,因为它是常规 String 而不是 ByteString。在 BS.empty 中进行替换似乎是正确的事情,但给出了“绑定(bind)位置的限定名称:BS.empty”。让我们去尝试

dropR :: BS.ByteString -> BS.ByteString
dropR empty = empty
dropR (x cons empty) = x cons empty
<...>

这给出了(x cons empty)的“模式中的解析错误”。我真的不知道我还能在这里做什么。

顺便说一句,我试图用这个函数做的是从某些文本中过滤掉特定的 UTF16 字符。如果有一种干净的方法来实现这一点,我很想听听,但这种模式匹配错误似乎是新手 Haskeller 应该真正理解的东西。

最佳答案

您可以使用view patterns对于这样的事情

{-# LANGUAGE ViewPatterns #-}    
import Data.ByteString (ByteString, cons, uncons, singleton, empty)
import Data.ByteString.Internal (c2w)

dropR :: ByteString -> ByteString
dropR (uncons -> Nothing) = empty
dropR (uncons -> Just (x,uncons -> Nothing)) = singleton x
dropR (uncons -> Just (x,uncons -> Just(y,xs))) =
if x == c2w 'a' && y == c2w 'b'
then dropR xs
else cons x (dropR $ cons y xs)

关于Haskell 字节串 : How to pattern match?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4056449/

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