mmag

ハマったことメモなど

Elixirでループ使って関数定義しようとしてハマった

例えば、

defmodule Greeting do
  Enum.each [:hello, :goodbye], fn (greeting) ->
    def unquote(greeting) do
      IO.puts unquote(greeting)
    end
  end
end

というもの。上手く使えばコード量がドチャクソ減って幸せになれるのですが、「invalid syntax in def :hello」というコンパイルエラーが出て ムッキー!!! ってなってた。原因は、unquote(greeting)の後に、()が無いこと。

なので、こっちは動きます。

defmodule Greeting do
  Enum.each [:hello, :goodbye], fn (greeting) ->
    def unquote(greeting)() do
      IO.puts unquote(greeting)
    end
  end
end