Search code examples
sortingtclapplyexpr

list sorting using apply function of Tcl


suppose I have a list like below:

set listNums {0 -1 5 5 -5 1 10 100 -10 -10 1000}

I want to sort it using the absolute values. I picked up the below from another script. I am having a tough time understanding this. Can someone help me understand what is going on in the below script? I used "puts" to print out values at each stage but I still did not get it!

How does "a" and "b" get updated? Why do we need "return 0" ?
Sorry if I am asking rudimentary questions.

lsort -command {apply {
  {a b}
  {
    if {[expr {abs($a)] < [expr {abs($b)}]} {return -1}
    if {[expr {abs($a)] > [expr {abs($b)}]} {return 1}
    if {$a < $b} {return -1}
    if {$a > $b} {return 1}
    return 0
  }
}} $listNums

Solution

  • Every time two elements are compared during the sorting, one is passed into this invocation as a, and the other as b.

    The result of the comparison can be "lesser than", "greater than", or "equal", encoded as the return values -1, 1, or 0.

    Also, try

    if {abs($a) < abs($b)} ... 
    

    instead: the condition to if implicitly invokes expr.

    And don't compare twice.

    Documentation: apply, if, lsort