help with "->"

hello,

It seems “->” could be one head of Expr, but I always got tuple head when trying
:(:->, :a, :a)

I was trying to know a little more about “->” and searched the document & google with no luck.
I also searched source code and found :lambda
lam = Expr(:lambda, g.argnames, …

Still, not much helpful. So where is the Symbol “->” defined?

Thanks!

It is used for lambdas (aka anonymous functions): x -> x+ 2. So try something like :(a -> b) to get an Expr with ->.

2 Likes

yes, I do know :(a → b). As “->” is a head, could you write it in the form :(:->, …? Tks!

You can construct an expression using Expr, but that relies on internals which may (1) change, (2) be complicated, or in some cases (3) irrelevant. Do what @mauro3 suggested, and construct expressions using interpolation, eg :($(aexpr) -> $(bexpr))

thanks for the reply. I guess I just would like to know a little bit about the internals of “->”, or the source code.

If you are interested in internals, just use something like

julia> dump(:(a -> b))
Expr
  head: Symbol ->
  args: Array{Any}((2,))
    1: Symbol a
    2: Expr
      head: Symbol block
      args: Array{Any}((2,))
        1: LineNumberNode
          line: Int64 1
          file: Symbol REPL[39]
        2: Symbol b

to explore.

1 Like

Maybe this also: Base.Meta.@lower a -> b

2 Likes

If you quote a tuple you get a quoted tuple. If you want the first argument to be the head of an Expr, construct an Expr.

julia> Expr(:->, :a, :a)
:(a->a)
1 Like

from Meta.lower I see Expr(:->, …) is based on Expr(:method, …(julia v1.0)

Note that the contents of Expr nodes are not “internals”, they are part of the exported Julia API; it is often necessary to use them when writing macros, for example. Breaking changes to Expr nodes should not be made in the Julia 1.x timeline.

2 Likes

I am confused then; since they are documented under the “Documentation of Julia’s Internals” part of the manual.

That section is about the lowered form of the AST. The surface-syntax Expr nodes are documented in the metaprogramming section of the manual, though the documentation could be more complete. Because macros directly access the surface-syntax Expr type, it is part of the API that cannot be changed without breaking valid user code.

1 Like

Thanks. So plain vanilla user-written macros are not supposed to encounter or expect lowered forms?

Lowering happens after macro expansion.

1 Like

Later in that section there is a list of surface AST forms, but I agree it would make sense to move it to the metaprogramming chapter.

1 Like