forked from Ramarren/cl-parser-combinators
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.lisp
66 lines (51 loc) · 1.96 KB
/
queue.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(in-package :parser-combinators)
(defclass queue ()
((head :accessor head-of :initform nil)
(tail :accessor tail-of :initform nil)
(size :accessor size-of :initform 0)))
(defun make-queue (&optional initial-contents)
(let ((queue (make-instance 'queue)))
(dolist (tk initial-contents queue)
(push-back queue tk))))
(defgeneric peek (collection) (:documentation "Return top element without removing it"))
(defgeneric empty-p (collection) (:documentation "True if collection is empty"))
(defgeneric push-front (collection value) (:documentation "Push value to the front"))
(defgeneric pop-front (collection) (:documentation "Remove and return value from the front"))
(defgeneric push-back (collection value) (:documentation "Push value to the back"))
(defgeneric peek-back (collection) (:documentation "Return value from the back without removing it"))
(defmethod empty-p ((queue queue))
(zerop (size-of queue)))
(defmethod peek ((queue queue))
(if (empty-p queue)
(values nil nil)
(values (car (head-of queue)) t)))
(defmethod peek-back ((queue queue))
(if (empty-p queue)
(values nil nil)
(values (car (tail-of queue)) t)))
(defmethod push-front ((queue queue) value)
(setf (head-of queue) (cons value (head-of queue)))
(unless (tail-of queue)
(setf (tail-of queue) (head-of queue)))
(incf (size-of queue))
queue)
(defmethod pop-front ((queue queue))
(if (empty-p queue)
(values nil nil)
(let ((front (car (head-of queue))))
(setf (head-of queue) (cdr (head-of queue)))
(unless (head-of queue)
(setf (tail-of queue) nil))
(decf (size-of queue))
(values front nil))))
(defmethod push-back ((queue queue) value)
(let ((new-cons (cons value nil)))
(when (tail-of queue)
(setf (cdr (tail-of queue)) new-cons))
(setf (tail-of queue) new-cons)
(unless (head-of queue)
(setf (head-of queue) new-cons)))
(incf (size-of queue))
queue)
(defun queue-to-list (queue)
(head-of queue))