我是一個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