;;; -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Copyright (C) 1999, 2002, 2009, 2015 Marek Rychlik ;;; ;;; This program is free software; you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 2 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage "PRIORITY-QUEUE" (:use :cl :heap) (:export "PRIORITY-QUEUE" "PRIORITY-QUEUE-ELEMENT-TYPE" "PRIORITY-QUEUE-TEST" "ENQUEUE" "DEQUEUE" "QUEUE-EMPTY-P" "QUEUE-SIZE" ) (:documentation "Implements a priority queue.")) (in-package :priority-queue) (defclass priority-queue () ((element-type :initarg :element-type :initform 'fixnum :accessor priority-queue-element-type :type symbol :documentation "Element type stored in this queue.") (test :initarg :test :accessor priority-queue-test :documentation "The partial order used in element comparison.") (heap :documentation "A private slot holding the heap.")) (:documentation "Represents a priority queue based on heaps. Slots HEAP and TEST are read-only after they are initialized. The slot ELEMENT-TYPE can be overriden in subclasses, by initializing it in a :BEFORE or an :AFTER method.")) (defmethod initialize-instance :around ((self priority-queue) &key (test #'<=) (element-key #'identity)) "Fill in the HEAP slot with an instance of a heap. NOTE: This has to be an :AROUND method, so that the slot ELEMENT-TYPE can be initialized in a :BEFORE or :AFTER method of a subclass of PRIORITY-QUEUE." (with-slots (heap (test-x test) element-type) (call-next-method) (setf heap (make-heap :element-type element-type) test-x #'(lambda (x y) (funcall test (funcall element-key y) (funcall element-key x))))) self) (defgeneric enqueue (self item) (:method ((self priority-queue) (item t)) (with-slots (heap test) self (heap-insert heap item test)) self)) (defgeneric dequeue (self) (:method ((self priority-queue)) (with-slots (heap test) self (heap-remove heap test)))) (defgeneric queue-empty-p (self) (:method ((self priority-queue)) (with-slots (heap) self (heap-empty-p heap)))) (defgeneric queue-size (self) (:method ((self priority-queue)) (with-slots (heap) self (heap-size heap))))