Pattern matching equality on tuples in Haskell

后端 未结 2 972
予麋鹿
予麋鹿 2021-01-24 18:58

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)


        
相关标签:
2条回答
  • 2021-01-24 19:39

    With the ViewPatterns you can achieve something that resembles the Erlang and Prolog pattern matching style:

    {-# LANGUAGE ViewPatterns #-}
    
    swap (a,b) = (b,a)
    
    symEq :: Eq a => (a,a) -> (a,a) -> Bool
    symEq a ((==a) -> True) = True
    symEq a ((==a).swap -> True) = True
    symEq _ _ = False
    

    Note how the a in (==a) refers to the first function argument - bound names of earlier function parameters may be used in the view patterns of later parameters.

    More details on ViewPatterns may be found here.

    0 讨论(0)
  • 2021-01-24 19:55

    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)]
    
    0 讨论(0)
提交回复
热议问题