Java Reference
In-Depth Information
So what's the difference between update and fupdate? We noted previously that the method
update assumes every user wants to share the identical data structure and see updates caused by
any part of the program. Hence it's vital (but often overlooked) in nonfunctional code that
whenever you add some form of structured value to a tree, you copy it, because, who knows,
someone may later assume they can update it. By contrast, fupdate is purely functional. It
creates a new Tree as a result but sharing as much as it can with its argument . Figure 14.4
illustrates this idea. You have a tree consisting of nodes storing a name and an age of a person.
Calling fupdate doesn't modify the existing tree but creates new nodes “living at the side of” the
tree without harming the existing data structure.
Figure 14.4. No existing data structure was harmed during the making
of this update to the Tree .
Such functional data structures are often called persistent —their values persist and are isolated
from changes happening elsewhere—so as a programmer you're sure fupdate won't mutate the
data structures passed as its arguments. There's just one proviso: the other side of the treaty is
you require all users of persistent data structures to follow the do-not-mutate requirement . If
not, a programmer who disregards this might mutate the result of fupdate (for example,
changing Emily's 20). This would then be visible as an (almost certainly unwanted) unexpected
and delayed change to the data structure passed as argument to fupdate!
Seen in these terms, fupdate can often be more efficient: the “no mutation of existing structure”
rule allows structures that differ only slightly from each other (for example, the Tree seen by
user A and the modified version seen by user B) to share storage for common parts of their
 
Search WWH ::




Custom Search