haskell中的任何工作运算符重载示例

时间:2013-04-26 16:56:57

标签: haskell operator-overloading overloading

我想重载任何运算符。我想做一个这样一个简单的函数,例如考虑重载==运算符.Overload ==这样 X ==ÿ
返回x。 或者x == y返回x + y。什么都没关系。你能告诉我任何简单的运算符重载示例吗?遗憾的是,我在网上找不到任何例子。

例如;当我调用树a ==树a 返回5(它总是返回5.我选择它,它与任何东西无关) 或当我打电话给3 == 4 回报:7

我尝试了以下代码(我从haskell.org找到它)但它无法编译。

class Eq a where
(==) ::a -> a -> Int

instance Eq Integer where
x == y = 5

instance Eq Float where
x == y = 5

以下代码均无效:

数据树a =节点a |空

class Tree a where     (==)::树a - >树a - > INT

实例树整数在哪里 x == y = 1

我接受了错误:

Ambiguous occurrence `Eq'
It could refer to either `Main.Eq', defined at Operations.hs:4:7
                      or `Prelude.Eq',
                         imported from `Prelude' at Operations.hs:1:1
                         (and originally defined in `GHC.Classes')

3 个答案:

答案 0 :(得分:2)

首先尝试隐藏Prelude中的==。如果您希望它对不同类型的工作方式不同,则只需要一个类型类。

import Prelude hiding ((==))

x == y = x

答案 1 :(得分:2)

您无法从导入的模块中隐藏实例。例如,请参阅:Explicitly import instances

您尝试执行的“重载”似乎是允许(==)用于其他类型,例如树。这很简单!只需创建一个新实例:

data Tree a = Leaf a | Branch [Tree a]

 instance (Eq a) => Eq (Tree a) where
    (Leaf a)   == (Leaf b)   = a == b
    (Branch a) == (Branch b) = a == b
    _          == _          = False

(您也可以只derive Eq个实例)

答案 2 :(得分:0)

这是一个+++运算符,其作用类似于用于追加列表的(++)运算符:

(+++) :: [a]->[a]->[a]
x +++ [] = x
[] +++ x = x
x  +++ y = (init x) +++ ((last x) : y)