【发布时间】:2013-04-26 16:56:57
【问题描述】:
我想重载任何 operator 。我想做一个简单的功能,例如考虑重载 == 运算符 .Overload == 这样
x==y
返回 x 。
或者 x==y 返回 x+y。没关系。你能告诉我任何简单的运算符重载示例吗?不幸的是,我在网上找不到任何示例。
例如;当我调用 Tree a == Tree a return 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 |空
类树在哪里 (==) :: 树 a -> 树 a -> Int
实例树整数 where 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')
【问题讨论】:
-
只尝试实例部分。类型类定义已经在 Prelude 中进行了。或者,隐藏前奏定义的导入。
-
那么如何为 Trees 重载 == 并始终返回 5 ?
-
Prelude 中定义的
Eq类要求==的结果是Bool,因此要返回5,您必须隐藏它并定义自己的。 -
如果你让 == 意味着不等于相等,你的代码将难以理解。考虑改用 ===。
标签: haskell operator-overloading overloading