Equivalent of Python's Walrus operator (:=) in Julia

182 Views Asked by At

In python you can write

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

is there an equivalent feature in Julia?

2

There are 2 best solutions below

0
Felix B. On BEST ANSWER

The value of assignment is always passed through (because everything is an expression) in julia, so you could write

if (n = length(a)) > 1
    println("List is too long ($(n) lements, expected <= 10)")
end

to avoid confusion with == and to make the variable local, you can use the local keyword. This is then equivalent to a walrus operator

if (local n = length(a)) > 1
    println("List is too long ($(n) lements, expected <= 10)")
end
0
Oscar Smith On

To expand on the above answer, python needs := because python makes a distinction between statements and expressions (see https://en.wikipedia.org/wiki/Statement_(computer_science)). Expressions are more flexible in where they are allowed than statements and return a value, while statements do not return values and can only be used in a more restricted set of locations.

In Julia (in the Lisp tradition), everything is an expression so you don't need a separate := from the your regular = expression. = already is an expression that returns the right hand side.