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

前端 未结 13 1623
一个人的身影
一个人的身影 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:44

    You're actually not right in saying python has no analogue to atoms or symbols. It's not difficult to make objects that behave like atoms in python. Just make, well, objects. Plain empty objects. Example:

    >>> red = object()
    >>> blue = object()
    >>> c = blue
    >>> c == red
    False
    >>> c == blue
    True
    >>> 
    

    TADA! Atoms in python! I use this trick all the time. Actually, you can go further than that. You can give these objects a type:

    >>> class Colour:
    ...  pass
    ... 
    >>> red = Colour()
    >>> blue = Colour()
    >>> c = blue
    >>> c == red
    False
    >>> c == blue
    True
    >>> 
    

    Now, your colours have a type, so you can do stuff like this:

    >>> type(red) == Colour
    True
    >>> 
    

    So, that's more or less equivalent in features to lispy symbols, what with their property lists.

提交回复
热议问题