【问题标题】:How to define functions in iex main scope?如何在 iex 主范围内定义函数?
【发布时间】:2015-12-11 16:19:33
【问题描述】:

在文件 ~/.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 中有没有办法做到这一点?

【问题讨论】:

    标签: elixir elixir-iex


    【解决方案1】:

    这是.iex.exs 机制的一个已知限制。 .iex.exs 文件在与您在 shell 中键入内容的上下文相同的上下文中进行评估:基本上,IEx 加载 .iex.exs 就像您在 shell 中键入它一样。

    在 Elixir 中,您不能定义一个模块并将其导入到相同的上下文中(例如,您不能在 shell/文件中定义一个模块然后再导入它),这就是那里发生的事情。

    我的建议是:在 .iex.exs 中定义模块并将其别名(仍在 .iex.exs 中)为一个非常短的名称。例如在.iex.exs:

    defmodule MyModule do
      def foo, do: :foo
    end
    
    alias MyModule, as: M
    

    然后,在 shell 中:

    iex> M.foo
    :foo
    

    这不是最优的,但现在,它可能是一种妥协。

    【讨论】:

    • 这就是我最终做的事情。我希望有一天 Elixir 能够在 iex 中定义模块之外的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多