Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Polymorphic Tree Walking</strong>, Python version</p> <pre><code>#!/usr/bin/python class Node: """base class, you should not process one of these""" def process(self): raise('you should not be processing a node') class BinaryNode(Node): """base class for binary nodes""" def __init__(self, _left, _right): self.left = _left self.right = _right def process(self): raise('you should not be processing a binarynode') class Plus(BinaryNode): def process(self): return self.left.process() + self.right.process() class Minus(BinaryNode): def process(self): return self.left.process() - self.right.process() class Mul(BinaryNode): def process(self): return self.left.process() * self.right.process() class Div(BinaryNode): def process(self): return self.left.process() / self.right.process() class Num(Node): def __init__(self, _value): self.value = _value def process(self): return self.value def demo(n): print n.process() demo(Num(2)) # 2 demo(Plus(Num(2),Num(5))) # 2 + 3 demo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5)))) # (2 * 3) + (10 / 2) </code></pre> <p>The tests are just building up the binary trees by using constructors.</p> <p>program structure:</p> <p>abstract base class: Node</p> <ul> <li>all Nodes inherit from this class</li> </ul> <p>abstract base class: BinaryNode</p> <ul> <li>all binary operators inherit from this class</li> <li>process method does the work of evaluting the expression and returning the result</li> </ul> <p>binary operator classes: Plus,Minus,Mul,Div</p> <ul> <li>two child nodes, one each for left side and right side subexpressions</li> </ul> <p>number class: Num</p> <ul> <li>holds a leaf-node numeric value, e.g. 17 or 42</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload