Updated 2015-03-27 07:05:02 by AMG

Tcl Learning Exercises: Answer: Number Sign Class

Description  edit

Write a procedure that takes one argument, a number, and returns -1, 0, or 1, indicating that the number is negative, zero, or positive, respectively. The procedure may contain exactly one command, expr, which may use the if-then-else (?...:) operator at most one time. Bonus Round: Add an additional constraint: The if-then-else operator may not be used.

Here is one answer:
proc numsign n {expr {$n == 0 ? 0 : $n/abs($n)}}

Scroll down for the bonus round answer...

Here is a solution by rmax to the bonus round:
proc numsign n {expr {($n > 0) - ($n < 0)}}

AMG: While this may be an interesting beginner problem, I don't think it succeeds in demonstrating anything special about Tcl other than that math must be done using [expr]. Text manipulation problems will likely do better to motivate interest in Tcl.