listtcl

concatinating tcl lists into one list


I have a procedure that returns a single element or a list of elements. I am trying to concatenate all the returned elements into a single list.

set childList [list];
foreach item $myList {
    lappend childList $item; 
    set tempChildList [::myproc $item];  #for different items it will return either single element or a list of elements. 
    if {[llength $tempChildList] > 0} {
        lappend childList $tempChildList;
    }
}

So now in my last statement when i lappend $tempChildList into childList it forms a list of lists like below

{a {b c} {d e f} {g {h i}} j}

but i want to concatenate the childList and tempChildList so that my final result will be

{a b c d e f g h i j}

i was thinking of using concat command but the issue is it wont concat the nested lists like {g {j i}} in my above use case.


Solution

  • In your situation, I recommend not flattening the list, but rather being more careful during its construction. In particular, flattening has problems where the list contains compound words (which can result in things going horribly wrong when you do a fancy demo, and things like that). By being more careful, knowing what sort of result you're getting from ::myproc (and assuming that's a simple list), you can then produce a simple concatenated list quite easily:

    set childList [list]
    foreach item $myList {
        lappend childList $item {*}[::myproc $item]
    }
    

    Note that if you're keen on returning a single item from ::myproc, return it with this:

    return [list $theItem]
    

    Though if $theItem is a simple word (e.g., some kind of ID) you can get away without being careful.