在类型类实例中提供函数类型签名会产生错误
Giving function type signature inside typeclass instance gives an error
一旦我成功解决了 Functor 类型类的练习:
data ExactlyOne a = ExactlyOne a deriving (Eq, Show)
instance Functor ExactlyOne where
(<$>) ::
(a -> b)
-> ExactlyOne a
-> ExactlyOne b
(<$>) f a = ExactlyOne $ f (runExactlyOne a)
解决另一个练习我需要为自定义 Odd 类型定义 Enum 类型类函数。
data Odd = Odd Integer
deriving (Eq, Show)
instance Enum Odd where
-- succ :: Odd -> Odd <-- error
succ (Odd x) = Odd $ x + 2
现在当我尝试为一个更简单的函数指定类型签名时,ghci 给出了一个错误:
Illegal type signature in instance declaration:
succ :: Odd -> Odd (Use InstanceSigs to allow this)
没有它也能工作,但我想知道为什么会产生这个错误以及如何为这个函数正确指定类型签名?
实例中的签名对于类型 类 中的类型签名是冗余的。如果稍后稍微更改类型类的签名,例如通过添加额外的类型约束,可能会导致错误,因为签名不再一致。
这是在section on Instance Declarations in the Haskell '10 report中指定的:
The declarations may not contain any type signatures or fixity declarations, since these have already been given in the class declaration. As in the case of default class methods (Section 4.3.1), the method declarations must take the form of a variable or function definition.
Enum
typeclass [src] 已经包含签名:
class Enum a where
-- | the successor of a value. For numeric types, 'succ' adds 1.
succ :: <b>a -> a</b>
-- ...
如果你想指定签名,你可以打开InstanceSigs
language extension [ghc-doc],比如:
{-# LANGUAGE <b>InstanceSigs</b> #-}
data Odd = Odd Integer deriving (Eq, Show)
instance Enum Odd where
<b>succ :: Odd -> Odd</b>
succ (Odd x) = Odd $ x + 2
一旦我成功解决了 Functor 类型类的练习:
data ExactlyOne a = ExactlyOne a deriving (Eq, Show)
instance Functor ExactlyOne where
(<$>) ::
(a -> b)
-> ExactlyOne a
-> ExactlyOne b
(<$>) f a = ExactlyOne $ f (runExactlyOne a)
解决另一个练习我需要为自定义 Odd 类型定义 Enum 类型类函数。
data Odd = Odd Integer
deriving (Eq, Show)
instance Enum Odd where
-- succ :: Odd -> Odd <-- error
succ (Odd x) = Odd $ x + 2
现在当我尝试为一个更简单的函数指定类型签名时,ghci 给出了一个错误:
Illegal type signature in instance declaration: succ :: Odd -> Odd (Use InstanceSigs to allow this)
没有它也能工作,但我想知道为什么会产生这个错误以及如何为这个函数正确指定类型签名?
实例中的签名对于类型 类 中的类型签名是冗余的。如果稍后稍微更改类型类的签名,例如通过添加额外的类型约束,可能会导致错误,因为签名不再一致。
这是在section on Instance Declarations in the Haskell '10 report中指定的:
The declarations may not contain any type signatures or fixity declarations, since these have already been given in the class declaration. As in the case of default class methods (Section 4.3.1), the method declarations must take the form of a variable or function definition.
Enum
typeclass [src] 已经包含签名:
class Enum a where -- | the successor of a value. For numeric types, 'succ' adds 1. succ :: <b>a -> a</b> -- ...
如果你想指定签名,你可以打开InstanceSigs
language extension [ghc-doc],比如:
{-# LANGUAGE <b>InstanceSigs</b> #-}
data Odd = Odd Integer deriving (Eq, Show)
instance Enum Odd where
<b>succ :: Odd -> Odd</b>
succ (Odd x) = Odd $ x + 2