Question mark with dot operations

I got such an example which quite confused me.

## Won't work
a = [1,2,3]
a .+= (true) ? [1,1,1] : 0
## Functionable version
a = [1,2,3]
b = (true) ? [1,1,1] : 0
a .+= b

The first version will report

ERROR: TypeError: non-boolean (Vector{Int64}) used in boolean context
Stacktrace:
 [1] top-level scope
   @ REPL[10]:1

but the second will work just fine.

I do regard it confusing that it doesn’t recognize (true) ? [1,1,1] : 0 as a whole part when used in an anonymous way.

Both versions work for me when running on Julia v1.9.0.
Which version are you on?

1 Like

Based on the reported error, I would guess that the broadcasting gets higher precedence than the ternary operator and the expression is evaluated as

(a .+= (true)) ? [1,1,1] : 0

You could try

a .+= ((true) ? [1,1,1] : 0)

However, I confirm that the original expression works for me on 1.9 too.

1 Like

I have tried on Julia 1.0.4 and 0.7 (the lowest version I have) and the first example also works…

1 Like

Quite strange. But I got the problem.
The first version a .+= (true) ? [1,1,1] : 0 works. But a .+ (true) ? [1,1,1] : 0 or c = a .+ (true) ? [1,1,1] : 0 won’t work. I typed the problematic one.

In a .+ (true) ? [1,1,1] : 0 you are trying first to sum a boolean number with a number to get a boolean value, from there you have an error.
It is just an issue about precedences, this work as expected: a .+ ((true) ? [1,1,1] : 0)

Thanks, this makes sense. I thought the question mark should organize (true) ? [1,1,1] : 0 as a whole part but it proved me wrong.