1

I think writing code in this way is redundant. Regardless of what the type constructors are, the return values are all the same. Is there a way to write the return values once for all?

data End = Leftend (Int,Int) | Rightend (Int, Int)
            deriving (Eq, Ord, Show)


cmp:: End->End->Ordering
cmp (Leftend (l, h1))  (Rightend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT
cmp (Leftend (l, h1))  (Leftend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT
cmp (Rightend (l, h1))  (Rightend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT
cmp (Rightend (l, h1))  (Leftend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT
user132603
  • 73
  • 4
  • This isn't exactly a duplicate, but treads a lot of the same ground as https://stackoverflow.com/questions/32158110/can-i-match-a-data-constructor-wildcard-in-haskell?rq=1. – amalloy May 09 '20 at 06:15
  • 4
    I propose refactoring your data declaration to something like `data Side = Left | Right; data End = End { side :: Side, width :: Int, height :: Int }` or similar. Then `cmp = comparing width`, and is probably not even worth giving a name to. – Daniel Wagner May 09 '20 at 06:18
  • 3
    For starters, this pattern `| l < r = LT | l == r = EQ | l > r = GT` that keeps appearing is just `compare l r` – luqui May 09 '20 at 06:55

1 Answers1

11

I guess...

import Data.Ord

discard :: End -> (Int, Int)
discard (Leftend v) = v
discard (Rightend v) = v

cmp :: End -> End -> Ordering
cmp = comparing (fst . discard)
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380