我是一个Haskell新手,并且在找出如何匹配ByteString
的模式时遇到了一些麻烦。该[Char]
版本我的功能看起来像:Haskell Bytestrings:如何模式匹配?
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
中的Subbing似乎是正确的,但会给出“绑定位置中的限定名:BS.empty”。留下我们试试
dropR :: BS.ByteString -> BS.ByteString
dropR empty = empty
dropR (x cons empty) = x cons empty
<...>
这给出了(x cons empty)
的“模式解析错误”。我真的不知道我还能在这里做什么。
作为一个方面说明,我正在尝试使用此功能是从某些文本中筛选出特定的UTF16字符。如果有一个干净的方法来实现这一点,我很乐意听到它,但这种模式匹配错误看起来像是一个新手哈克勒应该真正理解的东西。
我不知道,但也许守卫,而不是模式匹配? – 2010-10-29 23:24:16
您无法过滤出UTF-16字符。也许你的意思是“过滤出以UTF-16编码的文本的字符”。 – gawi 2010-10-30 00:55:23