Updated 2015-12-06 16:52:49 by pooryorick

A short question in comp.lang.tcl got me several useful answers that I'm now putting here for later reference:

The (generalized) question:

  • How do I embed comments into an expr (or the first argument to if,while)

The specific context:

  • an expression was structured as an "&&"ed sequence of separate conditions, each of which should be associated with a simple text (e.g. someone's name).
  • It was considered a valid assumption, that the comment text does not contain "nasty characters".
  • Readability weighs more than performance.

The answers:

my own: (provided in the posting as an example of what I meant)

  • use a proc that always returns true, and ignores its arguments:
proc noop args {return 1}
if {   <cond1>  && [noop  John Doe  ]
    && <cond2>  && [noop  Fu  Bar   ]
    ...
} { do something ... }

by Roy Terry:

  • use a proc that expr-evaluates its first argument and ignores the rest.
proc ? {cond args} { return [uplevel expr $cond]}
if { [? {<cond1>}  John Doe ]
    && [? {<cond2>}  Fu   Bar ]
    ...
} ...

A previous simpler version returned the first argument directly (without uplevel&expr), to which RS added: Note that this is another use for the K combinator...

  • use Tmac, which allows embedding comments everywhere: [1]
   if { cond1 (* John Doe *)
      && cond2 (*  Fu   Bar *)
      ...
   } ...

by Ulrich Schoebel

  • build up the expression condition by condition:
set cond [list]
lappend cond $cond1 ;# John Doe                                                 
lappend cond $cond2 ;# Fu Bar                                                   
...
if {[expr [join $cond &&]]} { ...                                                                             

by Michael Barth (per email):

  • make use of short-cut boolean evaluation. (slightly simplified)
if {  <cond1>  && (1 || " John Doe ")
   && <cond2>  && (1 || " Fu  Bar  ")
   ...
} { do something ... }

This is conceptually similar to my own solution, but better insofar, as no special procedure is needed and the "comment-ness" is immediately visible.

Andreas Leitgeb: Thanks for all the hints!