Version 5 of Filter in functional programming

Updated 2004-10-29 14:08:43

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
 }

RS would prefer an argument sequence with the list in the end:

 filter x {$x > 4} $list

so the second and third argument, which form a lambda, are left together.


SS Indeed, it's not clear what's the best. I like more what you proposed from an aesthetic point of view, but to have the same arguments order as map and foreach can be a good point.

There is another option too:

 filter $list x {$x > 4}

that sounds to me slightly better.


Category Algorithm|Category Functional Programming