Pattern matching identical values

匆匆过客 提交于 2019-11-27 14:37:18

This is called a nonlinear pattern. There have been several threads on the haskell-cafe mailing list about this, not long ago. Here are two:

http://www.mail-archive.com/haskell-cafe@haskell.org/msg59617.html

http://www.mail-archive.com/haskell-cafe@haskell.org/msg62491.html

Bottom line: it's not impossible to implement, but was decided against for sake of simplicity.

By the way, you do not need if or case to work around this; the (slightly) cleaner way is to use a guard:

a `plus` b
  | a == b = 2*a
  | otherwise = a+b

You can't have two parameters with the same name to indicate that they should be equal, but you can use guards to distinguish cases like this:

plus a b
  | a == b    = 2 * a
  | otherwise = a + b

This is more flexible since it also works for more complicated conditions than simple equality.

I have just looked up the mailing list threads given in Thomas's answer, and the very first reply in one of them makes good sense, and explains why such a "pattern" would not make much sense in general: what if a is a function? (It is impossible in general to check it two functions are equal.)

Haskell doesn't do unification.

I have implemented a new functional programming language that can handle non-linear patterns in Haskell.

https://github.com/egison/egison

In my language, your plus function in written as follow.

(define $plus
  (match-lambda [integer integer]
    {[[$a ,a] (* a 2)]
     [[$a $b] (+ a b)]}))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!