【发布时间】:2015-05-04 16:09:58
【问题描述】:
我想让 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 文档吗?
【问题讨论】:
标签: import module scope elixir