Version 10 of linsert

Updated 2004-10-27 11:45:42

linsert - insert elements into a list

http://www.purl.org/tcl/home/man/tcl8.4/TclCmd/linsert.htm


 linsert list index element1 ?element2 element3 ...?

A user asked why

    linsert $list 0 ..

did not result in .. being inserted into list.

Jesper Blommaskog ([email protected]) replied:

When doing list operations other than lappend, you must save the returned value. This applies to list, lindex, lrange, and lreplace at least.

In this example, you would perhaps want to do something like:

    set list [ linsert $list 0 .. ]

TFW Feb 20, 2004 - Inplace inserts

Often time we have a long list we want to insert "in-place", that is without copying the list to a new altered list. Using the K combinator it is quite easy. (Note 8.5 is needed for the {expand} command)

 proc lipinsert {_list index args} {
    upvar $_list list
    set list [linsert [K $list [set list ""]] $index {expand}$args]
 }
 > set A [list 1 2 3]
 1 2 3
 > lipinsert A 1 a b c
 1 a b c 2 3

DKF 26 Oct 2004: The linsert command can be used to create a "lprepend" command that is like lappend except that it puts the values at the start of the list:

 proc lprepend {var args} {
    upvar 1 $var v
    lappend v   ;# Used as a an "is a list" check and to do var creation
    set v [linsert $v[set v {}] 0 {expand}$args]
 }

(Note that this uses a variant on K that is more efficient in 8.5a2 but not so hot in previous versions)

Lars H: Has the above any advantage in comparison with

    set v [linsert $v [set v 0] {expand}$args]

which is anyway slightly shorter? (OK, it can be used also where ther isn't another argument to place the [set v <whatever>] in, but what about those cases where an alternative exists? Is the idea of the example to establish a new idiom?)


See also list, lappend, llength, lrange, lreplace, lsearch, lsort .


Tcl syntax help - Arts and crafts of Tcl-Tk programming - Category Command