Haskell中元组的模式匹配相等 [英] Pattern matching equality on tuples in Haskell
问题描述
symEq :: Eq a =>对于元组上的对称等式的这个函数, (a,a) - > (a,a) - > Bool
symEq(x,y)(u,v)=(x,y)==(u,v)|| (x,y)==(v,u)
想要使用模式匹配将其重写为如下所示:
symEq':: Eq a => (a,a) - > (a,a) - > Bool
symEq'(x,y)(x,y)= True
symEq'(x,y)(y,x)= True
symEq'_ _ = False
后者在 x
的冲突定义中出错并且ý
。如何重写 symEq
,并利用模式匹配?
在某些语言中(我听说Erlang以这种方式工作),在Haskell中以模式重复一个变量名 not 比较在这两个地方找到的值,通常是一个错误。所以你需要使用 ==
。
无论如何,这里是一个 更简洁的写作方式:
symEq t(x,y)= t ==(x, y)|| t ==(y,x)
甚至
symEq t(x,y)= t`elem` [(x,y),(y,x)]
For this function on symmetric equality over tuples,
symEq :: Eq a => (a,a) -> (a,a) -> Bool
symEq (x,y) (u,v) = (x,y) == (u,v) || (x,y) == (v,u)
would like to rewrite it using pattern matching as follows,
symEq' :: Eq a => (a,a) -> (a,a) -> Bool
symEq' (x,y) (x,y) = True
symEq' (x,y) (y,x) = True
symEq' _ _ = False
The latter fails with error on conflicting definitions for x
and y
. How to rewrite symEq
and take benefit of pattern matching ?
Unlike in some languages (I hear Erlang works that way), repeating a variable name in patterns in Haskell does not compare the values found at those two places, and is usually an error. So you are going to need to use ==
for that.
Anyway, here is a slightly more concise way of writing your function:
symEq t (x,y) = t == (x,y) || t == (y,x)
Or even
symEq t (x,y) = t `elem` [(x,y), (y,x)]
这篇关于Haskell中元组的模式匹配相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!