1

I created in Haskell a new class Eqa

class Eqa a where

   (=~) :: a -> a -> Bool

   (/~) :: a -> a -> Bool

and want to define (=~) same as (==) from the Prelude. So I tried

instance Eqa Int where            
   x=~y = x==y

   x/~y = x/=y

but this only works for Int (of course). How do I have to change my code that this works with all numerical types?

3
  • How do I have to change my code that this works with all numerical types? What does "this" refer to in your sentence, exactly? Commented Jun 21, 2015 at 10:29
  • With my defined instance I am only able to compare types of Int but I want to compare all numerical Types i.e. float, Integer, ... Commented Jun 21, 2015 at 12:02
  • This isn't something you can really do. The Num typeclass doesn't provide (==). You can convince GHC to accept a definition of instance Num a => Eqa a with the right language pragmas but it's nonsensical and in practice you won't be able to use it. Commented Jun 21, 2015 at 17:53

2 Answers 2

2

Why not just write

(=~) :: Num a => a -> a -> Bool
x=~y = x==y

If you don't actually need the code to be different for different types, why do you need a class at all?

Sign up to request clarification or add additional context in comments.

Comments

-1

All you have to do is to bind a to Num a or

instance Num a => Eqa a where            
    x=~y = x==y
    x/~y = x/=y

For more information, take a look at Numeric Types subsection of Real World Haskell to understand which class is related to each numerical types.

3 Comments

This isn't a great solution. First of all, it doesn't work as written: it requires FlexibleInstances and UndecidableInstances; plus, in modern GHCs, Eq is no longer a superclass of Num, so you need an Eq a constraint too. More importantly, though, it makes defining other instances of Eqa rather fraught: if we add instance Eqa () where { _ =~ _ = True ; _ /~ _ = False }, then () =~ () gives us an "Overlapping instances" error, because () could have a Num instance!
@AntalS-Z Do you happen to know when (i.e., for which version of GHC) Eq ceased to be a superclass of Num?
@Jubobs: Since GHC 7.4.1. Here are the GHC 7.4.1 release notes, which says "The Num class no longer has Eq or Show superclasses"; compare the GHC 7.2.1 release notes, which say nothing of the sort. This is from Ben James's answer to exactly this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.