Version 6 of The infinity trick

Updated 2005-02-04 16:16:02

It is common in programming that one sometimes wants to say "infinity", or at least "a number larger than any given number". The ordinary way to do that is to pick a fixed but very large number (e.g. the largest representable number) or to use an unreasonable number (e.g. -1 items) and add extra logic for handling it, but in Tcl there is a better way, thanks to that everything is a string: just say "infinity"!

Take for example conditions such as this

  if {$someQuantity >= $limit} then {
      # Do some kind of flush
  }

that aren't too uncommon in programs. Suppose you don't want any such flushes to happen at all. How to do that? It turns out you can do

  set limit infinity

This will not error out, as one might perhaps expect, since comparisons are string comparisons if not both operands are numbers;

 % expr {1 <= "infinity"}
 1
 % expr {2 < "infinity"}
 1
 % expr {2 > "infinity"}
 0
 % expr {"infinity" > "infinity"}
 0
 % expr {-3000 < "infinity"}
 1

A more complete example:

  proc record_work {items} {
      variable items_total
      incr items_total $items
      # Perhaps write a log message about this.
      set now [clock seconds]
      variable last_message_seconds
      variable period
      if {$now - $last_message_seconds >= $period} then {
          puts [format "At %s there is a total of %d items."\
            [clock format $now] $items_total]
          set last_message_seconds $now
      }
  }

  proc init_work_record {report_period} {
      variable items_total 0\
        last_message_seconds [clock seconds]\
        period $report_period
  }

With these procs,

  init_work_record 60

will generate a report about once a minute and

  init_work_record 3600

will generate a report about once an hour, but

  init_work_record infinity

will effectively turn reporting off completely.

It is normally not possible to do arithmetic with infinity (although on some platforms it can get parsed as some kind of double), so one has to execute some care in how it is used, but very often arithmetic with a number won't be needed until one has exceeded it.

-- Lars H

AM What a cute little trick! It even works for numbers like .1


I think most programmers if they needed some function to run forever they would script something like this instead:

 while {true} {#Do Something}

The endless while loop is very common in C programs and is easier to read then the forever for loop.

Lars H: Yeah, it was a poor example (although not entirely unlike what one might encounter). I've replaced it with something better.


Category Mathematics - Category Concept - Category Example