A metaprogramming question (sorry, can't find a more informative title)


#1

Here is an example I took from http://docs.julialang.org/en/stable/manual/metaprogramming/#interpolation, which confuses me.

My questions: 1. What does $:((1,2,3)) mean? Can we think $ and : as opposite operators which cancel each other, so that $:((1,2,3)) is exactly same as the original tuple (1,2,3)? 2. Why ex1 == ex2, but not ex1 === ex2? Thanks!!

julia> ex1 = :(a in $:((1,2,3)) )
:(a in (1,2,3))

julia> ex2 = :(a in (1,2,3) )
:(a in (1,2,3))

julia> ex1 == ex2
true

julia> ex1 === ex2
false


#2

Even though in some contexts $ and : “cancel”, I would think of : as a quote and $ as a splice operator instead.

The two expressions are not === since they are not the same object. Eg you could

push!(ex2.args[3].args,4)

and it would not affect ex1.


#3

Thanks, @Tamas_Papp! Then how should I understand the following?


julia> a = 1
1

julia> b = 1
1

julia> a === b
true

I’m quite surprised that a and b are a same object?


#4

expressions are objects. two objects created separately are never ===. consider

a = :(1+1); b = :(1+1); a===b
# -> false
a = []; b = []; a===b
# -> false

#5

In some cases, a nice alternative to being surprised is reading the documentation:

help?>  is
search: ind2sub @ip_str include_string @int128_str is isa issym isqrt isodd isnan

  is(x, y) -> Bool
  ===(x,y) -> Bool
  ≡(x,y) -> Bool

  Determine whether x and y are identical, in the sense that no program could
  distinguish them. Compares mutable objects by address in memory, and compares
  immutable objects (such as numbers) by contents at the bit level. This function
  is sometimes called egal.

#6

Thanks. Can you explain the difference between your second example and the following one?

julia> a = 1
1

julia> b = 1
1

julia> a === b
true


#7

The identity of immutables (e.g. 1) only depend on their value. The identity of mutable types (e.g. []) depend on their address.


#8

Thanks for the hint. But I’m not claiming a or b as immutable. Why is there anything to do with immutable? Thanks!


#9

immutable is a property of the type, it has nothing to do with the variable it is bound to.


#10

I see now. Just like:

julia> 1 === 1
true

julia> [] === []
false

Thanks!