如何在elixir上生成函数?

时间:2017-04-19 02:08:06

标签: elixir

我试图做elixir分布式任务的this指南,但我遇到了这个例外的麻烦:

** (EXIT from #PID<0.62.0>) an exception was raised:
    ** (BadFunctionError) expected a function, got: #Function<20.50752066/0 in :erl_eval.expr/5>
        :erlang.apply/2

然后提出这个:

[error] Error in process #PID<8796.100.0> on node :"silver@192.168.0.25" with exit value:
{{:badfun, #Function<20.50752066/0 in :erl_eval.expr/5>},
 [{:erlang, :apply, 2, []}]}

我使用machine one启动iex --name gold@192.168.0.20 --cookie foo并运行:

iex(gold@192.168.0.20)1> defmodule Hello do
iex(gold@192.168.0.20)1>   def world, do: IO.puts "hello world"
iex(gold@192.168.0.20)1> end

然后使用machine two启动iex --name silver@192.168.0.25 --cookie foo 并尝试生成Hello.world函数:

Node.spawn_link :"silver@192.168.0.25", fn -> Hello.world end

此后,显示错误。

更多信息:

machine one Node.list返回[:"silver@192.168.0.25"]

machine two Node.list返回[:"gold@192.168.0.20"]

epmd -names上的

machine one返回:

epmd: up and running on port 4369 with data:
name gold at port 37295
epmd -names上的

machine two返回:

epmd: up and running on port 4369 with data:
name gold at port 39738

2 个答案:

答案 0 :(得分:1)

首先,您的示例存在问题。你说

I start machine one with: iex --name gold@192.168.0.20 --cookie foo and run:

iex(silver@192.168.0.25)1> defmodule Hello do
iex(silver@192.168.0.25)1>   def world, do: IO.puts "hello world"
iex(silver@192.168.0.25)1> end

iex会话在银牌上,你以后会开始。

此外,epmd列表没有显示您编写Hello模块的silver@192.168.0.25的条目。

我在同一台机器上的两个iex会话上试过这个并且它工作正常。

以下是您应采取的步骤:

  1. 使用名称和机器的IP地址
  2. 启动第一个iex会话
  3. 使用名称及其机器的IP地址
  4. 打开第二个iex部分
  5. 在其中一个iex会话中键入`Node.connect:“另一台机器的名称@ ipaddress”
  6. 在一台计算机上定义Hello模块
  7. 在另一台机器上执行spawn_link。

答案 1 :(得分:1)

终于找到了答案:

  

您需要保证它们运行完全相同的Erlang版本。对于生产,我们通常在一台机器上编译代码并将其分发,以保证在任何地方都使用相同的版本。

如果您不能保证相同的版本,那么您必须避免使用匿名函数并始终使用命名版本,例如:

Node.spawn_link :"silver@192.168.0.25", &Hello.world/0
Node.spawn_link :"silver@192.168.0.25", Hello, :world, []