I’ve been playing with Elixir over the last couple of months and as a newbie I’m still finding things that totally trample over my preconceptions. For example, I was experimenting with tidying up some code, writing the equivalent of a Ruby function with a block (but as a macro), nothing really that heading scratching except … well, this little piece of code:

defmacro descendant(e_name, do: block) do quote do fn (_e, _a, meta) -> Enum.any?(meta[:path], fn (unquote(e_name)) -> unquote(block) end) end end end

Pay attention to the fn (unquote(e_name)) in Enum.any?. This is an anonymous function that is called once for each item in the collection meta[:path] passed as the the first parameter to Enum.any?, hence in this case a keyword list with an ascending path of HTML element names. So for every string in the path the function will receive that value e.g. The value of meta[:path] might be [“html”, “head”, “p”] so the anonymous function would be called 3 times, once for each string. But here I seem to be passing in a value to supply to the anonymous function rather than use the value from the list… what?!! It’s only “clear” what’s happening when you see how this is used:

def compile_descendant_selector( _type, attr) do descendant(e) do has_attribute?(elem(e, 1), attr) end end

Notice in this function that nowhere do I declare or set e to a value, but I can still reference e within the supplied body of the macro! Yup, the parameter is defined within the macro body and so this happily compiles and runs. Whilst this works only because it is a macro, the fact that it has all the feeling of a function and that nothing is never explicitly assigned within the macro makes this seem like utter voodoo on first glance!!