1
votes

I'm a newbie in the Haskell's world, so this may be a basic question.

Could this code:

data Numero =
  Integer Integer |
  Rational Rational |
  Double Double
  deriving (Show)
data Elemento =
  Numero Numero |
  Incognita String
  deriving (Show)

data Monomio = Monomio {base :: Elemento, exp :: Numero} deriving(Show)

main = print (Monomio (Numero (Integer 15)) (Integer 20))

be expressed without the explicit types at:

(Monomio (Numero (Integer 15)) (Integer 20))

?

This expression:

main = print (Monomio (Integer 15) (Integer 20))

which is shorter is not ambiguous, as (Integer 15) can't fit the definition of (Incognita String), but it doesn't compile:

main.hs:13:24:
    Couldn't match expected type `Elemento' with actual type `Numero'
    In the first argument of `Monomio', namely `(Integer 15)'
    In the first argument of `print', namely
      `(Monomio (Integer 15) (Integer 20))'

Why?

1

1 Answers

5
votes

The Numero in the expression

(Monomio (Numero (Integer 15)) (Integer 20))

is not a type - but a type value constructor, so you need it in order to construct something a value of type Elemento.

One way would be to use fromIntegral in order to achieve "automatic" conversion.

For the String-like you have the OverloadedStrings-Language extension but for numeric types there is nothing like that (at least to my knowledge).

On a side note: I think it makes your code much more confusing that you have a type of Numero and a type-constructor of Numero where the latter is constructs something of type Elemento.

I would use NumElemento and VarElemento or something the like.


A more concise but completely different approach (as written in my comment), would be to use polynomials instead of monomes.

data Polynomial1 = P1 String [Rational]
newtype Polynomial  = P [Polynomial1]

here would P1 "X" [1,2,3] stand for p(x) = 1 + 2*x + 3*x² and P [P1 "X" [1,2], P1 "Y" [0,1]] stand for p(x,y) = 1 + 2*x + y

This approach solves many problems that occur, and if you are careful you can even represent taylor series (save you're not checking wether youre not checking cosine == cosine - though obviously true, you happen to run in an infinite comparison process).