Version 0 of command prefix

Updated 2008-09-16 09:11:43 by lars_h

A command prefix is a prefix of a command (in the sense of rule 2 of the dodekalogue, i.e., a sequence of words) that is constructed with the expectation that zero or more arguments will be appended to it and that the resulting command will be evaluated. This is very often done repeatedly, with the arguments completing the command being different for each evaluation.

The classical (although not very efficient) example of this is the -command option of lsort, which takes a command prefix as argument. This command prefix is supposed to take two arguments and compare them according to some custom order, returning -1, 0, or 1 according to how the comparison came out. The equally classical example of such a command option is string compare, so one can say

 lsort -command {string compare} {a B c D 0}

which however is just the same as lsort {a B c D 0}. A more interesting choice is package vcompare, which compares version numbers:

 % lsort -command {package vcompare} {2.0.1 3 1.10 1.9 2a0}
 1.9 1.10 2a0 2.0.1 3

The -dictionary option of lsort is rather close, but it wouldn't get the alpha and beta versions right:

 % lsort -dictionary {2.0.1 3 1.10 1.9 2a0}
 1.9 1.10 2.0.1 2a0 3

In order to see (at least some of) how the sorting gets done, we can define a procedure that calls some other command prefix to do the actual sorting, writes the result to stdout, and then returns it:

 proc showsort {prefix a b} {
    set res [{*}$prefix $a $b]
    puts "$a [expr {$res<0 ? "<" : $res>0 ? ">" : "="}] $b"
    return $res
 }

For example,

 % lsort -command {showsort {string compare}} {a B c D 0}
 a > B
 c > D
 B < D
 a > D
 a < c
 B > 0
 0 B D a c
 % lsort -command {showsort {package vcompare}} {2.0.1 3 1.10 1.9 2a0}
 2.0.1 < 3
 1.10 > 1.9
 2.0.1 > 1.9
 2.0.1 > 1.10
 1.9 < 2a0
 1.10 < 2a0
 2.0.1 > 2a0
 1.9 1.10 2a0 2.0.1 3

This particular technique — to let one or more of the words in a command prefix themselves be command prefixes that handle some subtask — can become very powerful if you have several command prefixes that do related things, much for the same reasons as pipelines make the Unix command-line powerful.

Command prefixes in comparison

[Compare to scripts, commands, and lambdas.]