创建一个Num类的实例 [英] Creating an instance of Num class
问题描述
我有以下抽象数据类型:
$ pre > data标量=
标量整数
导出(Eq,Show)
我希望能够对Scaler类型执行以下操作:
> (标量10)+ 1
>标量11
为此,我尝试使 num
类的一个实例,如下所示:
instance Num标量,其中
(标量i1)+ i2 =(标量(i1 + i2))
但这不起作用。我究竟做错了什么?什么是正确的方法?
编辑:
我得到的错误是:
无法与实际类型为'Scalar'的预期类型'Integer'匹配
在` (+)',即`i2'
在'Scalar'的第一个参数中,即`(i1 + i2)'
不,你不能这样做,因为 +
是:
λ> :t(+)
(+):: Num a => a - > a - > a
因此,它对相同数据的类型进行操作。在你的情况下,你试图添加一个 它将在 但如果你真的想这样做,你可以为此创建您自己的特殊功能: 然后你可以使用此功能添加, 或以中缀方式: 由于@ user5402评论过,可以定义来自 现在,您可以使用整数文字,在必要时自动转换为 I am relatively new to learning haskell. I have the following abstract data type I want to be able to do the following operation on the Scaler type: To do this I tried making the But this doesn't work. What am I doing wrong? And whats the correct way to do this? Edit:
The error I am getting is:
No, you cannot do that, because the type of So, it operates on the type of same data. In your case you are trying to add a type of And it will operate on But if you really want to do this, you can create your own special function for that: And then you can add using this function, Or in an infix fashion: As @user5402 has commented, you can define the Now, you can use integer literals and they will be automatically converted to
这篇关于创建一个Num类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Integer
这个无效的类型。你可以像这样定义一个实例:
pre $ $ $ $ $ $ $ $ $ $ $ $标量(i1 + i2)
标量
type:
λ> Scalar 3 + Scalar 4
Scalar 7
addNumtoScalar :: Integer - >标量 - >标量
addNumtoScalar x(标量y)=标量(x + y)
λ> addNumtoScalar 3(标量7)
标量10
λ> 3`addNumtoScalar`(标量7)
标量10
Num
typeclass的Integer 函数的,然后在你的添加中使用它。例如:
pre $ 实例Num标量其中
(Scalar x)+(Scalar y)= Scalar(x + y)
fromInteger x =标量x
标量
值,例如:
λ> 3 +标量7
标量10
data Scalar =
Scalar Integer
deriving (Eq, Show)
> (Scalar 10) + 1
> Scalar 11
Scalar
an instance of the num
class like this:instance Num Scalar where
(Scalar i1) + i2 = (Scalar (i1+i2))
Couldn't match expected type `Integer' with actual type `Scalar '
In the second argument of `(+)', namely `i2'
In the first argument of `Scalar ', namely `(i1 + i2)'
+
is:λ> :t (+)
(+) :: Num a => a -> a -> a
Scalar
and Integer
which isn't valid. You can define an instance like this:instance Num Scalar where
(Scalar i1) + (Scalar i2) = Scalar (i1 + i2)
Scalar
type:λ> Scalar 3 + Scalar 4
Scalar 7
addNumtoScalar :: Integer -> Scalar -> Scalar
addNumtoScalar x (Scalar y) = Scalar (x + y)
λ> addNumtoScalar 3 (Scalar 7)
Scalar 10
λ> 3 `addNumtoScalar` (Scalar 7)
Scalar 10
fromInteger
function of Num
typeclass and then use that in your addition. Something like this:instance Num Scalar where
(Scalar x) + (Scalar y) = Scalar (x + y)
fromInteger x = Scalar x
Scalar
values when necessary, e.g.:λ> 3 + Scalar 7
Scalar 10