Version 3 of Filter in functional programming

Updated 2004-10-29 08:33:13

SS 29Oct2004: filter is a very useful function in functional programming, that given a list and a predicate (a function with arity of one, returing true or false) creates a new list which contains only the members of the original list meeting the predicate (in the same order they appeared).

I plan to submit a TIP for the addition of this function together with map in functional programming.

The following is an implementation for Tcl, with this command structure:

 filter var list expr

Some usage example:

 % filter x {1 2 3 4 5 6 7 8 9} {$x > 4}
 5 6 7 8 9
 % filter x {1 2 3 4 5 6 7 8 9} {$x % 3}
 1 2 4 5 7 8
 % filter x {1 2 3 4 5 6 7 8 9} {($x % 3) == 0}
 3 6 9
 % filter x [list a b {} c d e {} {} f g] {[llength $x]}
 a b c d e f g

Do you need filter? If you can see the following pattern in your code, you need it:

 set res {}
 foreach x $list {
    if {[foobar $x]} {
        lappend res $x
    }
 }
 use $res

Finally the (very simple) code:

 proc filter {fvar flist fexpr} {
     upvar 1 $fvar var
     set res {}
     foreach var $flist {
         set varCopy $var
         if {[uplevel 1 [list expr $fexpr]]} {
             lappend res $varCopy
         }
     }
     return $res
 }

Category Algorithm|Category Functional Programming