Peabrain
Peabrain

Reputation: 589

Haskell Sum Type Pattern Matching: how to specify some cases but not other cases?

I have the following data type:

data TestType a = TypeA a
     | TypeB a
     | TypeC a

How can I simplify the pattern matching of the following function:

f (TypeA x) (TypeB y) = "No"
f (TypeA x) (TypeC y) = "No"
f (TypeB x) (TypeA y) = "No"
f (TypeB y) (TypeC x) = "No"
f (TypeC y) (TypeA x) = "No"
f (TypeC y) (TypeB x) = "No"
f (TypeA x) (TypeA y) = "yes!"

In summary, I should only be returning "yes!" if I am receiving two TypeA data inputs, otherwise, return "No".

Upvotes: 1

Views: 256

Answers (2)

BitTickler
BitTickler

Reputation: 11947

Depending on the concrete signature of f, your implementation could also look like this:

Prelude> data TestType a = TypeA a | TypeB a | TypeC a
Prelude> :{
Prelude| f :: TestType a -> TestType a -> String
Prelude| f (TypeA x) (TypeA y) = "yes"
Prelude| f _ _ = "no"
Prelude| :}
Prelude> f (TypeA 42) (TypeA 21)
"yes"

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477749

Implement the case for two TypeAs and use wildcards for the other cases:

f :: TestType a -> TestType b -> String
f (TypeA _) (TypeA _) = "yes!"
f _ _ = "No"

Upvotes: 6

Related Questions