How do I write adding two elements to a string representation?

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


source to share


1 answer


I've made several assumptions about how Plus is defined. With this code, you can simply type expr on the ghci command line 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)))

      

+1


source







All Articles