Home > database >  Haskell Polymorphism on Datatype
Haskell Polymorphism on Datatype

Time:11-02

I want to define a polymorphic datatype to represent expressions involving addition, multiplication and numbers

data Expr = 
  Number (Integer, Double)
  | Plus Expr Expr
  | Times Expr Expr
  deriving Show

expr1 = Times (Plus (Number (5.2 :: Double)) (Number 4)) (Number 2)
expr2 = Plus (Number (2 :: Int)) (Times (Number 3) (Number 4))
expr3 = Times (Number "hello") (Number "world")

I do also have the following test cases:

testEval1 = "Expected 18.4; eval expr1 returned "    show (eval expr1 :: Double)
testEval2 = "Expected 14; eval expr2 returned "    show (eval expr2 :: Int)
testEval = putStr (testEval1    "\n"    testEval2    "\n")

How would I define that in Haskell?

CodePudding user response:

In the comments, chi writes:

You could use data Expr = NumberI Integer | NumberD Double | Plus Expr Expr | ... so that you can store both kinds of constants in your expressions

... but individually.

Haskell doesn't have untagged union types. Haskell has tagged union types (these are searchable terms).

So the Integer value gets its own tag, NumberI, and the Double value gets its own tag, NumberD.

What you wrote in your data type definition, Number (Integer, Double), means to have both Integer and Double at the same time in a value of type Expr.

But in your example you wrote Number (5.2 :: Double) and Number 4 where you have either a Double (5.2), or what you presumably meant as an Integer (4) there, inside values of type Expr.

  • Related