This is giving me false as output, can anybody explain why??
== allows comparing objects with different types, so you are accidentally comparing the Char
'd' to the String
julia> last("abcd") == 'd' true
You can get the string version by passing
julia> last("abcd",1) == "d" true
To explain why this happens:
== falls back to
=== for comparisons, which has a default fallback of
false for objects of different types (they’re differently typed objects after all and as such cannot be the exact same thing).
Is it a mistake to define it as such? Should it be defined as:
julia> import Base.== julia> ==(C::AbstractChar, S::AbstractString) = S == string(C) julia> ==(S::AbstractString, C::AbstractChar) = S == string(C) julia> last(x)=="d" true And note, in contrast, this will allocate for the String returned: julia> @time last("abcd",1) == "d" 0.000004 seconds (1 allocation: 32 bytes) true
I thought my version would also allocate because of
string, and I was going to amend it, but actually it doesn’t, at least on 1.7.3. I guess the compiler is just clever.