Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify type of number with Haskell

I'm working on a small symbolic library to perform some calculation with Haskell.

To represent symbolic operation I created this data type :

data MathExpress =                        -- A math expression
       MathDouble Double                  -- Represent a number      
     | MathAdd MathExpress MathExpress    -- Add 2 expressions 
     | MathSoust MathExpress MathExpress  -- Subtract 2 expressions
     | ...

I managed to create a Num instance to be able to use the operator + and - on my type MathExpress.

instance Num MathExpress where
  (+) (expa) (expb)  = MathAdd expa expb
  (-) (expa) (expb)  = MathSoust expa expb
  ...

and when I write :

( MathExpress expression ) * MathDouble 2.0

It's working !

Now, I would like to be able to use + and - with numbers too (Double or Int) to write more simply :

( MathExpress expression ) * 2.0

Is it possible (by creating an instance or anything) to make Haskell infer 2.0 as a MathDouble 2.0 ?

like image 333
JeanJouX Avatar asked Jan 09 '23 12:01

JeanJouX


1 Answers

You need to finish the implementation of Num MathExpress:

instance Num MathExpress where
    fromInteger n = MathDouble (fromInteger n)
    ...

The fromInteger methods is what allows numeric literals to be polymorphic, so 1 can be interpreted as Int, Integer, Double, Complex, or in this case MathExpress. If you want to have a number like 2.0 or 42.7 be interpreted as a MathExpress then you'll also need to implement the Fractional typeclass (as noted by @ØrjanJohansen), and in particular the fromRational method, which can be implemented essentially identically to fromInteger.

like image 148
bheklilr Avatar answered Jan 19 '23 11:01

bheklilr