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....
    – jamshidh
    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?
    – user5960886
    Mar 7, 2016 at 4:13
  • You can import Prelude hiding (+), but this is considered bad form. See below for another way.
    – jamshidh
    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.
    – chi
    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.

1
  • 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.
    – badcook
    Mar 8, 2016 at 5:12

Your Answer

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