![](/img/trans.png)
[英]Elixir in Emacs: UndefinedFunctionError: module is not available
[英]Elixir - Calling / Invoking Macros - UndefinedFunctionError
為什么靈葯報告UndefinedFunctionError
調用使用宏時Module.macroName
語法在.exs
文件? 我似乎只能調用宏,如果我有另一個調用宏的函數,我調用函數而不是宏。
下面的代碼演示了這個
defmodule Sample do
defmacro doIt(expression) do
quote do
IO.puts unquote(expression)
end
end
def doFunc(e), do: doIt(e)
end
Sample.doFunc "Hello World via Function" # Works fine
Sample.doIt "Hello World from Macro!" # Gives error
產量
Hello World via Function
** (UndefinedFunctionError) undefined function: Sample.doIt/1
Sample.doIt("Hello World from Macro!")
(elixir) lib/code.ex:307: Code.require_file/2
Elixir文檔示例使用iex
,而不是在.exs
文件中調用宏。 即使是上面的代碼,如果我們刪除對Sample.doIt
調用並將其加載到iex
,然后調用Sample.doIt
工作正常。
E:\elixir>iex hello.exs
Hello World via Function
Interactive Elixir (1.0.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> require Sample
nil
iex(2)> Sample.doIt "Hello"
Hello
:ok
iex(3)>
如果我嘗試在上面的文件中require Sample
,如下所示
defmodule Sample
... rest of stuff as shown above ...
end
require Sample
Sample.doFunc "Hello World via Function"
Sample.doIt "Hello World from Macro!"
我收到錯誤
** (CompileError) hello.exs:11: module Sample is not loaded but was defined. This happens because you are trying to use a module in the same context it is defined. Try defining the module outside the context that requires it.
(stdlib) lists.erl:1352: :lists.mapfoldl/3
(stdlib) lists.erl:1353: :lists.mapfoldl/3
像往常一樣,在使用宏之前需要一個模塊來向編譯器表明編譯模塊的順序:
defmodule Other do
def run do
require Sample
Sample.doFunc "Hello World via Function"
Sample.doIt "Hello World from Macro!"
end
end
Other.run # => Hello World via Function
# Hello World from Macro!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.