3 ms·
I don't really like the dogma of "don't use x". It's much better to just show examples of when macros are useful and when they're not. I got burnt trying to do
by dqv 5y ago
I don't really like the dogma of "don't use x". It's much better to just show examples of when macros are useful and when they're not. I got burnt trying to do tenancy. At one point I was like "I'll use the process dictionary", but had it hammered into my brain from everywhere "don't use the process dictionary!" It turns out the process dictionary was exactly correct for my use case. This is just an example of one of those dogmas that needs to be more like "x is a bad use case if you're trying to do y, but not if you're trying to do z".
Here's an example of when macros are very useful:
months = Enum.map(~w(january february march april may june july august september october november december)a, fn month ->
{month, to_string(month)}
end)
def to_month(arg)
for {atom, _string} <- months do
def to_month(unquote(atom)) do
{:ok, unquote(atom)}
end
end
for {atom, string} <- months do
def to_month(unquote(string)) do
{:ok, unquote(atom)}
end
end
def to_month(_), do: :error
I can already hear someone saying "well you can do the same with functions" but it starts to get ugly and you're now doing these conversions at run time. A function-oriented approach would need guard clauses and run-time checks of an element being in a list of atoms OR strings then possibly run-time conversion of the strings to atoms. Or you can just use macros.