隐含Haskell模式匹配中的相等性

Dan*_*ter 10 haskell boolean-logic pattern-matching

我正在编写一个函数来简化布尔表达式.例如,Nand(A, A) == Not(A).我试图使用模式匹配来实现这个特定的规则,如下所示:

-- Operands equivalent - simplify!
simplify (Nand q q) = Not (simplify q)
-- Operands must be different, so recurse.
simplify (Nand q q') = Nand (simplify q) (simplify q')
Run Code Online (Sandbox Code Playgroud)

编译后,我收到错误:

Conflicting definitions for `q'
Bound at: boolean.hs:73:21
          boolean:73:29
In an equation for `simplify'
Run Code Online (Sandbox Code Playgroud)

我想我明白发生了什么,我已经解决了,但我只是想知道:

  1. 为什么这种模式匹配不可能?
  2. 是否有惯用的解决方法?

完全披露:这与家庭作业有关,但课程的目的不是要学习Haskell,而是我已经以自己的方式解决了这个问题.

Dan*_*ter 14

我发现的解决方案是使用防护来检查子结构的相等性:

simplify (Nand q q')
    -- Operands equivalent - simplify!
    | q == q' = Not (simplify q)
    -- Operands different - recurse.
    | otherwise = Nand (simplify q) (simplify q')
Run Code Online (Sandbox Code Playgroud)


npo*_*cop 2

你可以坚持原来的风格:

-- Operands equivalent - simplify!
simplify (Nand q q') | q == q' = Not (simplify q)
-- Operands must be different, so recurse.
simplify (Nand q q') = Nand (simplify q) (simplify q')
Run Code Online (Sandbox Code Playgroud)

另外,我认为你应该在相等测试之前而不是之后进行简化:

simplify (Nand q q') = if qs == qs' then Not qs else Nand qs qs' where
    qs = simplify q
    qs' = simplify q'
Run Code Online (Sandbox Code Playgroud)