SIMEL
SIMEL

Reputation: 8941

Find the intersection of two lists in tcl

Is there a command that will allow me to get the intersection (members that apear in both lists) of two lists?

For example, if the lists are:

a b c d h and c e f g h

the result should be c h

Upvotes: 2

Views: 13791

Answers (3)

RHSeeger
RHSeeger

Reputation: 16262

Assuming what you really have is a set (a list with unique elements), you can use tcllib:

::struct::set intersect ? set1... ?

package require Tcl 8.0
package require struct::set

set list1 {a b c d h}
set list2 {c e f g h}
::struct::set intersect $list1 $list2
> c h

Upvotes: 7

glenn jackman
glenn jackman

Reputation: 246807

package require Tcl 8.5
set a {1 2 3 4 5}
set b {3 4 5 6 7}
set intersect [list]

foreach elem $a {
    if {$elem in $b} {
        lappend intersect $elem
    }
}

Upvotes: 2

Andrew Cheong
Andrew Cheong

Reputation: 30273

There isn't a command, but typically the way I do this is cache elements during construction of one or more of the lists, to save time. For example, given the following:

foreach x {a b c d h} {
    lappend list_x $x
}

foreach y {c e f g h} {
    lappend list_y $y
}

I would add:

foreach x {a b c d h} {
    lappend list_x $x
    set cache($x) 1
}

foreach y {c e f g h} {
    lappend list_y $y
    if {[info exists cache($y)]} {
        lappend list_xy $y
    }
}

puts $list_xy

Output:

c h

Upvotes: 6

Related Questions