Version 0 of lshift

Updated 2009-03-02 21:46:40 by LEG

lshift - shift list and return first element

lshift listVar

This is not a command included in Tcl, but rather a common 'idiom' for in place list manipulation used e.g. for implementing queues are for commandline processing.


Implementations

The following is taken from Tcl Gems though slightly modified:

proc lshift listVar {
    upvar 1 $listVar l
    set r [lindex $l 0]
    set l [lreplace $l [set l 0] 0]
    return $r
}

You can use this programming idiom also without having the lshift command, e.g. with the K combinator:

    K [lindex $l 0] [set l [lreplace $l [set l 0] 0]

Or more generalized:

lshift listVar ?count?

Shift list count elements and return the respective elements.

proc lshift {listVar {count 1}} {
    upvar 1 $listVar l
    set r [lrange $l 0 [incr count -1]]
    set l [lreplace $l [set l 0] [incr count]]
    return $r
}

Different Interpretations

In lshift -Adding Unique Items to Lists of Fixed Length the command lshift puts an element on a list if it is not already there. It is used to implement a 'recently used' list