Haskell类的错误我一直都在下降,无法理解

Raf*_*ini 0 haskell type-systems class

我遇到了一个错误,但无法理解如何使它正确.给我这个错误的代码示例是:

class Someclass a where
    somefunc :: (Num b) => b -> a -> a

data Sometype = Somecons Int

instance Someclass Sometype where
    somefunc x (Somecons y) = Somecons (x+y)
Run Code Online (Sandbox Code Playgroud)

错误消息是:

无法将预期类型'b'与推断类型'Int'匹配''
'b'是一个严格的类型变量,由error.hs中的'somefunc'的类型签名绑定:3:21
在'(+)'的第二个参数中,即'y'
在'Somecons'的第一个参数中,即'(x + y)'
在表达式中:Somecons(x + y)

据我所知,错误消息试图告诉我,我使用的是Int类型的名称,他期望类型为(Num b)=> b.我无法理解的是Int适合(Num b)=> b.难道编译器不应该理解我告诉他的内容(对于这个特定的实例,b应该是一个整数吗?我怎样才能使它合适?

Coment:当然在这个具体的例子中,我可以使用类型签名制作somefunc:

somefunc :: a -> a-> a 
Run Code Online (Sandbox Code Playgroud)

但是我希望我想要这样的东西:

data Newtype = Newcons (Int, Int) 

instance Someclass Newtype where
    somefunc x (Newtype (y,z) ) = Newtype (y+x, z)
Run Code Online (Sandbox Code Playgroud)

当我试图在哈斯克尔做某事时,反复发生这样的事情.

Dar*_*rio 8

那么,在使用通用量化来考虑泛型符号时,您可以更清楚地说明这一点.

somefunc :: (Num b) => b -> a -> a
Run Code Online (Sandbox Code Playgroud)

因此,意味着什么

somefunc :: forall a b . Num b => b -> a -> a
Run Code Online (Sandbox Code Playgroud)

这意味着必须为任何数字定义类函数b.

代码

Data Sometype = Somecons Int

instance Someclass Sometype where
    somefunc x (Somecons y) = Somecons (x+y)
Run Code Online (Sandbox Code Playgroud)

强制b使用一种具体类型 - Int这不符合任何数字类型的工作要求.

你可能想要这样的东西

class Num b => SomeClass a b where
    somefunc :: b -> a -> a

instance Someclass Somecons Int where
    -- ...
Run Code Online (Sandbox Code Playgroud)


R. *_*des 5

问题可以在+运营商的签名中看到:

(+) :: Num a => a -> a -> a
Run Code Online (Sandbox Code Playgroud)

正因为如此,当您使用+somefunc同一种Int,它令b为一个Int,因此,somefunc变成:

somefunc :: Int -> Sometype -> Sometype
Run Code Online (Sandbox Code Playgroud)

要实现Someclass该类,somefunc预计会有这个签名:

somefunc :: Num b => b -> Sometype -> Sometype
Run Code Online (Sandbox Code Playgroud)

也就是说,它应该适用于任何类型的实例Num.您的功能适用于Ints.