Version 0 of lselect

Updated 2019-08-22 11:41:00 by KlausSaalfeld

lselect

Klaus Saalfeld A function lselect is proposed that selects a number of items from a list and returns them as a new list. In contrast to known lindex with multiple indices lselect doesn't operate on nested lists but on flat lists. The returned list contains the items in the same order as specified with the indices argument.

# Returns from the specified list those elements identified by given indices.
# For positive index value the first element is list is given by index 0.
# The end of the list is given by "end" with an optional negative offset (e.g. "end-1").
# Syntax: value indices
proc lselect {value indices} {
   set result {}
   if {0 != [llength $value]} {
      foreach index $indices {
         if {0 == [string compare -length 3 $index end]} {
            set index [expr ([llength $value] - 1) [string range $index 3 end]]
         }
         if {($index >= 0) && ($index < [llength $value])} {
            lappend result [lindex $value $index]
         }
      }
   }
   return $result
}

Some examples:

> lselect {car house tiger penguin} {end-1 1 end 0}
tiger house penguin car

> lselect {banana pineapple orange} 1
pineapple

> lselect {tcl is great} {-1 17 end-8}
<empty>

Many list operations are a special case of lselect. For example:

  • lindex $x $n corresponds to lselect $x $n.
  • lrange means selecting a consecutive range of items from a list

lselect is moreover useful to implement stack or buffer like behavior with lists or to shuffle lists.

See also