如何在 iex 主作用域中定义函数?
How to define functions in iex main scope?
在文件 ~/.iex.exs
中,我有一个定义了多个函数的模块,我想从 iex
shell 中调用这些函数而不使用模块名称前缀。
使用 import SomeModule
不起作用,我收到错误消息:
module SomeModule 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.
在 ~/.iex.exs
中有什么方法可以做到这一点吗?
这是 .iex.exs
机制的已知限制。 .iex.exs
文件在与您在 shell 中键入内容的上下文相同的上下文中进行评估:基本上,IEx 加载 .iex.exs
就像您在 [=29= 中键入它一样].
在 Elixir 中,你不能定义一个模块并在相同的上下文中导入它(例如,你不能在 shell/in 文件中定义一个模块然后再导入它),这就是那里正在发生。
我的建议是:在 .iex.exs
中定义模块并将其别名(仍在 .iex.exs
中)命名为一个非常短的名称。例如,在 .iex.exs
:
defmodule MyModule do
def foo, do: :foo
end
alias MyModule, as: M
然后,在 shell:
iex> M.foo
:foo
这不是最佳选择,但现在是一个可能的折衷方案。
在文件 ~/.iex.exs
中,我有一个定义了多个函数的模块,我想从 iex
shell 中调用这些函数而不使用模块名称前缀。
使用 import SomeModule
不起作用,我收到错误消息:
module SomeModule 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.
在 ~/.iex.exs
中有什么方法可以做到这一点吗?
这是 .iex.exs
机制的已知限制。 .iex.exs
文件在与您在 shell 中键入内容的上下文相同的上下文中进行评估:基本上,IEx 加载 .iex.exs
就像您在 [=29= 中键入它一样].
在 Elixir 中,你不能定义一个模块并在相同的上下文中导入它(例如,你不能在 shell/in 文件中定义一个模块然后再导入它),这就是那里正在发生。
我的建议是:在 .iex.exs
中定义模块并将其别名(仍在 .iex.exs
中)命名为一个非常短的名称。例如,在 .iex.exs
:
defmodule MyModule do
def foo, do: :foo
end
alias MyModule, as: M
然后,在 shell:
iex> M.foo
:foo
这不是最佳选择,但现在是一个可能的折衷方案。