Conditional test `? :` behave differently if switch the turn of return value

Currently, I worked on this homework, i.e. Triangle. Some code snippet for test the isosceles is as following:

reset_pos(idx) = idx == 0 ? 1 : idx

function is_triangle(sides)
    i = 1
    while i <= length(sides)
        sides[i] + sides[reset_pos(mod(i+1,3))] > sides[reset_pos(mod(i+2,3))] ? i = i+1 : return false
    end
    return true
end

function is_isosceles(sides)
    if !is_triangle(sides) return false end
    i = 1
    while i <= length(sides)
        (sides[i] == sides[reset_pos(mod(i+1,4))]) ?  return true : i=i+1 # strange thing happens here.
    end
    return false
end

# test 
is_isosceles([1,2,2])

if the above code annotated is

(sides[i] == sides[reset_pos(mod(i+1,4))]) ?  return true : i=i+1

The compiler warns ERROR: LoadError: syntax: colon expected in "?" expression. However, if the above code annotated is changed into

!(sides[i] == sides[reset_pos(mod(i+1,4))]) ? i=i+1 : return true

is_isosceles(sides) works normally.

I wonder if I missed something. What caused the annotated code snippet behaves wrong?

Thank you.

Just a guess, but try wrapping the return statement in parentheses - that is ... ? (return true) : .... I’ve found that most syntax errors I make can be solved with judicious use of parentheses.

I don’t understand it in detail, but it’s something to due with how the parser breaks down your code into expressions. Things like return and = for assignment are special - I’m guessing that stuff ? retun foo : bar gets parsed as (stuff) ? (return foo : bar) rather than what you intended (stuff) ? (return foo) : (bar)

1 Like

Your solution works. Some revisions like the following works. Anyway, let’s wait to see if anyone can offer more details. Thank you.

(sides[i] == sides[reset_pos(mod(i+1,4))]) ?  (return true) : i=i+1
1 Like

This is parsed as return (true : i=i+1)

Just don’t return in ?:, use a proper if.

9 Likes

thank you very much. 囧rz