views:

68

answers:

1

For example I want to add two expressions e1 and e2

toString (Plus e1 e)= ??

I am guessing it would be something like

toString (Plus e1 e)= ((toString e1) ++ "+" ++ (toString e2))
+1  A: 

I've made a few assumptions about how Plus is defined. With this code you can just type expr at the ghci prompt and ghci will print out the expression 100-30+100+30.

module Main where

data Expr =
    Plus Expr Expr
  | Minus Expr Expr
  | Value Int

-- This works but is not as Haskell-y as using Show
toString (Plus e1 e2) = toString e1 ++ "+" ++ toString e2
toString (Minus e1 e2)  = toString e1 ++ "-" ++ toString e2
toString (Value n) = show n

instance Show Expr where
  show (Plus e1 e2) = show e1 ++ "+" ++ show e2
  show (Minus e1 e2)  = show e1 ++ "-" ++ show e2
  show (Value n) = show n

expr = (Plus
         (Minus (Value 100) (Value 30))
         (Plus (Value 100) (Value 30)))
Tim Stewart