Version 3 of list map and list grep

Updated 2003-08-13 16:45:05

Perhaps I'm just having a bout of Perl envy, but I keep wanting to implement an lmap and lgrep set of procs that do map and grep on lists. Sample usage:

  % set l [list a b c d]
  a b c d

  % lmap l { format %s%s $_ $_ }
  aa bb cc dd

  % lgrep l { string match *d* $_ }
  d

These are easy enough to implement in Tcl:

  proc lmap {listName expr} {
    upvar $listName list
    foreach _ $list {
      lappend newList [eval $expr]
    }
    return $newList
  }

  proc lgrep {listName expr} {
    upvar $listName list
    foreach _ $list {
      if [eval $expr] {
        lappend newList $_
      }
    }
    return $newList
  }

Does anyone else wish these were part of standard Tcl? Would someone want to write up the TIP to try and get this in?

-- Dossy 13aug2003


RS What you want (and have implemented) are the classic map (function mapping) and filter functions. The term lgrep seems not so good to me, as grep is etymologized as "general regular expression parser", and filter allows much more than that.

However, use of an implicit variable _ is no good Tcl style. I'm afraid one would have to call these with named or anonymous functions (Lambda in Tcl):

 lmap2   [lambda x {format %s%s $x $x}]   $list    ;# pass values, not names!
 lfilter [lambda x {string match *d* $x}] $list

And I think, as easily these are implemented, there's no need to TIP a core change... List comprehension has a fancy, and lambda-less, wrapper for filters:

 % all  i in {1 0 3 -2 4 -4} where {$i>1}
 3 4

[ Category Suggestions ]