我正在编写一个简化 bool 表达式的函数。例如,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')
编译后,出现错误:
Conflicting definitions for `q'
Bound at: boolean.hs:73:21
boolean:73:29
In an equation for `simplify'
我想我了解发生了什么,并且已经解决了这个问题,但是我只想知道:
全面披露:这与家庭作业有关,但是该类(class)的目的不是学习Haskell,而且我还是以自己的方式解决了它。
最佳答案
您可以坚持原来的风格:
-- 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')
另外,我认为您应该在相等性测试之前而不是之后进行简化:
simplify (Nand q q') = if qs == qs' then Not qs else Nand qs qs' where
qs = simplify q
qs' = simplify q'
关于haskell - 在Haskell模式匹配中隐含相等性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12084593/