任何工作操作符重载哈斯克尔例子(any working operator overloading e

2019-10-28 19:57发布

我想重载任何操作。 我想要做这样一个简单的函数,比如想想==操作符.Overload超载==使得x ==ÿ
返回x。 或x ==Ÿ返回X + Y。 它什么并不重要。 你能告诉我任何简单的运算符重载的例子吗? 我不能在网上找到不幸在任何例子。

例如,当我调用树一个==树返回图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 | 空

类树,其中一个(==)::树一 - >树一 - >内部

实例树整数,其中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')

Answer 1:

You can't hide instances from an imported module. See for example: Explicitly import instances

It looks like the "overloading" you're trying to do is to allow (==) for other types, like trees. This is easy! Just simply create a new instance:

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

(You could also just derive the Eq instance)



Answer 2:

尝试隐藏==首先从前奏。 如果你想为不同类型的不同的工作,你只需要一个类型的类。

import Prelude hiding ((==))

x == y = x


Answer 3:

下面是就像用于追加列表中(++)运算符+++操作:

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


文章来源: any working operator overloading example in haskell