.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{
. if \nF \{
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "HTML::Tree::AboutTrees 3"
.TH HTML::Tree::AboutTrees 3 "2024-01-23" "perl v5.16.3" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
HTML::Tree::AboutTrees \-\- article on tree\-shaped data structures in Perl
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 1
\& # This an article, not a module.
.Ve
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
The following article by Sean M. Burke first appeared in \fIThe Perl
Journal\fR #18 and is copyright 2000 The Perl Journal. It appears
courtesy of Jon Orwant and The Perl Journal. This document may be
distributed under the same terms as Perl itself.
.SH "Trees"
.IX Header "Trees"
\&\-\- Sean M. Burke
.Sp
.RS 4
\&\*(L"AaaAAAaauugh! Watch out for that tree!\*(R"
\*(-- \fIGeorge of the Jungle theme\fR
.RE
.PP
Perl's facility with references, combined with its automatic management of
memory allocation, makes it straightforward to write programs that store data
in structures of arbitrary form and complexity.
.PP
But I've noticed that many programmers, especially those who started out
with more restrictive languages, seem at home with complex but uniform
data structures \*(-- N\-dimensional arrays, or more struct-like things like
hashes\-of\-arrays(\-of\-hashes(\-of\-hashes), etc.) \*(-- but they're often uneasy
with building more freeform, less tabular structures, like
tree-shaped data structures.
.PP
But trees are easy to build and manage in Perl, as I'll demonstrate
by showing off how the HTML::Element class manages elements in an \s-1HTML\s0
document tree, and by walking you through a from-scratch implementation
of game trees. But first we need to nail down what we mean by a \*(L"tree\*(R".
.ie n .SS "Socratic Dialogues: ""What is a Tree?"""
.el .SS "Socratic Dialogues: ``What is a Tree?''"
.IX Subsection "Socratic Dialogues: What is a Tree?"
My first brush with tree-shaped structures was in linguistics classes,
where tree diagrams are used to describe the syntax underlying natural
language sentences. After learning my way around \fIthose\fR trees, I
started to wonder \*(-- are what I'm used to calling \*(L"trees\*(R" the same as what
programmers call \*(L"trees\*(R"? So I asked lots of helpful and patient
programmers how they would define a tree. Many replied with a
answer in jargon that they could not really explain (understandable,
since explaining things, especially defining things, is harder
than people think):
.Sp
.RS 4
\&\-\- So what \fIis\fR a \*(L"tree\*(R", a tree-shaped data structure?
.Sp
\&\-\- A tree is a special case of an acyclic directed graph!
.Sp
\&\-\- What's a \*(L"graph\*(R"?
.Sp
\&\-\- Um... lines... and... you draw it... with... arcs! nodes! um...
.RE
.PP
The most helpful were folks who couldn't explain directly, but with
whom I could get into a rather Socratic dialog (where \fII\fR asked the
half-dim half-earnest questions), often with much doodling of
illustrations...
.PP
Question: so what's a tree?
.PP
Answer: A tree is a collection of nodes that are linked together in a,
well, tree-like way! Like this \fI[drawing on a napkin]:\fR
.PP
.Vb 5
\& A
\& / \e
\& B C
\& / | \e
\& D E F
.Ve
.PP
Q: So what do these letters represent?
.PP
A: Each is a different node, a bunch of data. Maybe C is a
bunch of data that stores a number, maybe a hash table, maybe nothing
at all besides the fact that it links to D, E, and F (which are other
nodes).
.PP
Q: So what're the lines between the nodes?
.PP
A: Links. Also called \*(L"arcs\*(R". They just symbolize the fact that each
node holds a list of nodes it links to.
.PP
Q: So what if I draw nodes and links, like this...
.PP
.Vb 5
\& B \-\- E
\& / \e / \e
\& A C
\& \e /
\& E
.Ve
.PP
Is that still a tree?
.PP
A: No, not at all. There's a lot of un-treelike things about that.
First off, E has a link coming off of it going into nowhere. You can't have
a link to nothing \*(-- you can only link to another node. Second off, I
don't know what that sideways link between B and E means...
.PP
Q: Okay, let's work our way up from something simpler. Is this a tree...?
.PP
.Vb 1
\& A
.Ve
.PP
A: Yes, I suppose. It's a tree of just one node.
.PP
Q: And how about...
.PP
.Vb 1
\& A
\&
\& B
.Ve
.PP
A: No, you can't just have nodes floating there, unattached.
.PP
Q: Okay, I'll link A and B. How's this?
.PP
.Vb 3
\& A
\& |
\& B
.Ve
.PP
A: Yup, that's a tree. There's a node A, and a node B, and they're linked.
.PP
Q: How is that tree any different from this one...?
.PP
.Vb 3
\& B
\& |
\& A
.Ve
.PP
A: Well, in both cases A and B are linked. But it's in a different
direction.
.PP
Q: Direction? What does the direction mean?
.PP
A: Well, it depends what the tree represents. If it represents a
categorization, like this:
.PP
.Vb 3
\& citrus
\& / | \e
\& orange lemon kumquat ...
.Ve
.PP
then you mean to say that oranges, lemons, kumquats, etc., are a kind of
citrus. But if you drew it upside down, you'd be saying, falsely, that
citrus is a kind of kumquat, a kind of lemon, and a kind of orange.
If the tree represented cause-and-effect (or at least what situations
could follow others), or represented what's a part of what, you
wouldn't want to get those backwards, either. So with the nodes you
draw together on paper, one has to be over the other, so you can tell which
way the relationship in the tree works.
.PP
Q: So are these two trees the same?
.PP
.Vb 4
\& A A
\& / \e / \e
\& B C B \e
\& C
.Ve
.PP
A: Yes, although by convention we often try to line up things in the
same generation, like it is in the diagram on the left.
.PP
Q: \*(L"generation\*(R"? This is a family tree?
.PP
A: No, not unless it's a family tree for just yeast cells or something
else that reproduces asexually.
But for sake of having lots of terms to use, we just pretend that links
in the tree represent the \*(L"is a child of\*(R" relationship, instead of \*(L"is a
kind of\*(R" or \*(L"is a part of\*(R", or \*(L"could result from\*(R", or whatever the real
relationship is. So we get to borrow a lot of kinship words for
describing trees \*(-- B and C are \*(L"children\*(R" (or \*(L"daughters\*(R") of A; A is
the \*(L"parent\*(R" (or \*(L"mother\*(R") of B and C. Node C is a \*(L"sibling\*(R" (or
\&\*(L"sister\*(R") of node C; and so on, with terms like \*(L"descendants\*(R" (a node's
children, children's children, etc.), and \*(L"generation\*(R" (all the
nodes at the same \*(L"level\*(R" in the tree, i.e., are either all
grandchildren of the top node, or all great-grand-children, etc.), and
\&\*(L"lineage\*(R" or \*(L"ancestors\*(R" (parents, and parent's parents, etc., all the
way to the topmost node).
.PP
So then we get to express rules in terms like "\fBA node cannot have more
than one parent\fR", which means that this is not a valid tree:
.PP
.Vb 5
\& A
\& / \e
\& B C
\& \e /
\& E
.Ve
.PP
And: "\fBA node can't be its own parent\fR", which excludes this looped-up
connection:
.PP
.Vb 3
\& /\e
\& A |
\& \e/
.Ve
.PP
Or, put more generally: "\fBA node can't be its own ancestor\fR", which
excludes the above loop, as well as the one here:
.PP
.Vb 7
\& /\e
\& Z |
\& / |
\& A |
\& / \e |
\& B C |
\& \e/
.Ve
.PP
That tree is excluded because A is a child of Z, and Z is a child of C,
and C is a child of A, which means A is its own great-grandparent. So
this whole network can't be a tree, because it breaks the sort of
meta-rule: \fBonce any node in the supposed tree breaks the rules for
trees, you don't have a tree anymore.\fR
.PP
Q: Okay, now, are these two trees the same?
.PP
.Vb 3
\& A A
\& / | \e / | \e
\& B C D D C B
.Ve
.PP
A: It depends whether you're basing your concept of trees on each node
having a set (unordered list) of children, or an (ordered) list of
children. It's a question of whether ordering is important for what
you're doing. With my diagram of citrus types, ordering isn't
important, so these tree diagrams express the same thing:
.PP
.Vb 3
\& citrus
\& / | \e
\& orange lemon kumquat
\&
\& citrus
\& / | \e
\& kumquat orange lemon
.Ve
.PP
because it doesn't make sense to say that oranges are \*(L"before\*(R" or
\&\*(L"after\*(R" kumquats in the whole botanical scheme of things. (Unless, of
course, you \fIare\fR using ordering to mean something, like a degree of
genetic similarity.)
.PP
But consider a tree that's a diagram of what steps are comprised in an
activity, to some degree of specificity:
.PP
.Vb 8
\& make tea
\& / | \e
\& pour infuse serve
\& hot water / \e
\&in cup/pot / \e
\& add let
\& tea sit
\& leaves
.Ve
.PP
This means that making tea consists of putting hot water in a cup or
put, infusing it (which itself consists of adding tea leaves and letting
it sit), then serving it \*(-- \fIin that order\fR. If you serve an empty
dry pot (sipping from empty cups, etc.), let it sit, add tea leaves,
and pour in hot water, then what you're doing is performance art, not
tea preparation:
.PP
.Vb 9
\& performance
\& art
\& / | \e
\& serve infuse pour
\& / \e hot water
\& / \e in cup/pot
\& let add
\& sit tea
\& leaves
.Ve
.PP
Except for my having renamed the root, this tree is the same as
the making-tea tree as far as what's under what, but it differs
in order, and what the tree means makes the order important.
.PP
Q: Wait \*(-- \*(L"root\*(R"? What's a root?
.PP
A: Besides kinship terms like \*(L"mother\*(R" and \*(L"daughter\*(R", the jargon for
tree parts also has terms from real-life tree parts: the part that
everything else grows from is called the root; and nodes that don't
have nodes attached to them (i.e., childless nodes) are called
\&\*(L"leaves\*(R".
.PP
Q: But you've been drawing all your trees with the root at the top and
leaves at the bottom.
.PP
A: Yes, but for some reason, that's the way everyone seems to think of
trees. They can draw trees as above; or they can draw them sort of
sideways with indenting representing what nodes are children of what:
.PP
.Vb 6
\& * make tea
\& * pour hot water in cup/pot
\& * infuse
\& * add tea leaves
\& * let sit
\& * serve
.Ve
.PP
\&...but folks almost never seem to draw trees with the root at the
bottom. So imagine it's based on spider plant in a hanging pot.
Unfortunately, spider plants \fIaren't\fR botanically trees, they're
plants; but \*(L"spider plant diagram\*(R" is rather a mouthful, so let's just
call them trees.
.SS "Trees Defined Formally"
.IX Subsection "Trees Defined Formally"
In time, I digested all these assorted facts about programmers' ideas of
trees (which turned out to be just a more general case of linguistic
ideas of trees) into a single rule:
.PP
* A node is an item that contains (\*(L"is over\*(R", \*(L"is parent of\*(R", etc.)
zero or more other nodes.
.PP
From this you can build up formal definitions for useful terms, like so:
.PP
* A node's \fBdescendants\fR are defined as all its children, and all
their children, and so on. Or, stated recursively: a node's
descendants are all its children, and all its children's descendants.
(And if it has no children, it has no descendants.)
.PP
* A node's \fBancestors\fR consist of its parent, and its parent's
parent, etc, up to the root. Or, recursively: a node's ancestors
consist of its parent and its parent's ancestors. (If it has no parent,
it has no ancestors.)
.PP
* A \fBtree\fR is a root node and all the root's descendants.
.PP
And you can add a proviso or two to clarify exactly what I impute to the
word \*(L"other\*(R" in \*(L"other nodes\*(R":
.PP
* A node cannot contain itself, or contain any node that contains it,
etc. Looking at it the other way: a node cannot be its own parent or
ancestor.
.PP
* A node can be root (i.e., no other node contains it) or can be
contained by only one parent; no node can be the child of two or more
parents.
.PP
Add to this the idea that children are sometimes ordered, and sometimes
not, and that's about all you need to know about defining what a tree
is. From there it's a matter of using them.
.SS "Markup Language Trees: HTML-Tree"
.IX Subsection "Markup Language Trees: HTML-Tree"
While not \fIall\fR markup languages are inherently tree-like, the
best-known family of markup languages, \s-1HTML, SGML,\s0 and \s-1XML,\s0 are about
as tree-like as you can get. In these languages, a document consists
of elements and character data in a tree structure where
there is one root element, and elements can contain either other
elements, or character data.
.Sp
.RS 4
Footnote:
For sake of simplicity, I'm glossing over
comments (), processing instructions (), and declarations (, ).
And I'm not bothering to distinguish entity references
(<, @) or \s-1CDATA\s0 sections () from normal text.
.RE
.PP
For example, consider this \s-1HTML\s0 document:
.PP
.Vb 10
\&
\&
\&
\& Blank Document!
\&
\&
\&
\& I\*(Aqve got
\&
\& something to saaaaay
\&
\& !
\&
\&
.Ve
.PP
I've indented this to point out what nodes (elements or text items) are
children of what, with each node on a line of its own.
.PP
The HTML::TreeBuilder module (in the \s-1CPAN\s0 distribution HTML-Tree)
does the work of taking \s-1HTML\s0 source and
building in memory the tree that the document source represents.
.Sp
.RS 4
Footnote: it requires the HTML::Parser module, which tokenizes the
source \*(-- i.e., identifies each tag, bit of text, comment, etc.
.RE
.PP
The trees structures that it builds represent bits of text with
normal Perl scalar string values; but elements are represented with
objects \*(-- that is, chunks of data that belong to a
class (in this case, HTML::Element), a class that provides methods
(routines) for accessing the pieces of data in each element, and
otherwise doing things with elements. (See my article in TPJ#17 for a
quick explanation of objects, the \s-1POD\s0 document \f(CW\*(C`perltoot\*(C'\fR for a longer
explanation, or Damian Conway's excellent book \fIObject-Oriented Perl\fR
for the full story.)
.PP
Each HTML::Element object contains a number of pieces of data:
.PP
* its element name (\*(L"html\*(R", \*(L"h1\*(R", etc., accessed as \f(CW$element\fR\->tag)
.PP
* a list of elements (or text segments) that it contains, if any
(accessed as \f(CW$element\fR\->content_list or \f(CW$element\fR\->content, depending on
whether you want a list, or an arrayref)
.PP
* what element, if any, contains it (accessed as \f(CW$element\fR\->parent)
.PP
* and any \s-1SGML\s0 attributes that the element has,
such as \f(CW\*(C`lang="en\-US"\*(C'\fR, \f(CW\*(C`align="center"\*(C'\fR, etc. (accessed as
\&\f(CW$element\fR\->attr('lang'), \f(CW$element\fR\->attr('center'), etc.)
.PP
So, for example, when HTML::TreeBuilder builds the tree for the above
\&\s-1HTML\s0 document source, the object for the \*(L"body\*(R" element has these pieces of
data:
.PP
.Vb 8
\& * element name: "body"
\& * nodes it contains:
\& the string "I\*(Aqve got "
\& the object for the "em" element
\& the string "!"
\& * its parent:
\& the object for the "html" element
\& * bgcolor: "#d010ff"
.Ve
.PP
Now, once you have this tree of objects, almost anything you'd want to
do with it starts with searching the tree for some bit of information
in some element.
.PP
Accessing a piece of information in, say, a hash of hashes of hashes,
is straightforward:
.PP
.Vb 1
\& $password{\*(Aqsean\*(Aq}{\*(Aqsburke1\*(Aq}{\*(Aqhpux\*(Aq}
.Ve
.PP
because you know that all data points in that structure are accessible
with that syntax, but with just different keys. Now, the \*(L"em\*(R" element
in the above \s-1HTML\s0 tree does happen to be accessible
as the root's child #1's child #1:
.PP
.Vb 1
\& $root\->content\->[1]\->content\->[1]
.Ve
.PP
But with trees, you typically don't know the exact location (via
indexes) of the data you're looking for. Instead, finding what you want
will typically involve searching through the tree, seeing if every node is
the kind you want. Searching the whole tree is simple enough \*(-- look at
a given node, and if it's not what you want, look at its children, and
so on. HTML-Tree provides several methods that do this for you, such as
\&\f(CW\*(C`find_by_tag_name\*(C'\fR, which returns the elements (or the first element, if
called in scalar context) under a given node (typically the root) whose
tag name is whatever you specify.
.PP
For example, that \*(L"em\*(R" node can be found as:
.PP
.Vb 1
\& my $that_em = $root\->find_by_tag_name(\*(Aqem\*(Aq);
.Ve
.PP
or as:
.PP
.Vb 2
\& @ems = $root\->find_by_tag_name(\*(Aqem\*(Aq);
\& # will only have one element for this particular tree
.Ve
.PP
Now, given an \s-1HTML\s0 document of whatever structure and complexity, if you
wanted to do something like change every
.Sp
.RS 4
\fIstuff\fR
.RE
.PP
to
.Sp
.RS 4
\&\fB[\-\fR
\&\fIstuff\fR
\&\fB\-]\fR
.RE
.PP
the first step is to frame this operation in terms of what you're doing
to the tree. You're changing this:
.PP
.Vb 3
\& em
\& |
\& ...
.Ve
.PP
to this:
.PP
.Vb 5
\& em
\& / | \e
\& b ... b
\& | |
\& "[\-" "\-]"
.Ve
.PP
In other words, you're finding all elements whose tag name is \*(L"em\*(R",
setting its class attribute to \*(L"funky\*(R", and adding one child to the start
of its content list \*(-- a new \*(L"b\*(R" element
whose content is the text string \*(L"[\-\*(R" \*(-- and one to the end of its
content list \*(-- a new \*(L"b\*(R" element whose content is the text string \*(L"\-]\*(R".
.PP
Once you've got it in these terms, it's just a matter of running to the
HTML::Element documentation, and coding this up with calls to the
appropriate methods, like so:
.PP
.Vb 5
\& use HTML::Element 1.53;
\& use HTML::TreeBuilder 2.96;
\& # Build the tree by parsing the document
\& my $root = HTML::TreeBuilder\->new;
\& $root\->parse_file(\*(Aqwhatever.html\*(Aq); # source file
\&
\& # Now make new nodes where needed
\& foreach my $em ($root\->find_by_tag_name(\*(Aqem\*(Aq)) {
\& $em\->attr(\*(Aqclass\*(Aq, \*(Aqfunky\*(Aq); # Set that attribute
\&
\& # Make the two new B nodes
\& my $new1 = HTML::Element\->new(\*(Aqb\*(Aq);
\& my $new2 = HTML::Element\->new(\*(Aqb\*(Aq);
\& # Give them content (they have none at first)
\& $new1\->push_content(\*(Aq[\-\*(Aq);
\& $new2\->push_content(\*(Aq\-]\*(Aq);
\&
\& # And put \*(Aqem in place!
\& $em\->unshift_content($new1);
\& $em\->push_content($new2);
\& }
\& print
\& "\en",
\& $root\->as_HTML(), "\en";
.Ve
.PP
The class HTML::Element provides just about every method I can image you
needing, for manipulating trees made of HTML::Element objects. (And
what it doesn't directly provide, it will give you the components to build
it with.)
.SS "Building Your Own Trees"
.IX Subsection "Building Your Own Trees"
Theoretically, any tree is pretty much like any other tree, so you could
use HTML::Element for anything you'd ever want to do with tree-arranged
objects. However, as its name implies, HTML::Element is basically
\&\fIfor\fR \s-1HTML\s0 elements; it has lots of features that make sense only for
\&\s-1HTML\s0 elements (like the idea that every element must have a tag-name).
And it lacks some features that might be useful for general applications
\&\*(-- such as any sort of checking to make sure that you're not trying to
arrange objects in a non-treelike way. For a general-purpose tree class
that does have such features, you can use Tree::DAG_Node, also available
from \s-1CPAN. \s0
.PP
However, if your task is simple enough, you might find it overkill to
bother using Tree::DAG_Node. And, in any case, I find that the best
way to learn how something works is to implement it (or something like
it, but simpler) yourself. So I'll here discuss how you'd implement a tree
structure, \fIwithout\fR using any of the existing classes for tree nodes.
.SS "Implementation: Game Trees for Alak"
.IX Subsection "Implementation: Game Trees for Alak"
Suppose that the task at hand is to write a program that can play
against a human opponent at a strategic board game (as opposed to a
board game where there's an element of chance). For most such games, a
\&\*(L"game tree\*(R" is an essential part of the program (as I will argue,
below), and this will be our test case for implementing a tree
structure from scratch.
.PP
For sake of simplicity, our game is not chess or backgammon, but instead
a much simpler game called Alak. Alak was invented by the mathematician
A. K. Dewdney, and described in his 1984 book \fIPlaniverse\fR. The rules
of Alak are simple:
.Sp
.RS 4
Footnote: Actually, I'm describing only my
interpretation of the rules Dewdney describes in \fIPlaniverse\fR. Many
other interpretations are possible.
.RE
.PP
* Alak is a two-player game played on a one-dimensional board with
eleven slots on it. Each slot can hold at most one piece at a time.
There's two kinds of pieces, which I represent here as \*(L"x\*(R" and \*(L"o\*(R" \*(--
x's belong to one player (called X), o's to the other (called O).
.PP
* The initial configuration of the board is:
.PP
.Vb 1
\& xxxx_\|_\|_oooo
.Ve
.PP
For sake of the article, the slots are numbered from 1 (on the left) to
11 (on the right), and X always has the first move.
.PP
* The players take turns moving. At each turn, each player can move
only one piece, once. (This unlike checkers, where you move one piece
per move but get to keep moving it if you jump an your opponent's
piece.) A player cannot pass up on his turn. A player can move any one
of his pieces to the next unoccupied slot to its right or left, which
may involve jumping over occupied slots. A player cannot move a piece
off the side of the board.
.PP
* If a move creates a pattern where the opponent's pieces are
surrounded, on both sides, by two pieces of the mover's color (with no
intervening unoccupied blank slot), then those surrounded pieces are
removed from the board.
.PP
* The goal of the game is to remove all of your opponent's pieces, at
which point the game ends. Removing all-but-one ends the game as
well, since the opponent can't surround you with one piece, and so will
always lose within a few moves anyway.
.PP
Consider, then, this rather short game where X starts:
.PP
.Vb 10
\& xxxx_\|_\|_oooo
\& ^ Move 1: X moves from 3 (shown with caret) to 5
\& (Note that any of X\*(Aqs pieces could move, but
\& that the only place they could move to is 5.)
\& xx_xx_\|_oooo
\& ^ Move 2: O moves from 9 to 7.
\& xx_xx_oo_oo
\& ^ Move 3: X moves from 4 to 6.
\& xx_\|_xxoo_oo
\& ^ Move 4: O (stupidly) moves from 10 to 9.
\& xx_\|_xxooo_o
\& ^ Move 5: X moves from 5 to 10, making the board
\& "xx_\|_\|_xoooxo". The three o\*(Aqs that X just
\& surrounded are removed.
\& xx_\|_\|_x_\|_\|_xo
\& O has only one piece, so has lost.
.Ve
.PP
Now, move 4 could have gone quite the other way:
.PP
.Vb 11
\& xx_\|_xxoo_oo
\& Move 4: O moves from 8 to 4, making the board
\& "xx_oxxo_\|_oo". The surrounded x\*(Aqs are removed.
\& xx_o_\|_o_\|_oo
\& ^ Move 5: X moves from 1 to 2.
\& _xxo_\|_o_\|_oo
\& ^ Move 6: O moves from 7 to 6.
\& _xxo_o_\|_\|_oo
\& ^ Move 7: X moves from 2 to 5, removing the o at 4.
\& _\|_x_xo_\|_\|_oo
\& ...and so on.
.Ve
.PP
To teach a computer program to play Alak (as player X, say), it needs to
be able to look at the configuration of the board, figure out what moves
it can make, and weigh the benefit or costs, immediate or eventual, of
those moves.
.PP
So consider the board from just before move 3, and figure all the possible
moves X could make. X has pieces in slots 1, 2, 4, and 5. The leftmost
two x's (at 1 and 2) are up against the end of the board, so they
can move only right. The other two x's (at 4 and 5) can move either
right or left:
.PP
.Vb 7
\& Starting board: xx_xx_oo_oo
\& moving 1 to 3 gives _xxxx_oo_oo
\& moving 2 to 3 gives x_xxx_oo_oo
\& moving 4 to 3 gives xxx_x_oo_oo
\& moving 5 to 3 gives xxxx_\|_oo_oo
\& moving 4 to 6 gives xx_\|_xxoo_oo
\& moving 5 to 6 gives xx_x_xoo_oo
.Ve
.PP
For the computer to decide which of these is the best move to make, it
needs to quantify the benefit of these moves as a number \*(-- call that
the \*(L"payoff\*(R". The payoff of a move can be figured as just the number
of x pieces removed by the most recent move, minus the number of o
pieces removed by the most recent move. (It so happens that the rules
of the game mean that no move can delete both o's and x's, but the
formula still applies.) Since none of these moves removed any pieces,
all these moves have the same immediate payoff: 0.
.PP
Now, we could race ahead and write an Alak-playing program that could
use the immediate payoff to decide which is the best move to make.
And when there's more than one best move (as here, where all the moves
are equally good), it could choose randomly between the good
alternatives. This strategy is simple to implement; but it makes for a
very dumb program. Consider what O's response to each of the potential
moves (above) could be. Nothing immediately suggests itself for the
first four possibilities (X having moved something to position 3), but
either of the last two (illustrated below) are pretty perilous,
because in either case O has the obvious option (which he would be
foolish to pass up) of removing x's from the board:
.PP
.Vb 6
\& xx_xx_oo_oo
\& ^ X moves 4 to 6.
\& xx_\|_xxoo_oo
\& ^ O moves 8 to 4, giving "xx_oxxo_\|_oo". The two
\& surrounded x\*(Aqs are removed.
\& xx_o_\|_o_\|_oo
.Ve
.PP
or
.PP
.Vb 6
\& xx_xx_oo_oo
\& ^ X moves 5 to 6.
\& xx_x_xoo_oo
\& ^ O moves 8 to 5, giving "xx_xoxo_\|_oo". The one
\& surrounded x is removed.
\& xx_xo_o_\|_oo
.Ve
.PP
Both contingencies are quite bad for X \*(-- but this is not captured
by the fact that they start out with X thinking his move will be
harmless, having a payoff of zero.
.PP
So what's needed is for X to think \fImore\fR than one step ahead \*(-- to
consider not merely what it can do in this move, and what the payoff
is, but to consider what O might do in response, and the
payoff of those potential moves, and so on with X's possible responses
to those cases could be. All these possibilities form a game tree \*(-- a
tree where each node is a board, and its children are successors of
that node \*(-- i.e., the boards that could result from every move
possible, given the parent's board.
.PP
But how to represent the tree, and how to represent the nodes?
.PP
Well, consider that a node holds several pieces of data:
.PP
1) the configuration of the board, which, being nice and simple and
one-dimensional, can be stored as just a string, like \*(L"xx_xx_oo_oo\*(R".
.PP
2) whose turn it is, X or O. (Or: who moved last, from which we can
figure whose turn it is).
.PP
3) the successors (child nodes).
.PP
4) the immediate payoff of having moved to this board position from its
predecessor (parent node).
.PP
5) and what move gets us from our predecessor node to here. (Granted,
knowing the board configuration before and after the move, it's easy to
figure out the move; but it's easier still to store it as one is
figuring out a node's successors.)
.PP
6) whatever else we might want to add later.
.PP
These could be stored equally well in an array or in a hash, but it's my
experience that hashes are best for cases where you have more than just
two or three bits of data, or especially when you might need to add new
bits of data. Moreover, hash key names are mnemonic \*(--
\&\f(CW$node\fR\->{'last_move_payoff'} is plain as day, whereas it's not so easy having to
remember with an array that \f(CW$node\fR\->[3] is where you decided to keep the
payoff.
.Sp
.RS 4
Footnote:
Of course, there are ways around that problem: just swear you'll never
use a real numeric index to access data in the array, and instead use
constants with mnemonic names:
.Sp
.Vb 4
\& use strict;
\& use constant idx_PAYOFF => 3;
\& ...
\& $n\->[idx_PAYOFF]
.Ve
.Sp
Or use a pseudohash. But I prefer to keep it simple, and use a hash.
.Sp
These are, incidentally, the same arguments that
people weigh when trying to decide whether their object-oriented
modules should be based on blessed hashes, blessed arrays, or what.
Essentially the only difference here is that we're not blessing our
nodes or talking in terms of classes and methods.
.Sp
[end footnote]
.RE
.PP
So, we might as well represent nodes like so:
.PP
.Vb 2
\& $node = { # hashref
\& \*(Aqboard\*(Aq => ...board string, e.g., "xx_x_xoo_oo"
\&
\& \*(Aqlast_move_payoff\*(Aq => ...payoff of the move
\& that got us here.
\&
\& \*(Aqlast_move_from\*(Aq => ...the start...
\& \*(Aqlast_move_to\*(Aq => ...and end point of the move
\& that got us here. E.g., 5 and 6,
\& representing a move from 5 to 6.
\&
\& \*(Aqwhose_turn\*(Aq => ...whose move it then becomes.
\& just an \*(Aqx\*(Aq or \*(Aqo\*(Aq.
\&
\& \*(Aqsuccessors\*(Aq => ...the successors
\& };
.Ve
.PP
Note that we could have a field called something like 'last_move_who' to
denote who last moved, but since turns in Alak always alternate (and
no-one can pass), storing whose move it is now \fIand\fR who last moved is
redundant \*(-- if X last moved, it's O turn now, and vice versa.
I chose to have a 'whose_turn' field instead of a 'last_move_who', but
it doesn't really matter. Either way, we'll end up inferring one from
the other at several points in the program.
.PP
When we want to store the successors of a node, should we use an array
or a hash? On the one hand, the successors to \f(CW$node\fR aren't essentially
ordered, so there's no reason to use an array per se; on the other hand,
if we used a hash, with successor nodes as values, we don't have
anything particularly meaningful to use as keys. (And we can't use the
successors themselves as keys, since the nodes are referred to by
hash references, and you can't use a reference as a hash key.) Given no
particularly compelling reason to do otherwise, I choose to just use an
array to store all a node's successors, although the order is never
actually used for anything:
.PP
.Vb 5
\& $node = {
\& ...
\& \*(Aqsuccessors\*(Aq => [ ...nodes... ],
\& ...
\& };
.Ve
.PP
In any case, now that we've settled on what should be in a node,
let's make a little sample tree out of a few nodes and see what we can
do with it:
.PP
.Vb 9
\& # Board just before move 3 in above game
\& my $n0 = {
\& \*(Aqboard\*(Aq => \*(Aqxx_xx_oo_oo\*(Aq,
\& \*(Aqlast_move_payoff\*(Aq => 0,
\& \*(Aqlast_move_from\*(Aq => 9,
\& \*(Aqlast_move_to\*(Aq => 7,
\& \*(Aqwhose_turn\*(Aq => \*(Aqx\*(Aq,
\& \*(Aqsuccessors\*(Aq => [],
\& };
\&
\& # And, for now, just two of the successors:
\&
\& # X moves 4 to 6, giving xx_\|_xxoo_oo
\& my $n1 = {
\& \*(Aqboard\*(Aq => \*(Aqxx_\|_xxoo_oo\*(Aq,
\& \*(Aqlast_move_payoff\*(Aq => 0,
\& \*(Aqlast_move_from\*(Aq => 4,
\& \*(Aqlast_move_to\*(Aq => 6,
\& \*(Aqwhose_turn\*(Aq => \*(Aqo\*(Aq,
\& \*(Aqsuccessors\*(Aq => [],
\& };
\&
\& # or X moves 5 to 6, giving xx_x_xoo_oo
\& my $n2 = {
\& \*(Aqboard\*(Aq => \*(Aqxx_x_xoo_oo\*(Aq,
\& \*(Aqlast_move_payoff\*(Aq => 0,
\& \*(Aqlast_move_from\*(Aq => 5,
\& \*(Aqlast_move_to\*(Aq => 6,
\& \*(Aqwhose_turn\*(Aq => \*(Aqo\*(Aq,
\& \*(Aqsuccessors\*(Aq => [],
\& };
\&
\& # Now connect them...
\& push @{$n0\->{\*(Aqsuccessors\*(Aq}}, $n1, $n2;
.Ve
.SS "Digression: Links to Parents"
.IX Subsection "Digression: Links to Parents"
In comparing what we store in an Alak game tree node to what
HTML::Element stores in \s-1HTML\s0 element nodes, you'll note one big
difference: every HTML::Element node contains a link to its parent,
whereas we don't have our Alak nodes keeping a link to theirs.
.PP
The reason this can be an important difference is because it can affect
how Perl knows when you're not using pieces of memory anymore.
Consider the tree we just built, above:
.PP
.Vb 3
\& node 0
\& / \e
\& node 1 node 2
.Ve
.PP
There's two ways Perl knows you're using a piece of memory:
1) it's memory that belongs directly to a variable (i.e., is necessary
to hold that variable's value, or value\fIs\fR in the case of a hash or
array), or 2) it's a piece of memory that something holds a reference
to. In the above code, Perl knows that the hash for node 0 (for board
\&\*(L"xx_xx_oo_oo\*(R") is in use because something (namely, the variable
\&\f(CW$n0\fR) holds a reference to it. Now, even if you followed the above
code with this:
.PP
.Vb 1
\& $n1 = $n2 = \*(Aqwhatever\*(Aq;
.Ve
.PP
to make your variables \f(CW$n1\fR and \f(CW$n2\fR stop holding references to
the hashes for the two successors of node 0, Perl would still know that
those hashes are still in use, because node 0's successors array holds
a reference to those hashes. And Perl knows that node 0 is still in
use because something still holds a reference to it. Now, if you
added:
.PP
.Vb 1
\& my $root = $n0;
.Ve
.PP
This would change nothing \*(-- there's just be \fItwo\fR things holding a
reference to the node 0 hash, which in turn holds a reference to the
node 1 and node 2 hashes. And if you then added:
.PP
.Vb 1
\& $n0 = \*(Aqstuff\*(Aq;
.Ve
.PP
still nothing would change, because something (\f(CW$root\fR) still holds a
reference to the node 0 hash. But once \fInothing\fR holds a reference to
the node 0 hash, Perl will know it can destroy that hash (and reclaim
the memory for later use, say), and once it does that, nothing will hold
a reference to the node 1 or the node 2 hashes, and those will be
destroyed too.
.PP
But consider if the node 1 and node 2 hashes each had an attribute
\&\*(L"parent\*(R" (or \*(L"predecessor\*(R") that held a reference to node 0. If your
program stopped holding a reference to the node 0 hash, Perl could
\&\fInot\fR then say that \fInothing\fR holds a reference to node 0 \*(-- because
node 1 and node 2 still do. So, the memory for nodes 0, 1, and 2 would
never get reclaimed (until your program ended, at which point Perl
destroys \fIeverything\fR). If your program grew and discarded lots of
nodes in the game tree, but didn't let Perl know it could reclaim their
memory, your program could grow to use immense amounts of memory \*(--
never a nice thing to have happen. There's three ways around this:
.PP
1) When you're finished with a node, delete the reference each of its
children have to it (in this case, deleting \f(CW$n1\fR\->{'parent'}, say).
When you're finished with a whole tree, just go through the whole tree
erasing links that children have to their children.
.PP
2) Reconsider whether you really need to have each node hold a reference
to its parent. Just not having those links will avoid the whole
problem.
.PP
3) use the WeakRef module with Perl 5.6 or later. This allows you to
\&\*(L"weaken\*(R" some references (like the references that node 1 and 2 could
hold to their parent) so that they don't count when Perl goes asking
whether anything holds a reference to a given piece of memory. This
wonderful new module eliminates the headaches that can often crop up
with either of the two previous methods.
.PP
It so happens that our Alak program is simple enough that we don't need
for our nodes to have links to their parents, so the second solution is
fine. But in a more advanced program, the first or third solutions
might be unavoidable.
.SS "Recursively Printing the Tree"
.IX Subsection "Recursively Printing the Tree"
I don't like working blind \*(-- if I have any kind of a complex data
structure in memory for a program I'm working on, the first thing I do
is write something that can dump that structure to the screen so I can
make sure that what I \fIthink\fR is in memory really \fIis\fR what's in
memory. Now, I could just use the \*(L"x\*(R" pretty-printer command in Perl's
interactive debugger, or I could have the program use the
\&\f(CW\*(C`Data::Dumper\*(C'\fR module. But in this case, I think the output from those
is rather too verbose. Once we have trees with dozens of nodes in them,
we'll really want a dump of the tree to be as concise as possible,
hopefully just one line per node. What I'd like is something that can
print \f(CW$n0\fR and its successors (see above) as something like:
.PP
.Vb 3
\& xx_xx_oo_oo (O moved 9 to 7, 0 payoff)
\& xx_\|_xxoo_oo (X moved 4 to 6, 0 payoff)
\& xx_x_xoo_oo (X moved 5 to 6, 0 payoff)
.Ve
.PP
A subroutine to print a line for a given node, and then do that again for
each successor, would look something like:
.PP
.Vb 9
\& sub dump_tree {
\& my $n = $_[0]; # "n" is for node
\& print
\& ...something expressing $n\*(Aqn content...
\& foreach my $s (@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& # "s for successor
\& dump($s);
\& }
\& }
.Ve
.PP
And we could just start that out with a call to \f(CW\*(C`dump_tree($n0)\*(C'\fR.
.PP
Since this routine...
.Sp
.RS 4
Footnote:
I first wrote this routine starting out with \*(L"sub dump {\*(R". But when
I tried actually calling \f(CW\*(C`dump($n0)\*(C'\fR, Perl would dump core! Imagine
my shock when I discovered that this is absolutely to be expected \*(--
Perl provides a built-in function called \f(CW\*(C`dump\*(C'\fR, the purpose of which
is to, yes, make Perl dump core. Calling our routine \*(L"dump_tree\*(R"
instead of \*(L"dump\*(R" neatly avoids that problem.
.RE
.PP
\&...does its work (dumping the subtree at and under the
given node) by calling itself, it's \fBrecursive\fR. However, there's a
special term for this kind of recursion across a tree: traversal. To
\&\fBtraverse\fR a tree means to do something to a node, and to traverse its
children. There's two prototypical ways to do this, depending on what
happens when:
.PP
.Vb 3
\& traversing X in pre\-order:
\& * do something to X
\& * then traverse X\*(Aqs children
\&
\& traversing X in post\-order:
\& * traverse X\*(Aqs children
\& * then do something to X
.Ve
.PP
Dumping the tree to the screen the way we want it happens to be a matter
of pre-order traversal, since the thing we do (print a description of
the node) happens before we recurse into the successors.
.PP
When we try writing the \f(CW\*(C`print\*(C'\fR statement for our above \f(CW\*(C`dump_tree\*(C'\fR,
we can get something like:
.PP
.Vb 2
\& sub dump_tree {
\& my $n = $_[0];
\&
\& # "xx_xx_oo_oo (O moved 9 to 7, 0 payoff)"
\& print
\& $n\->{\*(Aqboard\*(Aq}, " (",
\& ($n\->{\*(Aqwhose_turn\*(Aq} eq \*(Aqo\*(Aq ? \*(AqX\*(Aq : \*(AqO\*(Aq),
\& # Infer who last moved from whose turn it is now.
\& " moved ", $n\->{\*(Aqlast_move_from\*(Aq},
\& " to ", $n\->{\*(Aqlast_move_to\*(Aq},
\& ", ", $n\->{\*(Aqlast_move_payoff\*(Aq},
\& " payoff)\en",
\& ;
\&
\& foreach my $s (@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& dump_tree($s);
\& }
\& }
.Ve
.PP
If we run this on \f(CW$n0\fR from above, we get this:
.PP
.Vb 3
\& xx_xx_oo_oo (O moved 9 to 7, 0 payoff)
\& xx_\|_xxoo_oo (X moved 4 to 6, 0 payoff)
\& xx_x_xoo_oo (X moved 5 to 6, 0 payoff)
.Ve
.PP
Each line on its own is fine, but we forget to allow for indenting, and
without that we can't tell what's a child of what. (Imagine if the
first successor had successors of its own \*(-- you wouldn't be able to
tell if it were a child, or a sibling.) To get indenting, we'll need
to have the instances of the \f(CW\*(C`dump_tree\*(C'\fR routine know how far down in
the tree they're being called, by passing a depth parameter between
them:
.PP
.Vb 11
\& sub dump_tree {
\& my $n = $_[0];
\& my $depth = $_[1];
\& $depth = 0 unless defined $depth;
\& print
\& " " x $depth,
\& ...stuff...
\& foreach my $s (@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& dump_tree($s, $depth + 1);
\& }
\& }
.Ve
.PP
When we call \f(CW\*(C`dump_tree($n0)\*(C'\fR, \f(CW$depth\fR (from \f(CW$_[1]\fR) is undefined, so
gets set to 0, which translates into an indenting of no spaces. But when
\&\f(CW\*(C`dump_tree\*(C'\fR invokes itself on \f(CW$n0\fR's children, those instances see
\&\f(CW$depth\fR + 1 as their \f(CW$_[1]\fR, giving appropriate indenting.
.Sp
.RS 4
Footnote:
Passing values around between different invocations of a recursive
routine, as shown, is a decent way to share the data. Another way
to share the data is by keeping it in a global variable, like \f(CW$Depth\fR,
initially set to 0. Each time \f(CW\*(C`dump_tree\*(C'\fR is about to recurse, it must
\&\f(CW\*(C`++$Depth\*(C'\fR, and when it's back, it must \f(CW\*(C`\-\-$Depth\*(C'\fR.
.Sp
Or, if the reader is familiar with closures, consider this approach:
.Sp
.Vb 10
\& sub dump_tree {
\& # A wrapper around calls to a recursive closure:
\& my $start_node = $_[0];
\& my $depth = 0;
\& # to be shared across calls to $recursor.
\& my $recursor;
\& $recursor = sub {
\& my $n = $_[0];
\& print " " x $depth,
\& ...stuff...
\& ++$depth;
\& foreach my $s (@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& $recursor\->($s);
\& }
\& \-\-$depth;
\& }
\& $recursor\->($start_node); # start recursing
\& undef $recursor;
\& }
.Ve
.Sp
The reader with an advanced understanding of Perl's reference-count-based
garbage collection is invited to consider why it is currently necessary
to undef \f(CW$recursor\fR (or otherwise change its value) after all recursion
is done.
.Sp
The reader whose mind is perverse in other ways is invited to consider
how (or when!) passing a depth parameter around is unnecessary because
of information that Perl's \f(CWcaller(N)\fR function reports!
.Sp
[end footnote]
.RE
.SS "Growing the Tree"
.IX Subsection "Growing the Tree"
Our \f(CW\*(C`dump_tree\*(C'\fR routine works fine for the sample tree we've got, so
now we should get the program working on making its own trees, starting
from a given board.
.PP
In \f(CW\*(C`Games::Alak\*(C'\fR (the CPAN-released version of Alak that uses
essentially the same code that we're currently discussing the
tree-related parts of), there is a routine called \f(CW\*(C`figure_successors\*(C'\fR
that, given one childless node, will figure out all its possible
successors. That is, it looks at the current board, looks at every piece
belonging to the player whose turn it is, and considers the effect of
moving each piece every possible way \*(-- notably, it figures out the
immediate payoff, and if that move would end the game, it notes that by
setting an \*(L"endgame\*(R" entry in that node's hash. (That way, we know that
that's a node that \fIcan't\fR have successors.)
.PP
In the code for \f(CW\*(C`Games::Alak\*(C'\fR, \f(CW\*(C`figure_successors\*(C'\fR does all these things,
in a rather straightforward way. I won't walk you through the details
of the \f(CW\*(C`figure_successors\*(C'\fR code I've written, since the code has
nothing much to do with trees, and is all just implementation of the Alak
rules for what can move where, with what result. Especially interested
readers can puzzle over that part of code in the source listing in the
archive from \s-1CPAN,\s0 but others can just assume that it works as described
above.
.PP
But consider that \f(CW\*(C`figure_successors\*(C'\fR, regardless of its inner
workings, does not grow the \fItree\fR; it only makes one set of successors
for one node at a time. It has to be up to a different routine to call
\&\f(CW\*(C`figure_successors\*(C'\fR, and to keep applying it as needed, in order to
make a nice big tree that our game-playing program can base its
decisions on.
.PP
Now, we could do this by just starting from one node, applying
\&\f(CW\*(C`figure_successors\*(C'\fR to it, then applying \f(CW\*(C`figure_successors\*(C'\fR on all
the resulting children, and so on:
.PP
.Vb 10
\& sub grow { # Just a first attempt at this!
\& my $n = $_[0];
\& figure_successors($n);
\& unless
\& @{$n\->{\*(Aqsuccessors\*(Aq}}
\& # already has successors.
\& or $n\->{\*(Aqendgame\*(Aq}
\& # can\*(Aqt have successors.
\& }
\& foreach my $s (@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& grow($s); # recurse
\& }
\& }
.Ve
.PP
If you have a game tree for tic-tac-toe, and you grow it without
limitation (as above), you will soon enough have a fully \*(L"solved\*(R" tree,
where every node that \fIcan\fR have successors \fIdoes\fR, and all the leaves
of the tree are \fIall\fR the possible endgames (where, in each case, the
board is filled). But a game of Alak is different from tic-tac-toe,
because it can, in theory, go on forever. For example, the following
sequence of moves is quite possible:
.PP
.Vb 6
\& xxxx_\|_\|_oooo
\& xxx_x_\|_oooo
\& xxx_x_o_ooo
\& xxxx_\|_o_ooo (x moved back)
\& xxxx_\|_\|_oooo (o moved back)
\& ...repeat forever...
.Ve
.PP
So if you tried using our above attempt at a \f(CW\*(C`grow\*(C'\fR routine, Perl would
happily start trying to construct an infinitely deep tree, containing
an infinite number of nodes, consuming an infinite amount of memory, and
requiring an infinite amount of time. As the old saying goes: \*(L"You
can't have everything \*(-- where would you put it?\*(R" So we have to place
limits on how much we'll grow the tree.
.PP
There's more than one way to do this:
.PP
1. We could grow the tree until we hit some limit on the number of
nodes we'll allow in the tree.
.PP
2. We could grow the tree until we hit some limit on the amount of time
we're willing to spend.
.PP
3. Or we could grow the tree until it is fully fleshed out to a certain
depth.
.PP
Since we already know to track depth (as we did in writing \f(CW\*(C`dump_tree\*(C'\fR),
we'll do it that way, the third way. The implementation for that third
approach is also pretty straightforward:
.PP
.Vb 10
\& $Max_depth = 3;
\& sub grow {
\& my $n = $_[0];
\& my $depth = $_[1] || 0;
\& figure_successors($n)
\& unless
\& $depth >= $Max_depth
\& or @{$n\->{\*(Aqsuccessors\*(Aq}}
\& or $n\->{\*(Aqendgame\*(Aq}
\& }
\& foreach my $s (@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& grow($s, $depth + 1);
\& }
\& # If we\*(Aqre at $Max_depth, then figure_successors
\& # didn\*(Aqt get called, so there\*(Aqs no successors
\& # to recurse under \-\- that\*(Aqs what stops recursion.
\& }
.Ve
.PP
If we start from a single node (whether it's a node for the starting board
\&\*(L"xxxx_\|_\|_oooo\*(R", or for whatever board the computer is faced with), set
\&\f(CW$Max_depth\fR to 4, and apply \f(CW\*(C`grow\*(C'\fR to it, it will grow the tree to
include several hundred nodes.
.Sp
.RS 4
Footnote:
If at each move there are four pieces that can move, and they can each
move right or left, the \*(L"branching factor\*(R" of the tree is eight, giving
a tree with 1 (depth 0) + 8 (depth 1) + 8 ** 2 + 8 ** 3 + 8 ** 4 =
4681 nodes in it. But, in practice, not all pieces can move in both
directions (none of the x pieces in \*(L"xxxx_\|_\|_oooo\*(R" can move left, for
example), and there may be fewer than four pieces, if some were lost.
For example, there are 801 nodes in a tree of depth four starting
from \*(L"xxxx_\|_\|_oooo\*(R", suggesting an average branching factor of about
five (801 ** (1/4) is about 5.3), not eight.
.RE
.PP
What we need to derive from that tree is the information about what
are the best moves for X. The simplest way to consider the payoff of
different successors is to just average them \*(-- but what we average
isn't always their immediate payoffs (because that'd leave us using
only one generation of information), but the average payoff of \fItheir\fR
successors, if any. We can formalize this as:
.PP
.Vb 6
\& To figure a node\*(Aqs average payoff:
\& If the node has successors:
\& Figure each successor\*(Aqs average payoff.
\& My average payoff is the average of theirs.
\& Otherwise:
\& My average payoff is my immediate payoff.
.Ve
.PP
Since this involves recursing into the successors \fIbefore\fR doing
anything with the current node, this will traverse the tree
\&\fIin post-order\fR.
.PP
We could work that up as a routine of its own, and apply that to the
tree after we've applied \f(CW\*(C`grow\*(C'\fR to it. But since we'd never
grow the tree without also figuring the average benefit, we might as well
make that figuring part of the \f(CW\*(C`grow\*(C'\fR routine itself:
.PP
.Vb 10
\& $Max_depth = 3;
\& sub grow {
\& my $n = $_[0];
\& my $depth = $_[1] || 0;
\& figure_successors($n);
\& unless
\& $depth >= $Max_depth
\& or @{$n\->{\*(Aqsuccessors\*(Aq}}
\& or $n\->{\*(Aqendgame\*(Aq}
\& }
\&
\& if(@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& my $a_payoff_sum = 0;
\& foreach my $s (@{$n\->{\*(Aqsuccessors\*(Aq}}) {
\& grow($s, $depth + 1); # RECURSE
\& $a_payoff_sum += $s\->{\*(Aqaverage_payoff\*(Aq};
\& }
\& $n\->{\*(Aqaverage_payoff\*(Aq}
\& = $a_payoff_sum / @{$n\->{\*(Aqsuccessors\*(Aq}};
\& } else {
\& $n\->{\*(Aqaverage_payoff\*(Aq}
\& = $n\->{\*(Aqlast_move_payoff\*(Aq};
\& }
\& }
.Ve
.PP
So, by time \f(CW\*(C`grow\*(C'\fR has applied to a node (wherever in the tree it is),
it will have figured successors if possible (which, in turn, sets
\&\f(CW\*(C`last_move_payoff\*(C'\fR for each node it creates), and will have set
\&\f(CW\*(C`average_benefit\*(C'\fR.
.PP
Beyond this, all that's needed is to start the board out with a root
note of \*(L"xxxx_\|_\|_oooo\*(R", and have the computer (X) take turns with the
user (O) until someone wins. Whenever it's O's turn, \f(CW\*(C`Games::Alak\*(C'\fR
presents a prompt to the user, letting him know the state of the current
board, and asking what move he selects. When it's X's turn, the
computer grows the game tree as necessary (using just the \f(CW\*(C`grow\*(C'\fR
routine from above), then selects the move with the highest average
payoff (or one of the highest, in case of a tie).
.PP
In either case, \*(L"selecting\*(R" a move means just setting that move's node
as the new root of the program's game tree. Its sibling nodes and their
descendants (the boards that \fIdidn't\fR get selected) and its parent node
will be erased from memory, since they will no longer be in use (as Perl
can tell by the fact that nothing holds references to them anymore).
.PP
The interface code in \f(CW\*(C`Games::Alak\*(C'\fR (the code that prompts the user for
his move) actually supports quite a few options besides just moving \*(--
including dumping the game tree to a specified depth (using a slightly
fancier version of \f(CW\*(C`dump_tree\*(C'\fR, above), resetting the game, changing
\&\f(CW$Max_depth\fR in the middle of the game, and quitting the game. Like
\&\f(CW\*(C`figure_successors\*(C'\fR, it's a bit too long to print here, but interested
users are welcome to peruse (and freely modify) the code, as well as to
enjoy just playing the game.
.PP
Now, in practice, there's more to game trees than this: for games with a
larger branching factor than Alak has (which is most!), game trees of
depth four or larger would contain too many nodes to be manageable, most
of those nodes being strategically quite uninteresting for either
player; dealing with game trees specifically is therefore a matter of
recognizing uninteresting contingencies and not bothering to grow the
tree under them.
.Sp
.RS 4
Footnote:
For example, to choose a straightforward case: if O has a choice between
moves that put him in immediate danger of X winning and moves that
don't, then O won't ever choose the dangerous moves (and if he does, the
computer will know enough to end the game), so there's no point in
growing the tree any further beneath those nodes.
.RE
.PP
But this sample implementation should illustrate the basics of
how to build and manipulate a simple tree structure in memory.
And once you've understood the basics of tree storage here, you should
be ready to better understand the complexities and peculiarities of
other systems for creating, accessing, and changing trees, including
Tree::DAG_Node, HTML::Element, \s-1XML::DOM,\s0 or related formalisms
like XPath and \s-1XSL.\s0
.PP
\&\fB[end body of article]\fR
.SS "[Author Credit]"
.IX Subsection "[Author Credit]"
Sean M. Burke (\f(CW\*(C`sburke@cpan.org\*(C'\fR) is a tree-dwelling hominid.
.SS "References"
.IX Subsection "References"
Dewdney, A[lexander] K[eewatin]. 1984. \fIPlaniverse: Computer Contact
with a Two-Dimensional World.\fR Poseidon Press, New York.
.PP
Knuth, Donald Ervin. 1997. \fIArt of Computer Programming, Volume 1,
Third Edition: Fundamental Algorithms\fR. Addison-Wesley, Reading, \s-1MA.\s0
.PP
Wirth, Niklaus. 1976. \fIAlgorithms + Data Structures = Programs\fR
Prentice-Hall, Englewood Cliffs, \s-1NJ.\s0
.PP
Worth, Stan and Allman Sheldon. Circa 1967. \fIGeorge of the Jungle\fR
theme. [music by Jay Ward.]
.PP
Wirth's classic, currently and lamentably out of print, has a good
section on trees. I find it clearer than Knuth's (if not quite as
encyclopedic), probably because Wirth's example code is in a
block-structured high-level language (basically Pascal), instead
of in assembler (\s-1MIX\s0). I believe the book was re-issued in the
1980s under the titles \fIAlgorithms and Data Structures\fR and, in a
German edition, \fIAlgorithmen und Datenstrukturen\fR. Cheap copies
of these editions should be available through used book services
such as \f(CW\*(C`abebooks.com\*(C'\fR.
.PP
Worth's classic, however, is available on the
soundtrack to the 1997 \fIGeorge of the Jungle\fR movie, as
performed by The Presidents of the United States of America.
.SH "BACK"
.IX Header "BACK"
Return to the HTML::Tree docs.