简体   繁体   中英

Overloading a function with a data type in Haskell

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.

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))

http://ideone.com/jsIBVF

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 data ExampleType = TypeA Int Int | TypeB Int Int Int

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM