-1

we can extract every n-th element of a TCL list by foreach loop. But is there a single line generic TCL cmd that will do the trick? Something like lindex with a '-stride' option.

Gert Gottschalk
  • 1,658
  • 3
  • 25
  • 37

2 Answers2

4

If you have lmap (Tcl 8.5 version in the links below) you can do this:

lmap [lrepeat $n a] $list {set a}

Example:

set list {a b c d e f g h i j k l}
set n 2
lmap [lrepeat $n a] $list {set a}
# => b d f h j l

But your comment seems to indicate that you really want the n+1 th value. In that case:

lmap [lreplace [lrepeat $n b] 0 0 a] $list {set a}
# => a c e g i k

Documentation: list, lmap (for Tcl 8.5), lmap, lrepeat, lreplace, set

Peter Lewerin
  • 13,140
  • 1
  • 24
  • 27
2

No, but you can do write a proc like:

proc each_nth {list n} {
    set result [list]
    set varlist [lreplace [lrepeat $n -] end end nth]
    while {[llength $list] >= $n} {
        set list [lassign $list {*}$varlist]
        lappend result $nth
    }
    return $result
}

and then:

each_nth {a b c d e f g h i j k l} 3    ;# => c f i l
each_nth {a b c d e f g h i j k l} 4    ;# => d h l
each_nth {a b c d e f g h i j k l} 5    ;# => e j
glenn jackman
  • 238,783
  • 38
  • 220
  • 352