## Tcl Learning Exercises: Answer: Number Sign Class

Tcl Learning Exercises: Answer: Number Sign Class

## Description

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.

`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.

RKZn 2017-05-27: Actually there is a subtle difference in the two procs. The return value of first one (with the ?: operator) is represented as an integer or a double, depending on the input's representation. The second proc always returns a integer representation.

```tcl> info patch
8.6.1
tcl> proc numsign n {expr {\$n == 0 ? 0 : \$n/abs(\$n)}}
tcl> tcl::unsupported::representation [numsign -5]
value is a int with a refcount of 1, object pointer at 0xb507f0, internal representation 0xffffffffffffffff:0xb53250, no string representation
tcl> tcl::unsupported::representation [numsign -5.5]
value is a double with a refcount of 1, object pointer at 0x91a210, internal representation 0xbff0000000000000:0xb50ee0, no string representation
tcl> proc numsign n {expr {(\$n > 0) - (\$n < 0)}}
tcl> tcl::unsupported::representation [numsign -5]
value is a int with a refcount of 1, object pointer at 0x919c40, internal representation 0xffffffffffffffff:0xb50880, no string representation
tcl> tcl::unsupported::representation [numsign -5.5]
value is a int with a refcount of 1, object pointer at 0xb50ee0, internal representation 0xffffffffffffffff:0xb53130, no string representation```

Other ways to do it from my own post on Code Golf - Output the sign :

`puts [expr \$n<0?-1:\$n>0]`
`puts [expr !!\$n|\$n>>31]`