54 lines
1.3 KiB
Common Lisp
54 lines
1.3 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 #:stop #:next #:value #:next-value #:process
|
|
#:list-iterator))
|
|
|
|
(in-package :scopes/util/iter)
|
|
|
|
;;;; iterators
|
|
|
|
(defclass iterator ()
|
|
((stopped :accessor stopped :initform nil)))
|
|
|
|
(defgeneric next (it))
|
|
(defgeneric value (it))
|
|
|
|
(defgeneric next-value (it)
|
|
(:method ((it iterator))
|
|
(next it)
|
|
(value it)))
|
|
|
|
(defgeneric stop (it)
|
|
(:method ((it iterator))
|
|
(setf (stopped it) t)))
|
|
|
|
(defgeneric process (it fn)
|
|
(:method ((it iterator) fn)
|
|
(do ((eoi (next it) (or (stopped it) (next it))))
|
|
(eoi)
|
|
(funcall fn (value it)))
|
|
(setf (stopped it) nil)))
|
|
|
|
;;;; list iterator implementation
|
|
|
|
(defclass list-iterator (iterator)
|
|
((data :reader data :initarg :data :initform nil)
|
|
(cur :accessor cur)))
|
|
|
|
(defun list-iterator (data)
|
|
(make-instance 'list-iterator :data data))
|
|
|
|
(defmethod initialize-instance :after ((it list-iterator) &key)
|
|
(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)))
|