Snelle referentie

Elixir Metaprogrammeren Spiekbrief

Korte handleiding voor Elixir metaprogrammeren: __ENV__, __MODULE__, __CALLER__, Kernel.SpecialForms, quote en unquote macro's.

· Gepubliceerd

Snelle syntaxisreferentie voor metaprogrammeren, AST-inspectie en macro's in Elixir.

🔗 Gerelateerd: Elixir Programmeertaal Spiekbrief

Speciale vormen en pseudovariabelen (Special Forms & Pseudo-Variables)

Kernconstructies gedefinieerd in Kernel.SpecialForms:

__DIR__     # Absoluut pad naar directory van huidig bestand
__MODULE__  # Huidige modulenaam atom
__ENV__     # Struct van huidige compilatie-omgeving (Macro.Env)
__CALLER__  # Omgevingsstruct van de macro-aanroeper

Compilatie-omgeving inspecteren (ENV)

# Velden in compilatie-omgeving inspecteren
Map.keys(__ENV__)
# => [:__struct__, :aliases, :context, :context_modules, :export_vars, :file,
#     :function, :functions, :lexical_tracker, :line, :macro_aliases, :macros,
#     :module, :requires, :vars]

# Definities in aanroepende module inspecteren
__CALLER__.module |> Module.definitions_in() |> IO.inspect()

Quotes, AST en dynamische dispatch (Quotes, AST & Dynamic Dispatch)

# Abstracte syntaxistree (AST) genereren
quote do: 1 + 2
# => {:+, [context: Elixir, import: Kernel], [1, 2]}

# Unquote binnen quotes
number = 10
quote do: 1 + unquote(number)

# Dynamische functie-aanroep
apply(Enum, :reverse, [[1, 2, 3]])
# => [3, 2, 1]

Verwante onderwerpen