Reputation: 519
If I've declared a data type thus:
data ExampleType = TypeA (Int, Int) | TypeB (Int, Int, Int)
How can I declare a function that takes either TypeA or TypeB and performs different operations on that basis? My current attempt is:
exampleFunction :: ExampleType -> Int
exampleFunction (TypeA(firstInt, secondInt)) = --Fn body
exampleFunction (TypeB(firstInt, secondInt, thirdInt)) = --Fn body
But I'm getting a Duplicate type signatures
error, so I'm clearly missing something.
Upvotes: 0
Views: 180
Reputation: 2366
Your code should not cause such an error. However there some things wrong with your question. First the use of a tuple is unsusual for a Product type (TypeA (Int, Int)
). Instead you would just declare TypeA
as a data constructor that takes two arguments of type Int
instead of one of type (Int, Int)
. Furthermore TypeA
and TypeB
are not two different types but two different data constructors of the same sum type ExampleType
. To reflect that I renamed them to DataA
and DataB
in the below code.
data ExampleType = DataA Int Int | DataB Int Int Int
exampleFunction :: ExampleType -> Int
exampleFunction (DataA x y) = x + y
exampleFunction (DataB x y z) = x + y + z
Upvotes: 2
Reputation: 54584
Works for me:
data ExampleType = TypeA (Int, Int) | TypeB (Int, Int, Int)
exampleFunction :: ExampleType -> Int
exampleFunction (TypeA (a,b)) = a + b
exampleFunction (TypeB (a,b,c)) = a + c + c
main = print $ exampleFunction (TypeA (2,3))
Note that you typically wouldn't use tuples as components of your type, as this makes it quite hard to get to the data. If you have not a very good reason, simply use
data ExampleType = TypeA Int Int | TypeB Int Int Int
Upvotes: 4