Version 2 of K

Updated 2002-12-12 10:08:37

Short for the K combinator, together with S the fundamental functional operators from which all function composition can be done. It is extremely simple:

 proc K {x y} {set x}

It just returns its first argument (and discards the second). The advantage is that in this way you can hold an intermediate result which you finally want to return, after doing more processing (which ends up in y) where only the side effects matter. Consider popping a global stack (top at end):

 proc pop1 {} {
    set top [lindex $::Stack end]
    set ::Stack [lrange $::Stack 0 end-1]
    return $top
 }

or, implemented with K:

 proc pop2 {} {K [lindex $::Stack end] [set ::Stack [lrange $::Stack 0 end-1]]}

One command less, one variable less, a slick one-liner (from: A different FORTH).

See Hot curry and Combinator engine for more details than you'd expect ;-)


Category Concept | Arts and crafts of Tcl-Tk programming