common-lispclos

Can I make a class iterable in Common Lisp?


I'm wondering how, if possible, I can make a custom class iterable, such that SEQUENCE functions and macros would work on it.

Something like

(loop for x in instance-of-my-custom-class
      do (print x))

(sort instance-of-my-custom-class #'<)

(aref instance-of-my-custom-class 3)
;; etc...

Is this doable in Common Lisp? Is it normal?


Solution

  • The commenters have given me the answer, so I'm typing it up here. The README of this repository: https://github.com/Shinmera/trivial-extensible-sequences explains in detail.

    In summary, the ability to make new sequence types as I desired is not part of the Common Lisp specification. However, some implementations of Common Lisp, such as SBCL, support this. See https://www.sbcl.org/manual/index.html#Extensible-Sequences. The library linked above provides a fallback for implementations which don't support the extensible sequences protocol.