Version 1 of If we had no expr

Updated 2003-12-27 13:49:00

In the spirit of If we had no if, I wondered what would happen if there was no expr (it's certainly one of the more awkward Tcl commands). There are probably plenty of alternative ways to achieve the necessary functionality. -- Lars H


Natural number arithmetic via unary representation

In unary representation of natural number, one simply writes as many digits as the number one wants to represent. string length sort of converts unary to decimal, and string repeat can be used to convert decimal to unary. That way, one can do things such as the following.

 proc plus {a b} {
    string length "[string repeat 1 $a][string repeat 1 $b]"
 }

As expected, we get

 % plus 2 2
 4
 % plus 2 3
 5

Negative input seems to be accepted, but is then treated as zero.

 % plus -2 2
 2

In a similar vein, one can define

 proc minus {a b} {
    string length [string range [string repeat 1 $a] $b end]
 }
 proc times {a b} {
    string length [string repeat [string repeat 1 $a] $b]
 }
 proc div {a b} {
    string length [string map [
        list [string repeat 1 $b] N 1 {}
    ] [string repeat 1 $a]]
 }
 proc mod {a b} {
    string length [string map [
        list [string repeat 1 $b] {}
    ] [string repeat 1 $a]]
 }

From these one gets for example

 % minus 10 4
 6
 % minus 4 10
 0
 % times 6 7
 42
 % div 10 4
 2
 % mod 7 2
 1
 % mod 7 0
 7
 % div 7 0
 0

some of which are unusual, still (kind of) make sense.


Other approaches ...

[ Arts and crafts of Tcl-Tk programming - ]