user132603
user132603

Reputation: 73

How to simplified this function in Haskell?

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

Upvotes: 1

Views: 90

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 153210

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)

Upvotes: 11

Related Questions