创建一个Num类的实例 [英] Creating an instance of Num class

查看:103
本文介绍了创建一个Num类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下抽象数据类型:

$ pre > data标量=
标量整数
导出(Eq,Show)

我希望能够对Scaler类型执行以下操作:

 > (标量10)+ 1 
>标量11

为此,我尝试使 Scalar num 类的一个实例,如下所示:

  instance Num标量,其中
(标量i1)+ i2 =(标量(i1 + i2))

但这不起作用。我究竟做错了什么?什么是正确的方法?

编辑:
我得到的错误是:


 无法与实际类型为'Scalar'的预期类型'Integer'匹配
在` (+)',即`i2'
在'Scalar'的第一个参数中,即`(i1 + i2)'



解决方案

不,你不能这样做,因为 + 是:

 λ> :t(+)
(+):: Num a => a - > a - > a

因此,它对相同数据的类型进行操作。在你的情况下,你试图添加一个 Scalar 和 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

由于@ user5402评论过,可以定义来自 Num typeclass的Integer 函数的,然后在你的添加中使用它。例如:

pre $ 实例Num标量其中
(Scalar x)+(Scalar y)= Scalar(x + y)
fromInteger x =标量x

现在,您可以使用整数文字,在必要时自动转换为标量值,例如:

 λ> 3 +标量7 
标量10


I am relatively new to learning haskell.

I have the following abstract data type

data Scalar = 
    Scalar Integer
  deriving (Eq, Show)

I want to be able to do the following operation on the Scaler type:

> (Scalar 10) + 1
> Scalar 11

To do this I tried making the Scalar an instance of the num class like this:

instance Num Scalar where
  (Scalar i1) + i2 = (Scalar (i1+i2))

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:

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)'

解决方案

No, you cannot do that, because the type of + is:

λ> :t (+)
(+) :: Num a => a -> a -> a

So, it operates on the type of same data. In your case you are trying to add a type of 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)

And it will operate on Scalar type:

λ> Scalar 3 + Scalar 4
Scalar 7

But if you really want to do this, you can create your own special function for that:

addNumtoScalar :: Integer -> Scalar -> Scalar
addNumtoScalar x (Scalar y)  = Scalar (x + y)

And then you can add using this function,

λ> addNumtoScalar 3 (Scalar 7)
Scalar 10

Or in an infix fashion:

λ> 3 `addNumtoScalar` (Scalar 7)
Scalar 10

As @user5402 has commented, you can define the 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

Now, you can use integer literals and they will be automatically converted to Scalar values when necessary, e.g.:

λ> 3 + Scalar 7
Scalar 10

这篇关于创建一个Num类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆