等同于C枚举的Common Lisp [英] Common Lisp equivalent to C enums

查看:97
本文介绍了等同于C枚举的Common Lisp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在尝试学习一些Lisp(通用Lisp),我想知道是否有一种方法可以像给C一样通过枚举来给常数命名。

I'm trying to learn some Lisp (Common Lisp) lately, and I wonder if there is a way to give constant numbers a name just like you can do in C via enums.

我不需要枚举的全部功能。最后,我只想拥有快速的可读代码。

I don't need the full featureset of enums. In the end I just want to have fast and readable code.

我已经尝试了全局变量和小函数,但这总是带有一个性能下降。只需将数字插入代码中总是更快。

I've tried globals and little functions, but that always came with a degration in performance. Just plugging the numbers into the code was always faster.

推荐答案

在Lisp中进行枚举的正常方法是使用符号。符号会被插入(用指向符号表中条目的指针代替),因此它们与整数一样快,并且与其他语言中的枚举常量一样可读。

The normal way to do enumerations in Lisp is to use symbols. Symbols get interned (replaced with pointers to their entries in a symbol table) so they are as fast as integers and as readable as enumerated constants in other languages.

C您可能会这样写:


enum {
   apple,
   orange,
   banana,
};

在Lisp中,您可以只使用'apple '橙色'香蕉直接。

In Lisp you can just use 'apple, 'orange and 'banana directly.

如果需要枚举的类型,则可以使用 deftype

If you need an enumerated type, then you can define one with deftype:

(deftype fruit () '(member apple orange banana))

,然后您可以在声明中使用水果类型 typep typecase 等,,您可以编写专门用于

and then you can use the type fruit in declare, typep, typecase and so on, and you can write generic functions that specialize on that type.

这篇关于等同于C枚举的Common Lisp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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