爲什麼以下嘗試在列表理解中模式匹配不起作用?表達式/列表解析中的模式匹配
示例:同時替換術語數據類型中的原子。
的數據類型:
data Term a
= Atom a
| Compound (Term a) (Term a)
deriving Show
在術語原子的取代算法(採第一匹配取代如果任何和忽略其餘部分):
subs :: [(Term a, Term a)] -> Term a -> Term a
subs subList term = case term of
[email protected](Atom x) -> let substitutions =
[ s | [email protected](Atom x, _) <- subList ]
in if null substitutions
then atom
else snd . head $ substitutions
(Compound t1 t2) -> Compound (subs subList t1) (subs subList t2)
一些測試數據:
subList = [((Atom 'a'), Compound (Atom 'b') (Atom 'c'))]
term1 = Atom 'a'
term2 = Atom 'x'
運行示例結果如下:
>: subs subList term1
Compound (Atom 'b') (Atom 'c')
這是所期望的行爲,和
>: subs subList term2
Compound (Atom 'b') (Atom 'c')
這是不。
Strangley明確的匹配工作的:
subs'' :: [(Term Char, Term Char)] -> Term Char -> Term Char
subs'' subList term = case term of
[email protected](Atom _) -> let substitutions =
[ s | [email protected](Atom 'a', _) <- subList ]
in if null substitutions
then atom
else snd . head $ substitutions
(Compound t1 t2) -> Compound (subs subList t1) (subs subList t2)
subs''' subList term = case term of
[email protected](Atom _) -> let substitutions =
[ s | [email protected](Atom 'x', _) <- subList ]
in if null substitutions
then atom
else snd . head $ substitutions
(Compound t1 t2) -> Compound (subs subList t1) (subs subList t2)
進料與所述測試數據導致:
>: subs'' subList term1
或>: subs'' subList term2
Compound (Atom 'b') (Atom 'c')
>: subs''' subList term1
或>: subs''' subList term2
Atom 'x'
我錯過了什麼?
爲了避免掉入這個錯誤在將來,我建議打開GHC的警告與'-Wall':這將指出'x'被綁定兩次(內部'x'對外部陰影有影響)。 – chi 2015-03-13 10:59:06