Lisp and Erlang Atoms, Ruby and Scheme Symbols. How useful are they?

前端 未结 13 1622
一个人的身影
一个人的身影 2020-12-12 18:08

How useful is the feature of having an atom data type in a programming language?

A few programming languages have the concept of atom or symbol to represent a consta

13条回答
  •  臣服心动
    2020-12-12 18:49

    Atoms are like an open enum, with infinite possible values, and no need to declare anything up front. That is how they're typically used in practice.

    For example, in Erlang, a process is expecting to receive one of a handful of message types, and it's most convenient to label the message with an atom. Most other languages would use an enum for the message type, meaning that whenever I want to send a new type of message, I have to go add it to the declaration.

    Also, unlike enums, sets of atom values can be combined. Suppose I want to monitor my Erlang process's status, and I have some standard status monitoring tool. I can extend my process to respond to the status message protocol as well as my other message types. With enums, how would I solve this problem?

    enum my_messages {
      MSG_1,
      MSG_2,
      MSG_3
    };
    
    enum status_messages {
      STATUS_HEARTBEAT,
      STATUS_LOAD
    };
    

    The problem is MSG_1 is 0, and STATUS_HEARTBEAT is also 0. When I get a message of type 0, what is it? With atoms, I don't have this problem.

    Atoms/symbols are not just strings with constant-time comparison :).

提交回复
热议问题