gpt4 book ai didi

haskell - 在类型类实例中提供函数类型签名会产生错误

转载 作者:行者123 更新时间:2023-12-01 23:16:01 25 4
gpt4 key购买 nike

一旦我成功解决了 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

关于haskell - 在类型类实例中提供函数类型签名会产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com