Lisp和Erlang原子,Ruby和方案符号。他们有多有用? [英] Lisp and Erlang Atoms, Ruby and Scheme Symbols. How useful are they?

查看:126
本文介绍了Lisp和Erlang原子,Ruby和方案符号。他们有多有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



一些编程语言有一个原子或符号的概念来表示一个常量排序。我遇到的语言(Lisp,Ruby和Erlang)之间有一些差异,但在我看来,一般概念是一样的。我对编程语言设计感兴趣,我想知道在现实生活中提供原子类型的价值是多少。我没有Lisp或Ruby的真实体验(我知道语法,但是避风港),但是其他的语言(如Python,Java,C#)在没有它的情况下似乎做的很好。



不用在真正的项目中)。我已经使用了Erlang来用于这个概念。

解决方案

一个简短的例子,说明如何操纵符号的能力更清楚的代码:(代码在Scheme中,Lisp的方言)。

  '(socrates plato aristotle))

(define(man?x)
(包含?men x))

(define(mortal?x)
(man?x))

;;测试

> (凡人?socrates)
=> #t

您可以使用字符串或整数常量来写这个程序。但符号版本具有一定的优势。系统中保证符号是唯一的。这使得比较两个符号比比较两个指针一样快。这显然比比较两个字符串要快。使用整型常量可以让人们写出无意义的代码,如:

 (define SOCRATES 1)
;; ...

(凡人?SOCRATES)
(凡人?-1);; ??

这个问题的详细答案可能在书中通用Lisp:符号计算的温柔介绍


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 constant of sorts. There are a few differences among the languages I have come across (Lisp, Ruby and Erlang), but it seems to me that the general concept is the same. I am interested in programming language design, and I was wondering what value does having an atom type provide in real life. Other languages such as Python, Java, C# seem to be doing quite well without it.

I have no real experience of Lisp or Ruby (I know the syntaxes, but haven't used either in a real project). I have used Erlang enough to be used to the concept there.

解决方案

A short example that shows how the ability to manipulate symbols leads to cleaner code: (Code is in Scheme, a dialect of Lisp).

(define men '(socrates plato aristotle))

(define (man? x) 
    (contains? men x))

(define (mortal? x) 
    (man? x))

;; test

> (mortal? 'socrates)
=> #t

You can write this program using character strings or integer constants. But the symbolic version has certain advantages. A symbol is guaranteed to be unique in the system. This makes comparing two symbols as fast as comparing two pointers. This is obviously faster than comparing two strings. Using integer constants allows people to write meaningless code like:

(define SOCRATES 1)
;; ...

(mortal? SOCRATES)
(mortal? -1) ;; ??

Probably a detailed answer to this question could be found in the book Common Lisp: A Gentle Introduction to Symbolic Computation.

这篇关于Lisp和Erlang原子,Ruby和方案符号。他们有多有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆