Last function

This is giving me false as output, can anybody explain why??

Unfortunately == allows comparing objects with different types, so you are accidentally comparing the Char 'd' to the String "d".

julia> last("abcd") == 'd'

You can get the string version by passing 1 to last.

julia> last("abcd",1) == "d"

Thanks :slight_smile:

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).

1 Like

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"

And note, in contrast, this will allocate for the String returned:
julia> @time last("abcd",1) == "d"
  0.000004 seconds (1 allocation: 32 bytes)

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.