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
3
  • This isn't exactly a duplicate, but treads a lot of the same ground as stackoverflow.com/questions/32158110/…. Commented May 9, 2020 at 6: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. Commented May 9, 2020 at 6:18
  • 3
    For starters, this pattern | l < r = LT | l == r = EQ | l > r = GT that keeps appearing is just compare l r Commented May 9, 2020 at 6:55

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.