Arian
Arian

Reputation: 56

Erlang - Help in understanding basic erlang code

I have stumbled upon a piece of code that I can't quite understand. It looks like this:

% spawn process which waits for a message and prints it
Pid = spawn(fun() ->
  receive
    X -> io:fwrite("I received: ~p~n", [X])
  end
end),
% send a message to the new process
Pid ! {message, "Hello"}.

In the last line, is "message" an atom that is defined in the module? I can't really understand that part.

My attempt at understanding it would be this: we save things in tuples where the first element is descriptive of the content. For example: {celsius, 55}. What is less clear is that the atom message is not defined in the module. Do you have to define it? No declaration is necessary so I guess you don't have to define the atom before using it. Am I correct?

Thanks for the help!

The code is from here.

Upvotes: 3

Views: 125

Answers (3)

bxdoan
bxdoan

Reputation: 1369

Basically, You understood right. You can use everything atom you want, they are not defined anywhere. Except some reserved words in Erlang:

receive, case, if, throw, catch, else...

Upvotes: 1

Adhiyaman
Adhiyaman

Reputation: 1

Atoms can be used at will, Every unique atom will be entered into an atom table. The atom table is never garbage collected. The default max atom count for an ERTS instance is 1048576. This limit can be increased by using +t option on startup. more information regarding limits. For diagnostic purpose you can use erlang:memory(atom) - elrang:memory(atom_used) calls, to ensure you haven't exhausted the available atoms. If the atoms are exhausted it leads to immediate termination of the ERTS without warning.

Upvotes: 0

Derek Brown
Derek Brown

Reputation: 521

Correct- you just use atoms at will. They're not "defined" anywhere.

Upvotes: 4

Related Questions