Convert expression to string representation?

Consider the following Haskell code:

module Expr where -- Variables are named by strings, assumed to be identifiers: type Variable = String -- Representation of expressions: data Expr = Const Integer | Var Variable | Plus Expr Expr | Minus Expr Expr | Mult Expr Expr deriving (Eq, Show) simplify :: Expr->Expr simplify (Mult (Const 0)(Var"x")) = Const 0 simplify (Mult (Var "x") (Const 0)) = Const 0 simplify (Plus (Const 0) (Var "x")) = Var "x" simplify (Plus (Var "x") (Const 0)) = Var "x" simplify (Mult (Const 1) (Var"x")) = Var "x" simplify (Mult(Var"x") (Const 1)) = Var "x" simplify (Minus (Var"x") (Const 0)) = Var "x" simplify (Plus (Const x) (Const y)) = Const (x + y) simplify (Minus (Const x) (Const y)) = Const (x - y) simplify (Mult (Const x) (Const y)) = Const (x * y) simplify x = x toString :: Expr->String 

How to convert expression to string representation?

eg.

 toString (Var "x") = "x" toString (Plus (Var "x") (Const 1)) = "x + 1" toString (Mult (Plus (Var "x") (Const 1)) (Var "y")) = "(x + 1) * y" 
+3
source share
3 answers

Instead of calling your function, toString might be preferable to using Show class type . Then your data type can be used wherever a Show instance can be used. Show is the Haskell standard method for converting "things" to strings.

 instance Show Expr where show (Var "x") = "x" -- etc. 
+3
source

It looks like you have almost none.

Here is an example

 toString (Plus e1 e2) = (toString e1) ++ " + " ++ (toString e2) toString (Const i) = show i 
+1
source

All Articles