我是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
似乎是正确的选择,但会出现 "Qualified name in the binding position: BS.empty." 的错误提示。所以我们尝试使用dropR :: BS.ByteString -> BS.ByteString
dropR empty = empty
dropR (x cons empty) = x cons empty
<...>
这会导致
(x cons empty)
出现“模式解析错误”。我不知道还能做什么。另外,我想用这个函数过滤文本中的特定UTF16字符。如果有一种简单的方法来实现这个目标,我很乐意听取建议,但这个模式匹配错误似乎是一个新手应该真正理解的问题。
ByteString
。在这种情况下,decodeUtf16LE
和Text.filter
(/= '消')
是更干净的高层工具,可以实现 LOS 所尝试做的事情。不管是什么情况让你看到了这个问题,都可能有类似的解决方案! - Lynn