Version 4 of ldiff

Updated 2014-01-21 18:22:07 by PeterLewerin

Peter Lewerin 2013-12-31: Find the difference of two lists, i.e. the list of elements that occur in list a but not in list b (and not the inverse of the intersection, i.e. the list of elements that occur in only one of the two lists).

package require Tcl 8.5
proc ldiff {a b} {
    lmap elem $a { expr {$elem in $b ? [continue] : $elem} }
}

ldiff {2 3 4 5 6 7 8 9 10} {2 3 5 7}
# -> 4 6 8 9 10
ldiff {1 2 3} {2 3 4}
# -> 1

This command probably isn't very efficient.


Gotta move with the times, it's not 2013 anymore!

The "new" in operator is more expressive than lsearch -exact, and, as I found today, quite a bit faster. So my old implementation gets retired (but I'll leave it here for pre-8.5 Tclers).

proc ldiff {a b} {
    lmap elem $a {
        expr {[lsearch -exact $b $elem] > -1 ? [continue] : $elem}
    }
}

gkubu - 2013-12-31 17:15:58

see also struct::set, http://tcllib.sourceforge.net/doc/struct_set.html (subcommand difference)