【发布时间】:2011-04-19 11:29:14
【问题描述】:
这是我目前的尝试:
module Main where
data FooT = One | Two deriving (Show, Read)
{-
That is what I want
foo :: (Show a, Read a) => a
foo = One
-}
--class Footable (Show a, Read a) => a where
class Footable a where
--foo2 :: (Show a, Read a) => a
foo2 :: a
instance Footable FooT where
foo2 = One
-- test = print foo2
我想编译测试。我认为问题不在于普遍量化。 ghc 说 a 是一个“严格类型变量”edit(rigid 类型变量),但我并不真正理解这是什么。这个问题好像和this有关
编辑
正如我在@sepp2k 的评论中所写,这可能与存在类型有关,但我偶然发现了一种奇怪的行为:
这确实编译:
{-# LANGUAGE OverlappingInstances, FlexibleInstances, OverlappingInstances,
UndecidableInstances, MonomorphismRestriction, PolymorphicComponents #-}
{-# OPTIONS_GHC -fno-monomorphism-restriction #-}
module Main where
class (Num a) => Numable a where
foo2 :: a
instance (Num a) => Numable a where
foo2 = 1
instance Numable Int where
foo2 = 2
instance Numable Integer where
foo2 = 3
--test = foo2 + foo2 -- This does NOT compile (ambiguous a)
test = (foo2::Integer) + foo2 --this works
但这不是(`a' 是刚性类型变量消息)
{-# LANGUAGE OverlappingInstances, FlexibleInstances, OverlappingInstances,
UndecidableInstances, MonomorphismRestriction, PolymorphicComponents #-}
{-# OPTIONS_GHC -fno-monomorphism-restriction #-}
module Main where
data FooT = One | Two deriving (Show, Read)
data BarT = Ten deriving (Show, Read)
class (Show a, Read a) => Footable a where
foo2 :: a
instance (Show a, Read a) => Footable a where
foo2 = Ten
instance Footable FooT where
foo2 = One
main = print foo2
之所以如此,是因为 1 :: (Num t) => t。我可以这样定义一些东西(类型构造函数,consts 不知道)吗?
【问题讨论】:
-
反引号不能格式化多行代码。您必须缩进四个空格(或使用代码按钮或 Ctrl-K)。
-
和撇号与配色方案混淆。不过现在好了。
-
您应该真正开始发布整个错误消息。消息的重要部分是“无法匹配预期的类型
a' against inferred typeBarT”,而不是“a 是刚性类型变量......”(它没有描述错误 - 它只告诉你 a 来自哪里)。