从两个模块运行代码时,Erlang 进程给出 undef 错误

标签 erlang

我有两个文件,processescalc(根据形状计算面积)。我是 Erlang 的新手,现在,我只想运行 processes 文件,它创建进程并从 calc 文件/模块调用 area()。

代码如下:

计算器:

- module(calc).
- export([start/0, area/0]).
- import(io, [fwrite/1]).

start() ->
    % Pid = spawn(fun() -> loop(Args here) end), 
    PID = spawn(calc, area, []),
    io:fwrite("PID: ~w", [PID]).
    % PID ! {self(), {rectangle, 10, 20}},

area() ->
    receive
        {From , {rectangle, X, Y}} ->
            From ! {rectangle, X*Y};
        {From, {square, X}} ->
            io:fwrite("in the Square area!"),
            From ! {square, X*X}
    end,
    area().

进程.erl:

-module(processes).
-export([execute/0]).
-import(io,[fwrite/1]).
-import(calc, [area/0]).

execute() ->
    PID = spawn(processes, area, []),
    Square_Area = PID ! {self(), {square, 10}},
    receive
        {rectangle, Area} ->
            io:fwrite("Rectangle area: ~w", [Area]);
        {square, Area} ->
            io:fwrite("Square area: ~w", [Area]);
        Other ->
            io:fwrite("In Other!")
    end,
    io:fwrite("Yolo: ~w", [Square_Area]).

当我在编译并运行 processes.erl 文件后运行命令 processes:execute(). 时,出现以下错误:

=ERROR REPORT==== 4-Sep-2022::20:24:26.720042 ===
Error in process <0.87.0> with exit value:
{undef,[{processes,area,[],[]}]}

这是因为没有加载第二个文件还是我写错了命令?任何帮助将不胜感激!

最佳答案

让我们检查错误:它说

{undef, [{processes, area, [], []}]}

这意味着函数 area 没有参数 ([]) 没有在模块 processes 中定义 (undef) 。准确地说,该错误意味着这样的函数未从该模块导出

这是正确的。该函数定义在模块 calc 中,对吗?

所以,如果你改变......

PID = spawn(processes, area, []).

…到…

PID = spawn(calc, area, []).

……你应该没问题:)

ℹ 额外提示

  1. 您不需要导入任何东西(例如io:fwrite/1calc:area/0 来使用它们- 特别是,因为您以完全合格的方式使用它们)。 import 在 Erlang 中有不同的含义,在实践中,根本不推荐使用它。
  2. 对变量使用 Camel_Case 并没有错,但使用起来更惯用……
    • PascalCase 变量
    • snake_case 用于原子(包括函数和模块名称)
    • SCREAMING_SNAKE_CASE 用于宏

关于从两个模块运行代码时,Erlang 进程给出 undef 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73603640/

相关文章:

erlang - Erlang/OTP 到底是什么?

erlang - 实现神经网络的最佳编程语言是什么?

erlang - 理解 spawn 的返回值

erlang - 如何让 Rebar 在发布目录中运行 Common Test?

erlang - 在 Erlang 中将字符串转换为整数列表

Erlang 语法 - 为 Erlang 构建 Intellij IDEA 语言支持插件

erlang - Erlang 有完整的 REPL 吗?

Erlang编译: mixed of "HiPE object code" and "opcode"?

erlang - 如何在 Mnesia 中设置记录过期

erlang - 生成没有通用文件系统的远程进程