Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package simplify
- import "fmt"
- import "hw1/expr"
- // Depth should return the simplified expresion
- func Simplify(e expr.Expr, env expr.Env) expr.Expr {
- //TODO implement the simplify
- // Case 1: Any Var should be replaced with its value
- v, ok := e.(expr.Var)
- if ok == true {
- v = v
- if e.Eval(env) == 0 {
- return e
- }
- ans := fmt.Sprintf("%f", e.Eval(env))
- tp, ok := expr.Parse(ans)
- if ok == nil {
- return tp
- }
- }
- // Case 2: Any Unary with Literal should be replaced with Literal
- u, ok := e.(expr.Unary)
- if ok == true {
- temp := Simplify(u.X, env)
- if temp == u.X {
- return e
- }
- l, ok3 := temp.(expr.Literal)
- if ok3 == true {
- l = l
- if u.Op == '-' {
- l = -1 * l
- }
- return l
- }
- }
- b, ok := e.(expr.Binary)
- if ok == true {
- // Case 4: Any Binary with addition of 0 should reduce
- l0, ok := b.X.(expr.Literal)
- if ok == true {
- l0 = l0
- if l0 == 0 {
- return b.Y
- }
- }
- l2, ok2 := b.Y.(expr.Literal)
- if ok2 == true {
- l2 = l2
- if l2 == 0 {
- return b.X
- }
- }
- // Case 3: Any Binary with both Literals return Literals
- l, ok2 := b.X.(expr.Literal)
- // Own Case: Binary with Var
- v, okk2 := b.X.(expr.Var)
- // Own case: One child is Binary, one is Var
- bl, bok := b.X.(expr.Binary)
- //TODO: put it HERE!!!!
- v = v
- if ok2 == true || okk2 == true || bok == true{
- if okk2 == true {
- temp := Simplify(b.X, env)
- if b.X != temp {
- tpl, okkk := temp.(expr.Literal)
- okkk = okkk
- l = tpl
- } else if bok == true {
- bl = bl
- if bok == true {
- fmt.Printf("f\n")
- bltp := Simplify(bl, env)
- l = bltp.(expr.Literal)
- } else {
- return e
- }
- }
- }
- l2, ok3 := b.Y.(expr.Literal)
- v2, okk3 := b.Y.(expr.Var)
- v2 = v2
- if ok3 == true || okk3 == true {
- if okk3 == true {
- temp := Simplify(b.Y, env)
- if b.Y != temp {
- tpl2, okkk2 := temp.(expr.Literal)
- okkk2 = okkk2
- l2 = tpl2
- } else {
- return e
- }
- }
- l = l
- l2 = l2
- if b.Op == '+' {
- l += l2
- } else if b.Op == '-' {
- l -= l2
- } else if b.Op == '*' {
- l *= l2
- } else if b.Op == '/' {
- l /= l2
- }
- return l
- }
- }
- }
- panic("TODO: implement this!")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement