在haskell中的任何工作运算符重载例子 [英] any working operator overloading example in haskell

查看:231
本文介绍了在haskell中的任何工作运算符重载例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重载任何操作员。我想做一个这样简单的函数,例如考虑重载==运算符.Overload ==,使得
x == y

返回x。
或x == y返回x + y。没关系。你能告诉我任何简单的操作符重载例子吗?不幸的是,我在web上找不到任何示例。



例如,当我调用Tree a == Tree时,
返回5(它总是返回5。选择它,它与任何东西无关)
或当我打电话3 == 4
return:7



我尝试了下面的代码(我发现它来自haskell.org),但它无法编译。

  class方程式a其中
(==) :: a - > a - > Int

实例Eq整数其中
x == y = 5

实例Eq Float其中
x == y = 5


$ b

以下代码都不起作用:

数据树a =节点a |空

类树a其中
(==)::树a - >树a - > Int



实例树整数其中
x == y = 1



我拿错误:

 不明确的出现'Eq'
它可以指在Operations.hs中定义的'Main.Eq':4:7
或'Prelude.Eq' ,从Operations.hs:1:1
(最初在`GHC.Classes'中定义)中的`Prelude'导入的


解决方案

您无法隐藏导入模块中的实例。例如,请参阅:显式导入实例



它看起来像你正在尝试做的重载是允许(==)用于其他类型的树,比如树。这很容易!只需简单地创建一个新实例即可:

 数据Tree a = Leaf a |分支[树a] 

实例(等式a)=> Eq(Tree a)其中
(Leaf a)==(Leaf b)= a == b
(Branch a)==(Branch b)= a == b
_ = = _ = False



<您可能也只是派生 Eq 实例)


I want to overload any operator . i want to do such a simple function that for instance think about overloading of == operator .Overload == such that x==y
returns x . Or x==y return x+y. It doesn't matter what . Can you show me any simple operator overloading example? I cannot find any example on the web unfortunately.

For example;when i call Tree a == Tree a return 5 (it always return 5. I select it ,it is not related to any thing) or when i call 3==4 return : 7

I tried the below codes(i find it from haskell.org) but it cannot compile.

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

instance Eq Integer where
x == y = 5

instance Eq Float where
x == y = 5

Neither the below code works:

data Tree a = Node a | Empty

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

instance Tree Integer where x == y = 1

I take the error :

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

解决方案

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)

这篇关于在haskell中的任何工作运算符重载例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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