Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove a sublist from list in tcl

Tags:

tcl

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

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

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

a { 1 2  { {3 4} } }

Please suggest how to dot his.

like image 885
Ruchi Avatar asked Oct 09 '22 19:10

Ruchi


2 Answers

Combine lindex to get the internal sublist, lreplace to delete an element of the extracted internal sublist and lset to put the modified sublist back in place.

But honestly I have a feeling something's wrong about your data model.

like image 65
kostix Avatar answered Oct 13 '22 10:10

kostix


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
}

If you need variable depth you're lost with this code. You need recursion for that.

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

As the outer list is never displayed in tclsh.

like image 25
unNamed Avatar answered Oct 13 '22 12:10

unNamed