Search code examples
syntaxerlangelixir

Why is useful to have an atom type (in elixir, erlang)?


According to http://elixir-lang.org/getting-started/basic-types.html#atoms:

Atoms are constants where their name is their own value. Some other languages call these symbols

I wonder what is the point of having an atom type. Probably to help build a parser or for macros? But in everyday use how does it help the programmer?

BTW: I've never used elixir or erlang, just note it exist (also in kdb)


Solution

  • I think that one of the most common usage in erlang is to tag variables and messages, with the benefit of fast comparison (pattern match) as mipadi says.

    For example you write a function that may fail depending on parameters provided, the status of connection to a server, or any reason. A very frequent usage is to return a tuple {ok,Value} in case of success, {error,Reason} in case of error. The calling function will have the choice to manage only the success case coding {ok,Value} = yourModule:yourFunction(Param...). Doing this it is clear that you consider only the success case, you extract directly the Value from the function return, it is fast, and you don't have to share any header with yourModule to decode the ok atom.

    In messages you will often see things like {add,Key,Value}, {delete,Key},{delete_all}, {replace,Key,Value}, {append,Key,Value}... These are explicit messages, with the same advantages as mentioned before: fast,sensible,no share of header...