How To Broadcast "in" to Compare Two Arrays?

Hi all,

I was doing some googling today and stumbled across this interesting syntax for an “in” broadcast where I want to check to see if any element from the first array is present in the second array:

in([1, 2]).([1, 2, 3])

I haven’t really seen this type of broadcasting before.
It returns a bit vector which makes sense but I am having trouble understanding the semantics of how this is working.
Could anyone explain to me in simple terms how this is working?

Thanks!

~ tcp :deciduous_tree:

in(x) is equivalent to y -> in(x, y), i.e. in(x)(y) == x in y. That means that in(x).(v) will be like [x in y for y in v]


Edit, I accidentally got the above backwards as was pointed out by @rafael.guerra. The correct version of the above is:

in(x) is equivalent to y -> in(y, x), i.e. in(x)(y) == y in x. That means that in(x).(v) will be like [y in x for y in v]

1 Like

Sorry master, shouldn’t it be instead:
in(x) is equivalent to y -> y in x, i.e. in(x)(y) == y in x
That means that: in(x).(y) will be like: y .∈ (x,)

In the OP example, the following two are equivalent:

( in([1, 2]).([1, 2, 3])  ) == ( [1, 2, 3] .∈ ([1, 2],) )  # true
3 Likes

Yes, sorry I wrote the above backwards, I wasn’t at my computer to double check.

It’s good that it works this way because in(x) really should generate a predicate function that checks if y is in x!

2 Likes

I see how this works, but this initially confused me since I would naively expect it to correspond to:
[ 1 ∈ ([1,2],), 2 ∈ ([1,2],), 3 ∈ ([1,2],)] == [0, 0, 0]
but the broadcast re-interprets the length-1 tuple ([1,2],) into just [1,2].

Broadcast doesn’t reinterpret the tuple, it iterates over all of it’s elements (which is one). E.g.

julia> println.(());

julia> println.((1,));
1

julia> println.((1,2));
1
2

Wrapping something in a Tuple or a Ref is how we make something act like a ‘scalar’ to broadcast.

So for instance, if we want to add [1, 2] to each element of [[1, 2], [3, 4], [5, 6]], then one thing we could write is

julia> [[1, 2], [3, 4], [5, 6]] .+ ([1, 2],)
3-element Vector{Vector{Int64}}:
 [2, 4]
 [4, 6]
 [6, 8]
4 Likes

I see, that helps me understand now. Thanks!

1 Like