Search code examples
erlang

Erlang process gives undef error when running code from two modules


I have two files, processes and calc(that calculates the area of depending upon the shape). I am new at Erlang and right now, I just want to run processes file which create the process and invokes the area() from the calc file/ module.

The code is as follows:

calc.erl:

- 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().

processes.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]).

When I run the command processes:execute(). after compiling and running the processes.erl file, I get the following error:

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

Is this because the second file is not being loaded or am I writing wrong commands? Any help will be appreciated!


Solution

  • Let's check the error: It says

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

    That means that the function area with no arguments ([]) is not defined (undef) in the module processes. To be precise, what that error means is that such a function is not exported from that module.

    Which is correct. The function is defined in the module calc, right?

    So, if you change…

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

    …to…

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

    …you should be fine :)

    ℹ Extra Tips

    1. You don't need to import anything (like io:fwrite/1 or calc:area/0 in order to use them - particularly, since you're using them in a fully qualified manner). import in Erlang has a different meaning and, in practice, its usage is not recommended at all.
    2. Using Camel_Case for variables is not wrong, but it's more idiomatic to use…
      • PascalCase for variables
      • snake_case for atoms (including function and module names)
      • SCREAMING_SNAKE_CASE for macros