== on composite values containing collections

93 views
Skip to first unread message

Zenna Tavares

unread,
Feb 23, 2015, 8:13:56 AM2/23/15
to juli...@googlegroups.com
I was recently surprised to find:

immutable MyType
  v
::Vector{Int}
end

MyType([1,2,3]) == MyType([1,2,3])
>false

In this case `==` is reduced to `===` and the documentation says that these values will be compared bitwise.  I suspect it evaluates to false because this bitwise comparison is on two different pointers? The help does also say for ==  that "Collections should generally implement "==" by calling "==" recursively on all contents".  But, I would imagine the majority of Julia users have not read this, and that there are many lurking bugs due to the expectation that the above comparison should evaluate to true.

(At least) for immutable types:
- is the reason the default behaviour does not compare the contents of collections in a type for efficiency?
- would warning users who use the fallback == on types which contain collections also incur a cost?

At the very least I think it should be emphasised in the documentation, perhaps on the Types page.

My own solution is:

equiv{T}(a::T,b::T) =
  all
([getfield(a,f) == getfield(b,f) for f in T.names])


This is not quite right, the == needs to be replaced with some method which is == in the case of primitive types and equiv in the case of composite types (actually, how would one do this?).  In any case, it seems like some more correct version of equiv is so basic that it exists already or I am missing something fundamental.

Zenna Tavares

unread,
Feb 23, 2015, 4:43:31 PM2/23/15
to juli...@googlegroups.com
A better version might be:

eq_f{T}(x::T,y::T) = Base.isstructtype(T) ? (==) : deepequiv


function deepequiv{T}(a::T,b::T)
 
for f in T.names
   
if Base.isdefined(a,f) && Base.isdefined(b,f)
      same
= eq_f(getfield(a,f), getfield(b,f))(getfield(a,f),getfield(b,f))
     
!same && return false
    elseif
Base.isdefined(a,f) $ Base.isdefined(b,f)
     
return false
   
end
 
end
 
return true
end
Reply all
Reply to author
Forward
0 new messages