你可以在Haskell中重载+吗? [英] Can you overload + in haskell?

查看:124
本文介绍了你可以在Haskell中重载+吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我在Haskell示例代码中看到了各种奇怪的东西 - 我从来没有见过一个运算符加上被重载。有什么特别的吗?



假设我有一个类似于 Pair 的类型,并且我想要类似于



pre $ Pair(2,4)+ Pair(1,2)= Pair(3,6)

p>

一个人可以在haskell中完成吗?



我只是好奇,因为我知道这是可能的在Scala中以相当优雅的方式。

code>(+)是 Num typeclass的一部分,每个人似乎都觉得你不能定义(*)等您的类型,但我强烈反对。

  newtype Pair ab = Pair (a,b)派生(Eq,Show)

我认为 Pair ab 会更好,或者我们甚至可以直接使用类型(a,b),但是...



这非常类似于两个Monoid,组,环或者数学中的任何东西的笛卡尔乘积,并且有一个定义数字结构的标准方法

  instance(Num a,Num b)=> (a,b)+ Pair(c,d)= Pair(a + c,b + d)
Pair(a,b)* Pair(c,d) )= Pair(a * c,b * d)
Pair(a,b) - Pair(c,d)= Pair(ac,bd)$ b $ abs(Pair(a,b))=对(abs a,abs b)
signum(Pair(a,b))= Pair(signum a,signum b)
fromInteger i = Pair(fromInteger i,fromInteger i)

现在我们以一种明显的方式重载了(+)而且也消耗了整个猪,并且重载了(*)和其他所有 Num 函数,方式数学做一对。我只是没有看到这个问题。事实上,我认为这是一个很好的做法。

  * Main> Pair(3,4.0)+ Pair(7,10.5)
Pair(10,14.5)
* Main> Pair(3,4.0)+ 1 - *
Pair(4,5.0)

* - 注意来自整数的应用于数字文字,如 1 ,所以在上下文中解释为 Pair(1,1.0):: Pair Integer Double 。这也相当不错,方便。


While I've seen all kinds of weird things in Haskell sample code - I've never seen an operator plus being overloaded. Is there something special about it?

Let's say I have a type like Pair, and I want to have something like

 Pair(2,4) + Pair(1,2) = Pair(3,6)

Can one do it in haskell?

I am just curious, as I know it's possible in Scala in a rather elegant way.

解决方案

Yes

(+) is part of the Num typeclass, and everyone seems to feel you can't define (*) etc for your type, but I strongly disagree.

newtype Pair a b = Pair (a,b)  deriving (Eq,Show) 

I think Pair a b would be nicer, or we could even just use the type (a,b) directly, but...

This is very much like the cartesian product of two Monoids, groups, rings or whatever in maths, and there's a standard way of defining a numeric structure on it, which would be sensible to use.

instance (Num a,Num b) => Num (Pair a b) where
   Pair (a,b) + Pair (c,d) = Pair (a+c,b+d)
   Pair (a,b) * Pair (c,d) = Pair (a*c,b*d)
   Pair (a,b) - Pair (c,d) = Pair (a-c,b-d)
   abs    (Pair (a,b)) = Pair (abs a,    abs b) 
   signum (Pair (a,b)) = Pair (signum a, signum b) 
   fromInteger i = Pair (fromInteger i, fromInteger i)

Now we've overloaded (+) in an obvious way, but also gone the whole hog and overloaded (*) and all the other Num functions in the same, obvious, familiar way mathematics does it for a pair. I just don't see the problem with this. In fact I think it's good practice.

*Main> Pair (3,4.0) + Pair (7, 10.5)
Pair (10,14.5)
*Main> Pair (3,4.0) + 1    -- *
Pair (4,5.0)

* - Notice that fromInteger is applied to numeric literals like 1, so this was interpreted in that context as Pair (1,1.0) :: Pair Integer Double. This is also quite nice and handy.

这篇关于你可以在Haskell中重载+吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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