V. Kalle
V. Kalle

Reputation: 13

Algebraic Data Type in Haskell

I'm trying to write a simple data type for mathematical expressions. The code I have right now is:

data Expr
  = Num Double
  | Add Expr Expr
  | Mul Expr Expr
  | Sin Expr
  | Cos Expr
  | X
  deriving Eq

This works as expected but I want to make it simpler with only one line for binary operators (Add and Mul) and one for unary operators (Sin and Cos). Any suggestions?

Upvotes: 1

Views: 88

Answers (1)

Rein Henrichs
Rein Henrichs

Reputation: 15605

You can use, e.g.,

data BinOp = Add | Mul
data UnaryOp = Sin | Cos

data Expr
  = Num Double
  | Binary BinOp Expr Expr
  | Unary UnaryOp Expr

YMMV on whether this is simpler.

Upvotes: 6

Related Questions