The Problem
In one of my Tcl programming projects, I needed to keep track of a list of child process IDs: When I spawn a new process, I added that process’s ID to a list. When the process finished, I removed its ID from the list.
The Initial Solution
Due to the way I phrased my problem, I naturally chose to use Tcl’s list to keep track of the IDs. Thus, to add an ID to the list, I used the following command:
lappend idList $id
That was easy enough. However, removing and ID from the list requires more works because Tcl does not have an remove command. I ended up with something like this:
set index [lsearch -exact $idList $id]
if {$index != -1} {
set idList [lreplace $idList $index $index]
}
Months after I wrote that code, I looked back at my work and did not like it a bit. The code was hard to understand and error prone. There must be a better way.
The Second Solution
While browing the help file for Tcllib, I stumbled upon a package called struct::set and inspiration struck me. Yes, instead of using a list to keep track of my IDs, I could use a set data structure to greatly simplify my task. To add an ID to the “list”, I would issue the following command:
struct::set include idList $id
Likewise, to remove an ID from the list, I would issue the following command:
struct::set exclude idList $id
That was much better. By using the right data type, not only I simplified my tasks, enhanced readability, but also reduced chance of making error. It is time to go back to school and learn about data structure!
Posted on August 7, 2009
0