Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Julia doesn't consider maximum function in the chained functions?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading