any working operator overloading example in haskell

戏子无情 提交于 2020-01-17 05:28:21

问题


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

回答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)




回答2:


Try hiding the == from the Prelude first. You only need a type class if you want it to work differently for different types.

import Prelude hiding ((==))

x == y = x



回答3:


Here's a +++ operator that acts like the (++) operator used to append lists:

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


来源:https://stackoverflow.com/questions/16241556/any-working-operator-overloading-example-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!