使用 Haskell 中的数据类型重载函数

Overloading a function with a data type in Haskell

如果我这样声明数据类型:

data ExampleType = TypeA (Int, Int) | TypeB (Int, Int, Int)

我如何声明一个接受 TypeA 或 TypeB 并在此基础上执行不同操作的函数?我目前的尝试是:

exampleFunction :: ExampleType -> Int
exampleFunction (TypeA(firstInt, secondInt)) = --Fn body
exampleFunction (TypeB(firstInt, secondInt, thirdInt)) = --Fn body

但是我遇到了 Duplicate type signatures 错误,所以我显然遗漏了一些东西。

适合我:

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

请注意,您通常不会使用元组作为类型的组成部分,因为这使得获取数据变得非常困难。如果你没有很好的理由,只需使用 data ExampleType = TypeA Int Int | TypeB Int Int Int

您的代码不应导致此类错误。但是,您的问题有些问题。首先,元组的使用对于产品类型 (TypeA (Int, Int)) 是不寻常的。相反,您只需将 TypeA 声明为一个数据构造函数,它接受两个 Int 类型的参数而不是一个 (Int, Int) 类型的参数。此外 TypeATypeB 不是两个不同的类型,而是相同和类型 ExampleType 的两个不同的数据构造函数。为了反映我在下面的代码中将它们重命名为 DataADataB

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