A more powerful version of the operator |>

(This is probably the best section to make this proposal)
I recently asked a question about how often the |> operator is used.
Many people don’t use the pipe operator because of its limitations (having to write a lambda every time the function to the right of |> takes more than one argument, or having to rely on external macros).
I wish there were more powerful versions of the pipe operator in the Base library that didn’t force you to write lambdas.
I’ve been thinking about something like this but I don’t know if they are good or bad practice:

before

a = [1:100;]
a |> 
    x -> reshape(x, 10, 10)   |>    # reshape to 10x10 matrix
    x -> my_function(x, args) |>    # apply a function with other args to the matrix
    x -> reshape(x, size(a))  |>    # convert to original size
    x -> filter(iseven, a)    

after

|>₁(a, f_args::Tuple) = f_args[1](a, f_args[2:end]...)
|>₂(a, f_args::Tuple) = f_args[1](f_args[2], a, f_args[3:end]...)
|>₃(a, f_args::Tuple) = f_args[1](f_args[2], f_args[3], a, f_args[4:end]...)

a = [1:100;]
a |>₁
    (reshape, 10, 10)   |>₁    
    (my_function, args) |>₁
    (reshape, size(a))  |>₂
    (filter, iseven)

What are your thoughts on this? Does it make sense? Are there better ways to do this? Thank you.

2 Likes

Have you seen Underscores.jl? It provides placeholder functionality, which tries to solve the same issue.

3 Likes

Julians have considered this problem quite a lot, except the focus has been on simplifying lambdas using underscores, see #24990. One version of the proposed syntax has been implemented in Underscores.jl, so you can do this:

julia> using Underscores

julia> my_function(x,b) = x * b
my_function (generic function with 1 method)

julia> a = [1:100;];

julia> @_ a |>
    reshape(__, 10, 10) |>
    my_function.(__,3) |>
    reshape(__, size(a)) |>
    filter(iseven, __)

50-element Vector{Int64}:
   6
  12
  18
  24
  30
  36
  42
  48
  54
  60
  66
  72
  78
   ⋮
 234
 240
 246
 252
 258
 264
 270
 276
 282
 288
 294
 300

Ninja’d, darn it. :slight_smile:

6 Likes