案例表达式/列表理解中的模式匹配

时间:2015-03-13 10:16:40

标签: haskell pattern-matching list-comprehension

为什么以下尝试在列表推导中进行模式匹配不起作用?

示例:术语数据类型中原子的同时替换。

数据类型:

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 
    atom@(Atom x)       ->  let substitutions = 
                                [ s | s@(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 
    atom@(Atom _)       ->  let substitutions = 
                            [ s | s@(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 
     atom@(Atom _)       ->  let substitutions = 
                             [ s | s@(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'

我错过了什么?

1 个答案:

答案 0 :(得分:8)

Haskell具有线性模式,这意味着模式中不得有重复的变量。此外,内部表达式中的模式变量会影响外部变量,而不是建立相同变量的相等性。

你正试图做这样的事情:

charEq :: Char -> Char -> Bool
charEq c c = True
charEq _ _ = False

但由于重复变量,这是一个错误。如果我们将第二个c移动到内部表达式,它会编译,但它仍然不能按预期工作:

charEq :: Char -> Char -> Bool
charEq c d = case d of
  c -> True
  _ -> False

此处内部c只是一个隐藏外部c的新变量,因此charEq始终返回True

如果我们要检查是否相等,我们必须明确使用==

subs :: [(Term a, Term a)] -> Term a -> Term a
subs subList term = case term of 
    atom@(Atom x)       ->  let substitutions = 
                                [ s | s@(Atom x', _) <- subList, x == x' ]
                            in  if null substitutions
                                then atom
                                else snd . head $ substitutions
    (Compound t1 t2)    -> Compound (subs subList t1) (subs subList t2)