0
votes

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')
3
try only the instance parts. The typeclass definition is already made in Prelude. Alternatively, hide the import of the prelude definition.m09
then how to overload == for Trees and return always 5 ?oiyio
The Eq class defined in the Prelude requires that the result of == is a Bool, so to return 5 you'd have to hide that and define your own.hammar
If you make == mean something other than equality, your code will be hard to understand. Consider using === instead.AndrewC

3 Answers

2
votes

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
votes

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
0
votes

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)