I’ve just got aware of chaining functions (like a pipeline) in Julia for a couple of days. I was trying something today and got an unexpected result. Hence, I decided to ask about the root of the problem better to understand the behavior of Julia in chaining functions. Consider this example:
julia> a = [1 2 3]
1×3 Matrix{Int64}:
1 2 3
Then I want to chain some functions like the below, and after all, I want the maximum value of the entire Matrix:
julia> a .|> x->x^2 .|> sqrt .|> Int64 |> maximum
1×3 Matrix{Int64}:
1 2 3
But I expected just a 3! Why doesn’t Julia consider that last function of the chain, namely, the maximum function?
PS: Also, I tried this way:
julia> a .|> x->x^2 .|> sqrt .|> Int64 |> x->maximum(x)
1×3 Matrix{Int64}:
1 2 3
Still not what I expected it to be.
>Solution :
The issue is associativity of |>, see https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity. As you can see:
julia> :(a .|> x->x^2 .|> sqrt .|> Int64 |> maximum)
:(a .|> (x->begin
#= REPL[11]:1 =#
((x ^ 2 .|> sqrt) .|> Int64) |> maximum
end))
To resolve this put the first part (before broadcast) in parentheses:
julia> (a .|> x->x^2 .|> sqrt .|> Int64) |> maximum
3
However, I personally in such cases prefer to use composition:
julia> maximum((Int64∘sqrt∘(x->x^2)).(a))
3