在 TCL 中比较两个列表的正确方法是什么? [英] What is the right way of comparing two lists in TCL?

查看:29
本文介绍了在 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]} { 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?

解决方案

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

这篇关于在 TCL 中比较两个列表的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆