elixir icon indicating copy to clipboard operation
elixir copied to clipboard

Wrong if/2 macro in Elixir metaprogramming documentation

Open Equiel-1703 opened this issue 1 year ago • 1 comments

I am studying metaprogramming in Elixir and found a wrong code snippet for the implementation of the if/2 macro in the official docs (https://hexdocs.pm/elixir/macros.html):

Image

The if/2 macro is implemented using unquote/1 in both the clause and expression variables. Here is the correct code from the Kernel module:

defmacro if(condition, clauses) do
    build_if(condition, clauses)
  end

  defp build_if(condition, do: do_clause) do
    build_if(condition, do: do_clause, else: nil)
  end

  defp build_if(condition, do: do_clause, else: else_clause) do
    annotate_case(
      [optimize_boolean: true, type_check: :expr],
      quote do
        case unquote(condition) do
          x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(else_clause)
          _ -> unquote(do_clause)
        end
      end
    )
  end

I know this is a small mistake, but for me as a learner this was very misleading. The documentation doesn't explain very well how the unquote/1 function is used in real scenarios. I felt like the examples shown were a bit too unrealistic. And then when this wrong code snippet was shown things got even more confusing for me.

Equiel-1703 avatar May 19 '25 02:05 Equiel-1703

Hi @Equiel-1703 , thanks for reporting 💜 This has already been fixed in main by https://github.com/elixir-lang/elixir/pull/14476, so I'm going to clause the issue.

sabiwara avatar May 19 '25 05:05 sabiwara