为什么以下尝试在列表理解中模式匹配不起作用?表达式/列表解析中的模式匹配
示例:同时替换术语数据类型中的原子。
的数据类型:
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