用宏清理重复代码?

时间:2016-08-17 16:09:52

标签: elixir ecto

我有以下查询,可以看出,它们需要大量的复制/粘贴。

有一种快速而优雅的方法可以通过元编程来解决这个问题吗?

no matching function for call to 'QQmlListProperty<TTimingDriver>::QQmlListProperty(TTiming*, QList<TTimingDriver*>*, int (TTiming::*)(QQmlListProperty<TTimingDriver>*), TTimingDriver* (TTiming::*)(QQmlListProperty<TTimingDriver>*, int))'
 return QQmlListProperty<TTimingDriver>(this, &m_drivers, &TTiming::count, &TTiming::driverAt);

2 个答案:

答案 0 :(得分:1)

未经测试和丑陋,但我会说:

def days_of_week do
  days = ~w(monday tuesday wednesday thursday friday saturday sunday)a

  for {day, index} <- Enum.with_index(days) do
    {day, quote do fragment("count(extract(dow FROM ?) = ? OR null)", c.inserted_at, unquote(index)) end}
  end
end
defmacro by_day_of_week,
    do: quote do: %{unquote_splicing(days_of_week)}

它产生代码:

"%{
  monday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 0),
  tuesday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 1), 
  wednesday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 2), 
  thursday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 3), 
  friday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 4), 
  saturday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 5), 
  sunday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 6)
}"

因此与第二个。

答案 1 :(得分:0)

如果你真的想用宏做,你可能会这样做。

Running example

defmodule MapUtils do
 defmacro spam(numbers) do
    quote do
      Enum.reduce(unquote(numbers), %{}, fn (elem, acc) -> 
        Map.put(acc, elem, elem)
      end)
    end
  end
end

非常感谢Chris Wende