lisp - Common Lisp 中的循环列表

标签 lisp common-lisp circular-list

我正在使用可视化编程环境进行基于 CL 的音乐创作。我正在尝试创建一个函数,当给出 3 个元素 (1 2 3) 时将返回 1、2、3、1、2、3 等,每次评估时返回一个数字。 Common Lisp a Gentle Introduction 一书简要提到可以使用锐等号表示法创建循环列表,但没有详细说明如何使用它们。 请记住,我可以使用专门为此设计的对象在程序中插入实际的 Lisp 代码。

最佳答案

CL-USER 3 > (defun circular (items)
              (setf (cdr (last items)) items)
              items)
CIRCULAR

CL-USER 4 > (setf *print-circle* t)
T

CL-USER 5 > (circular (list 1 2 3))
#1=(1 2 3 . #1#)

例子:

CL-USER 16 > (setf c1 (circular (list 1 2 3)))
#1=(1 2 3 . #1#)

CL-USER 17 > (pop c1)
1

CL-USER 18 > (pop c1)
2

CL-USER 19 > (pop c1)
3

CL-USER 20 > (pop c1)
1

还有:

CL-USER 6 > '#1=(1 2 3 . #1#)
#1=(1 2 3 . #1#)

添加了一些 CLOS:

(defclass circular ()
  ((items :initarg :items)))

(defmethod initialize-instance :after ((c circular) &rest initargs)
  (setf (slot-value c 'items) (circular (slot-value c 'items))))

(defmethod next-item ((c circular))
  (prog1 (first (slot-value c 'items))
    (setf (slot-value c 'items)
          (rest (slot-value c 'items)))))

CL-USER 7 > (setf circ1 (make-instance 'circular :items (list 1 2 3)))
#<CIRCULAR 40200017CB>

CL-USER 8 > (next-item circ1)
1

CL-USER 9 > (next-item circ1)
2

CL-USER 10 > (next-item circ1)
3

CL-USER 11 > (next-item circ1)
1

CL-USER 12 > (next-item circ1)
2

关于lisp - Common Lisp 中的循环列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16678371/

相关文章:

lisp - Lisp 中值的内存表示

lisp - 普通LISP加法程序

java - 破解编码面试循环链表

lisp - 普通口齿不清 : Beginner's trouble with funcall

lisp - 在 Emacs Lisp 中,如何获得单个哈希键?

lisp - 从 SLIME 运行时无法找到包,但从命令行可以

lisp - Common Lisp 中的跨包 defgeneric/defmethod?

lisp - 修改 Lisp 函数而不重写它?

java - 我可以使用 java.util.LinkedList 构造循环/循环链表吗?

algorithm - 两个循环列表之间的最小编辑距离?