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

后端 未结 3 1598
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 00:31

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

Atoms are constants where their name is their own value. Some other lang

3条回答
  •  一个人的身影
    2020-12-30 00:49

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

提交回复
热议问题