gpt4 book ai didi

ruby - Lisp 和 Erlang 原子、Ruby 和 Scheme 符号。它们有多有用?

转载 作者:数据小太阳 更新时间:2023-10-29 06:20:07 26 4
gpt4 key购买 nike

在编程语言中具有原子数据类型的特性有多大用处?

一些编程语言有原子或符号的概念来表示各种常量。我遇到的语言(Lisp、Ruby 和 Erlang)之间存在一些差异,但在我看来,一般概念是相同的。我对编程语言设计很感兴趣,我想知道原子类型在现实生活中有什么值(value)。没有它,Python、Java、C# 等其他语言似乎也做得很好。

我没有 Lisp 或 Ruby 的实际经验(我知道语法,但没有在实际项目中使用过)。我已经足够使用 Erlang 来适应那里的概念。

最佳答案

Atoms are literals, constants with their own name for value. What you see is what you get and don't expect more. The atom cat means "cat" and that's it. You can't play with it, you can't change it, you can't smash it to pieces; it's cat. Deal with it.

I compared atoms to constants having their name as their values. You may have worked with code that used constants before: as an example, let's say I have values for eye colors: BLUE -> 1, BROWN -> 2, GREEN -> 3, OTHER -> 4. You need to match the name of the constant to some underlying value. Atoms let you forget about the underlying values: my eye colors can simply be 'blue', 'brown', 'green' and 'other'. These colors can be used anywhere in any piece of code: the underlying values will never clash and it is impossible for such a constant to be undefined!

取自 http://learnyousomeerlang.com/starting-out-for-real#atoms

话虽这么说,原子最终在语义上更适合在其他语言将被迫使用字符串、枚举或定义的地方描述代码中的数据。它们更安全、更友好,可用于获得类似的预期结果。

关于ruby - Lisp 和 Erlang 原子、Ruby 和 Scheme 符号。它们有多有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4874744/

26 4 0