TclOO:对象等于

TclOO: object equals

TclOO object equals 实现的惯用模式是什么?

也许比较串联排序 lists of all properties?

是否有 Scala 的类似物 case classes

TclOO 在设计上没有为您定义平等制度;因为对象通常是可修改的,所以除了对象标识之外没有自动应用的概念,你可以只比较对象的名称来获得它(或者 info object namespace $theObj 的结果,如果你非常偏执狂;我认为 Tcl 8.7 将提供更多选项,但尚未被接受)。

如果你想像你提议的那样定义一个平等制度,你可以这样做:

oo::class create PropertyEquals {
    method equals {other} {
        try {
            set myProps [my properties]
            set otherProps [$other properties]
        } on error {} {
            # One object didn't support properties method
            return 0
        }
        if {[lsort [dict keys $myProps]] ne [lsort [dict keys $otherProps]]} {
            return 0
        }
        dict for {key val} $myProps {
            if {[dict get $otherProps $key] ne $val} {
                 return 0
            }
        }
        return 1
    }
}

那么你只需要在你可能要比较的class上定义一个properties方法,并混入上面的equals方法。

oo::class create Example {
    mixin PropertyEquals
    variable _x _y _z
    constructor {x y z} {
        set _x $x; set _y $y; set _z $z
    }
    method properties {} {
        dict create x $_x y $_y z $_z
    }
}

set a [Example new 1 2 3]
set b [Example new 2 3 4]
set c [Example new 1 2 3]
puts [$a equals $b],[$b equals $c],[$c equals $a]; # 0,0,1

请注意,Tcl 不像某些其他语言那样提供复杂的集合 classes(因为它具有类似数组和类似映射的开放值),因此不需要对象相等性(或内容哈希)框架来支持它。