【发布时间】:2014-12-04 05:14:24
【问题描述】:
首先,我的背景是 C++,所以尽量不要太用力地打我。
在这个人为的例子中,我试图定义一个看起来像这样的多态类型:
data T x y
= Cons1 x
| Cons2 y
| Neither
deriving (Show)
我想要一个数据类型,它包含x、y 类型或两者都不包含的值。 Maybe a 的一种变体。当我尝试这样做时:
main = do
let v = Cons1 1
putStrLn (show v)
出现了一些歧义:
No instance for (Show y0) arising from a use of `show'
The type variable `y0' is ambiguous
Note: there are several potential instances:
instance (Show x, Show y) => Show (T x y)
-- Defined at C:\Projects\Private\Haskell\Play\play.hs:14:27
instance Show Double -- Defined in `GHC.Float'
instance Show Float -- Defined in `GHC.Float'
...plus 25 others
In the first argument of `putStrLn', namely `(show t)'
In a stmt of a 'do' block: putStrLn (show t)
In the expression:
do { let t = Cons1 1;
putStrLn (show t) }
这是为什么?为什么会有歧义? Cons1 1 中的1 是从我理解的一个数字中得出的,它们都派生出Show。我认为构造函数本身充当了鉴别器,使Cons1 1 /= Cons2 1。
【问题讨论】:
标签: haskell