Version 5 of Pipeline programming

Updated 2007-03-13 17:42:33

SS 13 March 2007. I like to program in a functional style, so many times I end writing in Tcl and other languages something like a [b [c [d $arg]. Semantically this is like the Unix shell pipe, so I wrote the following function.

Example:

 set s "    supercalifragilistichespiralitoso    "
 pipe    {string trim $s} {split * {}} {lsort -unique} {join * {}} > s \
         {string length} > l
 puts $s
 puts $l

Will output

 acefghiloprstu
 14

The code:

 proc pipe args {
     set r [uplevel 1 [lindex $args 0]]
     for {set i 1} {$i < [llength $args]} {incr i} {
         set e [lindex $args $i]
         if {[llength $e] == 1} {
             if {$e eq {>}} {
                 incr i
                 uplevel 1 [list set [lindex $args $i] $r]
             } else {
                 set r [uplevel 1 [list $e $r]]
             }
         } else {
             set cmd {}
             set substdone 0
             foreach arg $e {
                 if {$arg eq {*}} {
                     lappend cmd $r
                     set substdone 1
                 } else {
                     lappend cmd $arg
                 }
             }
             if {$substdone == 0} {
                 lappend cmd $r
             }
             set r [uplevel 1 $cmd]
         }
     }
     return $r
 }

 set s "    supercalifragilistichespiralitoso    "
 pipe    {string trim $s} {split * {}} {lsort -unique} {join * {}} > s \
         {string length} > l
 puts $s
 puts $l

If you read italian there is a longer article about this concept in my blog at http://antirez.com/post/49

p.s. I don't know how to write a literal square bracket, please fix the formatting of the first line if you know how to do it.


LV I don't know where you mean you need a [ and ] - can you be more specific?


Category Command