Change number type with Haskell

I am working on a small symbolic library to do some calculations using Haskell.

To represent a 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 was able to create an instance Num, to be able to use the operator +and -for 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

Works!

Now I would like to be able to use +and -with numbers too ( Doubleor Int) to write simpler:

( MathExpress expression ) * 2.0

Is it possible (by creating an instance or something) to make Haskell output 2.0 as MathDouble 2.0?

+4
source share
1

Num MathExpress:

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

fromInteger - , , 1 Int, Integer, Double, Complex MathExpress. , , 2.0 42.7, MathExpress, Fractional typeclass ( @ØrjanJohansen), fromRational, fromInteger.

+9

Source: https://habr.com/ru/post/1583871/


All Articles