Dot syntax for anonymous functions

Hi,
in mathematics we use this syntax of • to represent (anonymous) functions. For instance ||•|| is then equivalent to writing x |–> ||x||.

My question is, is there such syntax in julia?

If not, I’d love to see the, for instance, bullet operator handle this shorthand in a future release. Do you agree?

See https://github.com/JuliaLang/julia/pull/24990

5 Likes

Oh okay, thanks.

They seem to have problems regarding how the “_” syntax should be used, more important, their representation does not seem well defined anymore, as for instance

A,B,C = rand(5), rand(5), rand(5)
maximum(_[1], [A,B,C])

could mean maximum(x -> x[1], [A,B,C]), but also x -> maximum(x[1], [A,B,C]), hence where x is itself is an array of functions.

Therefore I just wanted to implement my own macro as follows:

  • the replacement would be achieved by writing @x(:x + 3), meaning x -> x + 3
  • similarly @x(f(:x, :y, 7, :x)) means (x,y) -> f(x, y, 7, x)

We then can automatically create problem cases like the ones above and by using composition or |> we can create arbitrary complex functions, like @x(f(:x, :y, 7)) |> @x(:x^2) |> @x(print("The solution is $(:x).")).

How do I write such a macro and do you have a neater syntax idea?

By writing

macro x(f)
    f.args = replace(f.args, :(:x) => :x)
    return :(x -> $f)
end

I got a little of the functionality. One can for instance do this

julia> rdim = @x(rand(5, :x)) # 5 × x random arrays

julia> rdim(1)
5×1 Array{Float64,2}:
 0.9939828371497994
 0.773338508907532
 0.8633776655992123
 0.22892379107363436
 0.39529414038536226

julia> rdim(3)
5×3 Array{Float64,2}:
 0.146573  0.108516  0.327287
 0.105098  0.111566  0.942984
 0.713338  0.69219   0.877718
 0.243916  0.561024  0.569137
 0.787741  0.970282  0.0878656

You can find examples on this forum (search for partial application macro or something similar), and even some packages like

(I think there are others, but I can’t recall the names).

3 Likes