chaining and (dot) operations

First I admit I have some Elixir experience that leads me to have intuition about |> that is wrong. That said…

I was reading the docs and playing with some data and realized I could use .|> rather like a call to map

julia> [1:5;] .|> x → x^2
5-element Array{Int64,1}:
1
4
9
16
25

but, I can’t seem to switch back to the |> behaviour I expect

julia> [1:5;] .|> x → x^2 |> sum
5-element Array{Int64,1}:
1
4
9
16
25

I expect 55 not an Array

Can someone explain why my intuition is wrong and what I’m missing, Thanks.

julia> ([1:5;] .|> x->x^2) |> sum
55

This works too

[1:5;] .|> (x -> x^2) |> sum

To add to the above explanations: your original expression is parsed as

[1:5;] .|> x-> (x^2 |> sum)

You can see this by comparing the output of

julia> Meta.show_sexpr(:([1:5;] .|> x->x^2 |> sum))
(:call, :.|>, (:vcat, (:call, :(:), 1, 5)), (:->, :x, (:block,
      :(#= REPL[16]:1 =#),
      (:call, :|>, (:call, :^, :x, 2), :sum)
    )))
julia> Meta.show_sexpr(:([1:5;] .|> x-> (x^2 |> sum)))
(:call, :.|>, (:vcat, (:call, :(:), 1, 5)), (:->, :x, (:block,
      :(#= REPL[17]:1 =#),
      (:call, :|>, (:call, :^, :x, 2), :sum)
    )))
6 Likes