Thursday, August 18, 2016

get string for binary expression tree

Include brackets only when required.
- No brackets for high precedence operator.
- No brackets for root node.
   +
 *   7
2 3
= "2*3+7"

   *
 +   7
2 3
= "(2+3)*7"

   /
 *   /
2 3 6 2
= "2*3/6/2"
This is bad design as the flag is used only in low precedence operator class.
// bad design
inode:
    text(putbrackets)

dataNode: inode
    data
    text(putbrackets = true):
        if data == null:
            throw
        return data.tostring()

operatorHighPrecedenceNode: inode
    inode leftOperand
    inode rightOperand
    operator
    text(putbrackets = true):
        if leftOperand == null 
            || rightOperand == null
            || operator == null:
            throw
        return
            leftOperand.text() + 
            operator + 
            rightOperand.text()

operatorLowPrecedenceNode: operatorHighPrecedenceNode
    text(putbrackets = true):
        return
            putbrackets ?
            "(" + base.text() + ")" :
            base.text()

string stringify(inode n):
    if n == null:
        return ""
    return n.text(false)
Instead put the behavior in a class and let the impl' classes call the desired behavior so there are no "ifs" in the design logic.
// good design
bracketBehavior:
    string excludeBrackets(operatorNode n):
        if n == null ||
            n.left == null ||
            n.operator == null ||
            n.right == null:
            throw
        return textInner(n)
    string includeBrackets(operatorNode n):
        if n == null ||
            n.left == null ||
            n.operator == null ||
            n.right == null:
            throw
        return "(" + textInner(n) + ")"
    string textInner(operatorNode n):
        return
            n.left.text() +
            n.operator +
            n.right.text()

inode:
    string text():
    
dataNode: inode
    data
    string text():
        if data == null:
            throw
        return data.toString()

abstract operatorNode: inode
    string operator
    inode left
    inode right
    bracketBehavior
    abstract string text():

operatorHighPNode: operatorNode
    string text():
        return bracketBehavior.excludeBrackets(this)
        
operatorLowPNode: operatorNode
    string text():
        return bracketBehavior.includeBrackets(this)

rootNode: operatorNode
    string text():
        return bracketBehavior.excludeBrackets(this)

string stringify(inode n):
    if n == null:
        return ""
    return n.text()
[Hat tip to LW]

No comments:

Post a Comment