Search code examples
juliaoperatorschain

Chaining of operators with .|> in Julia


I have an expression

 [1:5;] .|> [x->x^2, inv, x->2*x, -, isodd]

taken from Julia documentation.

The output is

5-element Vector{Real}:
    1
    0.5
    6
   -4
 true

Can somebody explain the chain of operations on each elements 1:5 in detail. I did not understand why 1 is converted to 1 and 5 is converted to true.


Solution

  • What you are doing is equivalent to:

    julia> (x -> x^2)(1)
    1
    
    julia> inv(2)
    0.5
    
    julia> (x -> 2x)(3)
    6
    
    julia> -(4)
    -4
    
    julia> isodd(5)
    true
    

    i.e. you are broadcasting a container with five functions to it over a range with five elements. The first function is then applied to the first element of your range, the second function to the second element etc.