0

I can get the file to compile fine. However, when I try to test if the operator is overloaded correctly I get the error message:

*Main> MyFloat (2,3) + MyFloat(3,3) <interactive>:19:15: Ambiguous occurrence `+' It could refer to either `Main.+', defined at problem1.hs:3:16 or `Prelude.+', imported from `Prelude' at problem1.hs:1:1 (and originally defined in `GHC.Num') 

The code I am using is:

data MyFloat = MyFloat (Int, Int) MyFloat (a, b) + MyFloat (c, d) = ((fromIntegral a)/ (fromIntegral(order a)) * 10^b) Prelude.+ ((fromIntegral c)/ (fromIntegral(order c)) * 10^d) order :: Int -> Int order b | b == 0 = 0 | otherwise = ((ceiling ((logBase 10 (abs (fromIntegral b))))) Prelude.+ 1) 

Am I misunderstanding how overload operators correctly, or is there a different problem entirely?

4
  • 1
    The error is that you have defined your own (+) operator, which conflicts with the standard one from the prelude.... Commented Mar 7, 2016 at 4:11
  • @jamshidh So how can I tell the complier when adding these data types it should use the Main.+ or do I have to go MyFloat (a,b) Main.+ MyFloat (b,c) each time? Commented Mar 7, 2016 at 4:13
  • You can import Prelude hiding (+), but this is considered bad form. See below for another way. Commented Mar 7, 2016 at 4:14
  • 1
    There's no operator overloading in Haskell. You can only add new instances to typeclasses, with similar consequences. Commented Mar 7, 2016 at 13:35

1 Answer 1

3

What you really want to do is make your class an instance of Num

instance Num MyFloat where x + y = <put in your definition here> 

Note that Num will require a definition of (*), abs, signum, fromInteger, (negate | (-)) also

In haskell, one typically overloads functions using class definitions.

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

1 Comment

As @chi points out, "typical" isn't strong enough; you can only "overload" functions with typeclasses. Even then overloading isn't really a particularly helpful way of thinking about what's going on.