Welcome, guest | Sign In | My Account | Store | Cart

Altough the latest Tcl verions have a -unique flag for lsort, older verions do not. So for those with older versions here is some nice, fast uinquer. Note that it assumes that the list items do not include the charecter ',' so it should probably be used only with numeric data.

Tcl, 5 lines
1
2
3
4
5
### NOTE: this assumes list data does not contain the , (comma) char...
proc unique { list } {
    array set a [split "[join $list {,,}]," {,}]
    return [array names a]
}

What we do here is a simple as split,join,return: 1) join the list using a double comma, so that {1 2 3 1} turns into the string "1,,2,,3,,1" 2) add an exra comma at the end 2) split it back into a list using a single comma, so we now have {1 {} 2 {} 3 {} 1 {}} 3) array set it into something, will produce: a(1) {} a(2) {} a(3) {} 4) just return the names of the array, which are always unique

3 comments

Richard Suchenwirth 21 years, 3 months ago  # | flag

A simple alternative without caring for commas.

proc uniq list {
   foreach element $list {set a($element) ""}
   array names a
}
Nir Levy (author) 21 years, 2 months ago  # | flag

True, but... i wanted to avoid having a foreach for preformance reasons. On my machine it was significant when dealing with large lists...

Nir Levy (author) 21 years, 2 months ago  # | flag

Empty Lists. Oh... forgot to mention that it does not handle empty lists well. You can always add

if { $list == {} } { return {} }

as the first list to have proper support...

Created by Nir Levy on Sun, 1 Sep 2002 (MIT)
Tcl recipes (162)
Nir Levy's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks