Remove a list from a list in tcl

I want to remove a sublist from a list in Tcl. I know how to do this for a main list using lreplace, but I don't know how to do this for a sublist. For instance:

set a { 1 2  { {3 4} { 4 } } }

Now I want to remove {4}from the internal list { {3 4} {4} }. The final list should be:

a {1 2 {{3 4}}}

Please suggest how to arrange it.

+5
source share
3 answers

Combine lindexto get the internal sublist, lreplaceto remove the item from the extracted internal sublist and lsetto return the modified sublist back.

But honestly, I have something wrong with your data model.

+2
source
proc retlist {a} {
    set nl ""
    foreach i $a {
        if {[llength $i] > 1} {
            set nl2 ""
            foreach i2 $i {
                if {[llength $i2] > 1} { lappend nl2 $i2 }
            }
            lappend nl $nl2
        } else {
            lappend nl $i
        }
    }
    return $nl
}

, . .

% set a {1 2 {{3 4} {5}}}
1 2 {{3 4} {5}}
% retlist $a
1 2 {{3 4}}

tclsh.

+1

:

proc lremove {theList args} {
    # Special case for no arguments
    if {[llength $args] == 0} {
        return {}
    }
    # General case
    set path [lrange $args 0 end-1]
    set idx [lindex $args end]
    lset theList $path [lreplace [lindex $theList $path] $idx $idx]
}

set a [lremove $a 2 1]

This works because the and tags lset, and lindexcan receive path, and they also do reasonable things with an empty path.

+1
source

All Articles