Professional Documents
Culture Documents
Recursive structure:
list, tree
File system
single file
Binary tree
a leaf
or an internal node
(root) and two smaller
trees
Recursive structure
a constant, or
an operator and two smaller expressions
representation of an expression
QUIZ
Which UML diagram models
recursive bullet lists best?
2.
1.
Tree t =
new Node(
new Leaf(6),
Operator.PLUS,
new Node(
new Node(new Leaf(8),Operator.MULT,new Leaf(2)),
Operator.MINUS,
new Leaf(1)
)
);
3.
4.
5. I dont know
evaluate(v):
if v is a leaf:
return number stored at v
else
x = evaluate(left subexpression stored at v)
y = evaluate(right subexpression stored at v)
return x o y (where o is operator stored at v)
QUIZ
For QUIZ:
<ul>
<li>a simple bullet list</li>
<li>containing smaller lists</li>
<li>
<ul>
<li>a smaller sublist</li>
<li>
li
<ul>
<li>a tiny list</li>
<li>with several entries</li>
</ul>
</li>
<li>look: recursive lists!</li>
</ul>
</li>
</ul>
necessary!
in class Leaf:
public int getValue() { return value; }
in class Node:
public int getValue() {
return op.apply(left.getValue(),
right.getValue());
}
Example: 8 * (5 + 2)
expr1.getValue()
Example: 8 * (5 + 2)
Node expr1 =
new Node(
new Leaf(8),
Operator.MULT,
new Node(
new Leaf(5),
Operator.PLUS,
new Leaf(2)
)
);
QUIZ
In interface Tree
In class Leaf
In class Node
callback
callback to
to problem
problem
specific
specific
methods
method
defined
by external visitor
Example: 8 * (5 + 2)
expr1.accept(new EvaluateVisitor())
QUIZ
evaluate(t)
public
bli St
String
i
visitBulletList(BulletList
i itB ll tLi t(B ll tLi t b) {
String result = "<ul>";
for (HTML h : b.getEntries())
result += "<li>"+h.accept(this)+"</li>";
return result+"</ul>;
}
1.
2.
3.
4.
5.
text(v):
if v is a leaf:
return number
else
return "("
+ text( left subexpression)
+ operator
+ text( right subexpression )
+ ")"
Application:
System.out.println(t.accept(new PrintVisitor()));
Recursive list
new DrawVisitor(t)
where
Tree t = new Node(new Leaf(6),Operator.PLUS,
new Node(new Node(new Leaf(8),Operator.MULT,
new Leaf(2)),Operator.MINUS,new Leaf(1)));
or an element followed
by a shorter list
[]
[ 2, 7, 13, 1]
class representing
p
g element and shorter list
public class Cons implements ConsList {
private Object hd;
private ConsList tl;
public Cons(Object x, ConsList y) { hd = x; tl = y; }
}
In interface ConsList
abstract <T> T accept(ConsListVisitor<T> v);
In class Nil
specific
specific
methods
method
defined
by external visitor
In class Cons
(simple) labyrinth
empty labyrinth