Chaining of functions

It would be great if the chaining operator supported something like:

my_path |> joinpath(_, "my_file.jld")

so I can avoid

my_path |> x -> joinpath(x, "my_file.jld")

i think R supports this in the %>% operator using .

1 Like

I thought about exactly the same thing. The above example is actually pretty simple and may be rewritten in a pretty readable:

joinpath(my_path, "my_file.jld")

But if there are more functions, code becomes pretty messy, e.g.:

foo(bar(baz(x)), y)

Which could have been:

baz(x) |> bar(_, y) |> foo

Which looks more more clear for me. At least, it doesn’t require parenthesis highlighting to parse the code by eye :slight_smile:

To give some more background, many other languages include similar means, e.g. Haskell has a dot operator and Clojure has -> macro together with short syntax for lambdas (e.g. #(bar % y)). So having something like this in Julia might be beneficial for code readability.

However, if we don’t have it in the language itself, we still have macros that can do literally anything with code in question. Some time ago I experimented with a macro (although I don’t remember where the code for it is) that allowed to chain functions like this:

@c foo bar(_, y) baz

The main disadvantage of this macro for me was that users reading my code may be unfamiliar with the syntax and thus may be better with more traditional syntax.

1 Like

thanks for elaborating.

Have a look at package Lazy.jl. I think i does exactly what you’re looking for.

# @as lets you name the threaded argmument
@as _ x f(_, y) g(z, _) == g(z, f(x, y))
2 Likes

thanks, seems to be a really interesting package.

btw: there is a @_ macro which is equivalent to @as _

@_ x f(_, y) g(z, _) == g(z, f(x, y))

1 Like