Given a string containing brackets []
, braces {}
, parentheses ()
, or any combination thereof, verify that any and all pairs are matched and nested correctly.
The string may also contain other characters, which for the purposes of this exercise should be ignored.
Tcl is a very simple language, but the way they interpreter parses code has a couple of nasty edge cases.
Braces in Tcl are simply a way to quote a block of text -- that text may be interpreted as code or data. Within braces, nested braces may appear but the nested braces must be balanced. The Tcl man page says this:
Braces nest within the word: for each additional open brace there must be an additional close brace (however, if an open brace or close brace within the word is quoted with a backslash then it is not counted in locating the matching close brace).
The wording there is quite specific: if you want to have an unmatched open or close brace character, it must be quoted with a backslash. So don't do this:
proc isOpenBrace {char} {
return [expr {$char eq "{"}]
# ......................^ will not work
}
You must do this
proc isOpenBrace {char} {
return [expr {$char eq "\{"}]
# ......................^^ will work
}
This can be problematic with the way Tcl parses comments, which is different from most languages. There is more discussion on the Tcl wiki.
Similarly, since Tcl uses brackets for Command substitution., even within double quoted strings, you have to be careful about escaping open brackets.
With the exception of associative array variables, parentheses are simply ordinary characters.
Sign up to Exercism to learn and master Tcl with 124 exercises, and real human mentoring, all for free.