简体   繁体   English

未定义函数生成函数

[英]undefined function Generating Functions

I am trying to generate 100 functions using metaprogramming in Elixir我正在尝试使用 Elixir 中的元编程生成 100 个函数

I want the function to return a value that is computed during compile time我希望函数返回一个在编译时计算的值

def func(0) do
  "you have 0 chances"
end

def func(1) do
  "you have 1 chances"
end

...

def func(100) do
  "you have 100 chances"
end

My first attempt was我的第一次尝试是

0..100 |> Enum.each fn val ->
    def func(unquote(val)) do
        val_string = to_string(unquote(val))
        "you have " <> val_string <> " chances"
    end
end

But I have reason to believe that this just returns 100 functions that aren't evaluated during compile time.但我有理由相信这只会返回 100 个在编译时未评估的函数。

Finally I tried this最后我试过这个

0..100 |> Enum.each fn vol ->
  defmacro func(unquote(vol) = vol) do
    quote do
      "you have " <>  unquote(vol) <> " chances" |> unquote
    end
  end
end

but when I require the file and I call func(1) in iex I get但是当我需要该文件并在 iex 中调用 func(1) 时,我得到

** (CompileError) iex:2: undefined function func/1

Is my defmacro logic correct in the first place?我的 defmacro 逻辑首先正确吗? Any idea what I could be doing wrong.知道我可能做错了什么。

First, just in case, you can acheive the same thing with a regular function, without metaprogramming:首先,为了以防万一,您可以使用常规函数实现相同的功能,而无需元编程:

def func(num) when is_integer(num) and 0 <= num and num <= 100 do
  "you have #{num} chances"
end

But if you are practising metaprogramming, remember that you need to unquote any of the compile-time variables:但是如果您正在练习元编程,请记住您需要unquote任何编译时变量:

for i <- 0..100 do
  def func(unquote(i)) do
    "You have #{unquote(i)} chances"
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM