What does `|>` mean?

I saw this syntax during a Juliacon2018 video that I was watching. It was unfamiliar to me, so I tried to find it in the documentation, but the search functionality didn’t send me anywhere useful. I scrolled through different parts of the documentation that seemed relevant but it never turned up.

I’m sure this is something banal, but I’m curious

2 Likes

https://docs.julialang.org/en/v1/manual/functions/#Function-composition-and-piping-1

2 Likes

Thanks. I just also tried ?|> at the REPL and that started me on a useful path too.

3 Likes

Note also that there is a package, Pipe.jl, that greatly improve the pipe operator in base…

1 Like

It’s another of writing function call.

E.g let fn be a function then

x |> fn is equivalent to fn(x)

Let fn2 be another function then

x |> fn |> fn2 is equivalent to fn2(fn(x)) and is also equivalent to fn2(x | fn) and fn(x) |> fn2. You get the point.

You can also use the . broadcasting syntax with it. E.g

fn.(x) is equivalent to x .|> fn

4 Likes
julia> MulByTwo(x) = 2 * x
MulByTwo (generic function with 1 method)

julia> MulBySeven(x) = 7 * x
MulBySeven (generic function with 1 method)

julia> 10.0 |> MulByTwo |> MulBySeven
140.0
1 Like

Or

julia> mul(n) = x -> x * n
mul (generic function with 1 method)

julia> 10.0 |> mul(2) |> mul(7)
140.0
9 Likes

This is not quite true, since the latter can also iterate over fn, which is sometimes useful. For example, the following works, because it iterates over (cos, sin) and broadcast grows compatible dimensions:

julia> [0 pi/3 pi/4 2pi/3 pi/2] .|> (cos, sin)
2×5 Array{Float64,2}:
 1.0  0.5       0.707107  -0.5       6.12323e-17
 0.0  0.866025  0.707107   0.866025  1.0

This would not work with the standard fn.(x) syntax.

9 Likes

I don’t know the best way to solve this problem, but I want to second the comment that it can be hard to find the meaning of punctuation in the docs.

When I was a beginner, it took me a while to track down what <: and :: meant (for example) b/c it was hard to search for those symbols in the docs.

2 Likes

https://docs.julialang.org/en/v1/base/punctuation/

6 Likes

Amazing. Thanks! If that was around in 2016, I did not know about it when I needed it. It would be cool if that popped up if you searched for :: in the search function on the docs website. Like Microsoft Clippy saying “it looks like you’re searching for some Julia-specific punctuation”

2 Likes

Yes, it is hard to search for punctuation at the moment in the generated docs. You may want to open an issue about this, I could not find an existing on (but please check).

Possibly related to this one

1 Like