45 lines
1.1 KiB
Common Lisp
45 lines
1.1 KiB
Common Lisp
;;;; cl-scopes/util/iter
|
|
|
|
;;;; iterators, queues, and other sequentially accessible stuff
|
|
;;;; producing items (objects) like: numbers, strings, symbols, lists, ...
|
|
|
|
(defpackage :scopes/util/iter
|
|
(:use :common-lisp)
|
|
(:export #:next #:value #:process
|
|
#:list-iterator))
|
|
|
|
(in-package :scopes/util/iter)
|
|
|
|
;;;; iterators
|
|
|
|
(defclass abstract-iterator () ())
|
|
|
|
(defgeneric next (it))
|
|
(defgeneric value (it))
|
|
|
|
(defgeneric next-value (it)
|
|
(:method ((it abstract-iterator))
|
|
(next it)
|
|
(value it)))
|
|
|
|
(defgeneric process (it fn &optional stop)
|
|
(:method ((it abstract-iterator) fn &optional (stop (constantly nil)))
|
|
(do ((eoi (next it) (next it)))
|
|
((or eoi (funcall stop)))
|
|
(funcall fn (value it)))))
|
|
|
|
;;;; list iterator implementation
|
|
|
|
(defclass list-iterator (abstract-iterator)
|
|
((data :reader data :initarg :data :initform nil)
|
|
(cur :accessor cur)))
|
|
|
|
(defmethod initialize-instance :after ((it list-iterator) &key &allow-other-keys)
|
|
(setf (cur it) (cons nil (data it))))
|
|
|
|
(defmethod next ((it list-iterator))
|
|
(pop (cur it))
|
|
(null (cur it)))
|
|
|
|
(defmethod value ((it list-iterator))
|
|
(car (cur it)))
|