What is the right way of comparing two lists in TCL?

早过忘川 提交于 2019-12-02 11:44:40

问题


I am newbie to TCL and I have written the following code:

set list1 {{1 2} 3 4}
set list2 {{1 2} 8 1}
if {[lindex $list1 0] == [lindex $list2 0]} { puts "They are equal!"}

But when I print the sublist elements I see that they are equal, but the if statement does not catch it. Why? How I should right this comparision?


回答1:


If I were to implement an lequal proc, I'd start with this:

proc lequal {l1 l2} {
    foreach elem $l1 {
        if {$elem ni $l2} {return false}
    }
    foreach elem $l2 {
        if {$elem ni $l1} {return false}
    }
    return true
}

And then optimize to this:

proc K {a b} {return $a}

proc lequal {l1 l2} {
    if {[llength $l1] != [llength $l2]} {
        return false
    }

    set l2 [lsort $l2]

    foreach elem $l1 {
        set idx [lsearch -exact -sorted $l2 $elem]
        if {$idx == -1} {
            return false
        } else {
            set l2 [lreplace [K $l2 [unset l2]] $idx $idx]
        }
    }

    return [expr {[llength $l2] == 0}]
}



回答2:


I would do:

# from tcllib
package require struct::list


if {[::struct::list equal $list1 $list2]} { puts "Lists are equal"}



回答3:


They're not equal, and you test correctly for that. Sure you're printing the right variables?

EDIT: Behavior for me.

# cat test.tcl
set list1 {{1 2} 3 4}
set list2 {{1 2} 8 1}
if {[lindex $list1 0] == [lindex $list2 0]} { puts "They are equal!"}
# tclsh test.tcl
They are equal!
#



回答4:


#compare two lists with hash table
if {[llength $list1] ne [llength $list2]} {
    puts "number of list elements is different"
} else {
    puts "there are [llength $list1] list elements"
}
set i 1
foreach a {$list1} b {$list2} {
    set a($i) $a
    set b($i) $b
    incr i
}
for {set j 1} {$j <= [llength $list1]} {incr j} {
    if { $a($j) ne $b($j) } {
        puts "No Match $a($j) $b($j)"
    } else {
      puts "Match $a($j) $b($j)"
    }
}


来源:https://stackoverflow.com/questions/5195153/what-is-the-right-way-of-comparing-two-lists-in-tcl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!