Le mardi 07 avril 2015 à 06:05 -0700, David Gold a écrit :
> Greetings all,
>
> I've quite taken to the short-circuit evaluation idiom. I just have a
> quick question about its behavior. Why does
>
> boolexpr && boolvar = false
>
>
> throw an error ("syntax: invalid assignment location"), but
>
> boolexpr && (boolvar = false)
>
>
> work just fine? The documentation
> (http://docs.julialang.org/en/latest/manual/control-flow/#short-circuit-evaluation)
> doesn't quite mention this point, though the parentheses are used in the
> examples at the end of the section.
>
> I'm just curious. I don't have much background in programming (but
> will have to, as I'm beginning graduate study in statistics this
> coming fall -- I thought I'd be an early adopter of something for
> once), so please humor me if this is a silly question.
That's just because && has a higher precedence than =. See:
http://julia.readthedocs.org/en/latest/manual/mathematical-operations/#operator-precedence
So
boolexpr && boolvar = false
is parsed as
(boolexpr && boolvar) = false
which doesn't make sense.
I guess one of the reasons for that priority order is that one can write
things like this without parentheses:
x = cond1 && cond2 ? a : b
If you think that point should be mentioned in the docs, an addition
would likely be appreciated.
Regards