gpt4 book ai didi

c - 数据类型 : symbol vs enumerated?

转载 作者:太空宇宙 更新时间:2023-11-03 18:46:15 26 4
gpt4 key购买 nike

我想知道symbol之间有什么区别和关系?和 enumerated类型?

我在阅读符号类型的第一个链接时产生了我的问题

In the most trivial implementation, they (symbol types) are essentially named integers (e.g. the enumerated type in C).

我按照第二个链接阅读了枚举类型,但无法弄清楚它们之间的区别和关系。

例如,它们似乎同时存在于 Common Lisp here 中。和 here ,但我的问题不限于 CL,两篇维基百科文章也不限于此。

谢谢。

最佳答案

假设我们有几种文本样式:boldìtalicthinregular。现在我们有一个绘制一些文本的函数:

(defun draw-text-string (text style stream)
...)

整数枚举

我们如何传递样式信息?我们可以将它们编码为数字:

(defconstant +regular+ 0)
(defconstant +thin+ 1)
(defconstant +bold+ 2)
(defconstant +italic+ 3)

我们可以将它们编码为位:

(defconstant +regular+ #b0001) ; 1
(defconstant +thin+ #b0010) ; 2
(defconstant +bold+ #b0100) ; 4
(defconstant +italic+ #b1000) ; 8

通常,枚举 类型将这些映射隐藏在类型声明之后。

当我们调用绘图函数时,我们以某种方式传递这些数字:

(draw-text-string "hello" +thin+ *standard-output*)

我们可以这样写:

(draw-text-string "hello" 1 *standard-output*)

如果我们有位编码,我们也可以传递一个集合:

(draw-text-string "hello" (logxor +thin+ +italic+) *standard-output*)
(draw-text-string "hello" 10 *standard-output*)

优点是编码非常紧凑。如果我们调试程序,在 Lisp 中我们会看到数字。在静态类型语言中,调试器可以访问类型信息并将值显示为名称。

这种枚举通常不会在 Lisp 中完成 - 仅当需要与外部例程接口(interface)时才使用,通常遵循 C 约定。

作为符号的枚举值

在 Lisp 中,也可以使用符号来达到这一目的。作为单个符号或作为符号列表。这里的符号本身就是值,它们不用作变量。

(draw-text-string "hello" 'thin *standard-output*)
(draw-text-string "hello" '(thin italic) *standard-output*)

在 Common Lisp 中,我们经常使用自评估关键字符号。这样我们就不需要考虑包( namespace )。

(draw-text-string "hello" :thin *standard-output*)
(draw-text-string "hello" '(:thin :italic) *standard-output*)

两者的优点是我们传递命名对象(符号),这在 Lisp 系统调试期间更容易理解。缺点是我们现在可以传递符号列表,这比数字或位 vector 之类的东西效率稍低。

然后通常通过 MEMBER 完成运行时类型检查类型。

关于c - 数据类型 : symbol vs enumerated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25170828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com