Matching method argument types in Macro

Iam trying to build a macro for chaining operations which works like follow:

@chain vec |> map(x -> x^2) |> reduce(+, 0) |> first(6)

The macro should be able to paste the result of the evaluation of a chain element into the next expression on the position where the data types matches the first time. Iam not sure if this is possible because
I need to evaluate a part of the expression to get its type and find a method signature for the function which matches.

Does someone have an idea how to do that?
Thanks a lot for your help.

The short answer is that I think you may want @>>.

The longer answer is that you should write out the code you would have typed in to do this without the macro. Like so, I think:

@chain vec |> map(f) # --> map(f, vec)

The macro’s sole job is to convert the code on the left (ex1 = :(vec |> map(f))) into that on the right (ex2 = :(map(f, vec))). It can’t know the type of vec but doesn’t have to, that’s figured out when this output expression is executed. As would happen if you had typed it in.

Hi, thanks for the reply. You have partly answered my question because you said it’s not possible to determine the type by using the expression . My plan was to find the right spot for the argument by comparing the types and not use different macros for placing in first or last argument spot like lazy does:

@chain vec |> map(f) |> first(6)  # --> first(map(f, vec), 6)

No, this isn’t really possible. Macros only operate on syntax. They take in expressions and produce other expressions. What value those expressions have is not something the macro can observe (since it varies with context). Furthermore, it’s not clear how this would work in a case where a function has multiple methods with different types in different positions.

On the other hand, a placeholder like _ works really well, is completely unambiguous in the presence of multiple methods, and doesn’t require evaluating anything when the macro is run. I believe Lazy.jl provides that (but I’m on a phone right now and can’t test it).

1 Like