在Haskell模式匹配中暗含平等 [英] Implying equality in a Haskell pattern match

查看:110
本文介绍了在Haskell模式匹配中暗含平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

- 操作数相当于 - 简化!
简化(Nand q q)= Not(简化q)
- 操作数必须不同,所以递归。
简化(Nand q q')= Nand(简化q)(简化q')

编译时,出现错误:

pre $ $ $

绑定在:boolean.hs: 73:21
布尔值:73:29
在用于简化'

我想我明白发生了什么,我已经解决了这个问题,但我只想知道:


  1. 为什么这种模式匹配是不可能的吗?

  2. 是否有一种惯用的解决方法?

充分披露:这与作业有关,但课程的目的不是要学习Haskell,而是我已经用自己的方式解决了它。



   - 等效的操作数 - 简化! 
简化(Nand q q')| q == q'= Not(简化q)
- 操作数必须不同,因此递归。
简化(Nand q q')= Nand(简化q)(简化q')

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

  simplify(Nand q q')= if qs = = qs'then不是qs其他qq qs qq qq qq qq q $ q $ q $ q 
$ q $ q


$ $ b

I'm writing a function to simplify a Boolean expression. For example, Nand(A, A) == Not(A). I've tried to implement this particular rule using pattern matching, like so:

-- 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')

Upon compiling, I get the error:

Conflicting definitions for `q'
Bound at: boolean.hs:73:21
          boolean:73:29
In an equation for `simplify'

I think I understand what's going on, and I've worked around it, but I'd just like to know:

  1. Why is this sort of pattern matching not possible?
  2. Is there an idiomatic workaround?

Full disclosure: this is related to homework, but the purpose of the course is not to learn Haskell, and I've solved it my own way anyway.

解决方案

You could stick to your original style:

-- 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')

Also, I think you should simplify before equality testing and not after:

simplify (Nand q q') = if qs == qs' then Not qs else Nand qs qs' where
    qs = simplify q
    qs' = simplify q'

这篇关于在Haskell模式匹配中暗含平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆