Search code examples
listtclcomplexity-theory

Destructive TCLunshift



Let's say I have a list {1 2 3 }. I want to unshift it. Create a list which is { 0 1 2 3 }, without creating a new list. This is to save in complexity. In Perl and Ruby, it is possible, by using unshift. Is there a TCL equivalent?
Thanks.


Solution

  • There is no such command in Tcl, but you can easily make it yourself:

    proc lunshift {var args} {
        upvar 1 $var list
        set list [linsert $list[set list {}] 0 {*}$args]
    }
    

    The [set list {}] part is a trick to make the list unshared, so no duplicate will be made. See the Tcl wiki for details.

    Demo:

    set mylist {1 2 3}
    lunshift mylist 0
    puts $mylist;  # Result => 0 1 2 3