import - 如何在 Elixir 1.0.3 中引用函数中的模块变量而不引用其模块?在其父范围内?

标签 import module scope elixir

我想让 Elixir 1.0.3 中的一个函数引用其“父”范围内的一个变量。在这种情况下,它的父作用域是一个模块。

这是与我在上一个问题中使用的代码相同的代码:

defmodule Rec do
  def msgurr(text, n) when n <= 1 do
    IO.puts text
  end

  def msgurr(text, n) do
    IO.puts text
    msgurr(text, n - 1)
  end
end

如果我将其更改为以下内容:
defmodule Rec do
  counter = "done!"
  def msgurr(text, n) when n <= 1 do
    IO.puts text
    IO.puts Rec.counter
  end

  def msgurr(text, n) do
    IO.puts text
    msgurr(text, n - 1)
  end
end

它编译得很好,但如果我尝试 msgurr 函数,我会收到以下错误:
** (UndefinedFunctionError) undefined function: Rec.counter/0
    Rec.counter()
    recursion_and_import_test.exs:5: Rec.msgurr/2

我还尝试了以下方法:
defmodule Rec do
  counter = "done!"
  def msgurr(text, n) when n <= 1 do
    import Rec
    IO.puts text
    IO.puts Rec.counter
  end

  def msgurr(text, n) do
    IO.puts text
    msgurr(text, n - 1)
  end
end

不过,我在这里收到编译时警告:
➜ ubuntu elixirc recursiontest.exs
recursion_and_import_test.exs:1:警告:重新定义模块 Rec
recursion_and_import_test.exs:2:警告:变量计数器未使用
recursion_and_import_test.exs:4:警告:未使用的导入记录

当我尝试使用 msgurr 函数时:

➜ ubuntu iex
Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:8:8] [async-threads:10] [kernel-poll:false]
Interactive Elixir (1.0.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> import Rec
nil
iex(2)> Rec.msgurr("blah", 3)
blah
blah
blah
** (UndefinedFunctionError) undefined function: Rec.counter/0
    Rec.counter()
    recursiontest.exs:6: Rec.msgurr/2

我似乎无法将我自己的变量从模块导入到该模块内的函数中。

我已经查看了导入文档,但我似乎无法从中理解如何做这种事情。我应该检查 Erlang 文档吗?

最佳答案

您将模块与对象混淆了。

Rec.counter 

总是指 Rec Module 中的函数。这就是错误消息告诉您的内容,他们找不到该功能。模块不能像你想象的那样有变量。

模块可以有属性。虽然可能会捏造想要的东西
使用模块属性,如果你想使用 Rec.counter 引用它,你应该只创建一个返回常量的函数。
def counter do
  "done!"
end

还有更多关于模块属性 here ,但如果你想能够在 Elixir 中思考,你需要开始思考“函数而不是变量”。

关于import - 如何在 Elixir 1.0.3 中引用函数中的模块变量而不引用其模块?在其父范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841449/

相关文章:

java - 如何从 Intellij IDEA 中的类创建 .jar 库

module - 如何使用 Phoenix 项目的 lib/文件夹中定义的模块?

python-3.x - 使用生成的变量,其值在一个函数中分配给另一个函数

perl - 如何有条件地在 Perl 中导入包?

hadoop - sqoop导入成功,但配置单元显示表看不到表

python - 在python中导入文本文件

css - Yii:在模块级别集成 CSS 文件

Java 开关 : variable declaration and scope

javascript - JavaScript 闭包的一个包罗万象的定义

Python:导入文件夹的符号链接(symbolic link)