What is the right way of comparing two lists in TCL?
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]} { pu开发者_如何转开发ts "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?
I would do:
# from tcllib
package require struct::list
if {[::struct::list equal $list1 $list2]} { puts "Lists are equal"}
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}]
}
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!
#
#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)"
}
}
精彩评论