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

对着背影说爱祢 提交于 2019-12-02 07:25:27

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}]
}

I would do:

# from tcllib
package require struct::list


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

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