Search code examples
operatorsjulia

How do I define a new operator |= or |>= in Julia?


We know that a += 1 is equivalent to a = a + 1. I would like to have a |>= √ or a |= √ being equivalent to a = a |> √. Can I define this new operator?


Solution

  • The set of updating operators is hardcoded and currently limited to:

    += -= *= /= //= \= ^= ÷= %= <<= >>= >>>= |= &= ⊻= $=
    

    The parser will automatically expand all of these to a = a op b. All of these operators, however, have well defined meaning in base and have different precedence than |>. You could shadow one of these definitions with your own meaning, but it'll be very surprising for anyone else that uses your code… and you yourself could be surprised by the precedence at times.

    julia> const | = |>
    |> (generic function with 1 method)
    
    julia> a = 2
    2
    
    julia> a |= √
    1.4142135623730951
    

    I suppose you could make it a little better by only overriding the behavior for function arguments:

    julia> >>>(x, y::Function) = y(x)
           >>>(x, y) = Base.:>>>(x, y)
    >>> (generic function with 2 methods)
    
    julia> a = 2
           a >>>= √
    1.4142135623730951
    
    julia> 0xf3 >>> 3 # The standard unsigned bit shift
    0x1e