MITSUBISHI ELECTRIC RESEARCH LABORATORIES http://www.merl.com
Some Useful Lisp Algorithms: Part 1
Richard C. Waters
TR91-04 December 1991
Abstract Richard C. Waters Chapter 3 Implementing¨ Queues in Lisp(co-authored¨ by P. Norvig) presents several different algorithms for implementing queues in Lisp. It discusses why the obvious list- based implementation of queues is inefficient and the particular situations where more complex implementations are appropriate.
This work may not be copied or reproduced in whole or in part for any commercial purpose. Permission to copy in whole or in part without payment of fee is granted for nonprofit educational and research purposes provided that all such whole or partial copies include the following: a notice that such copying is by permission of Mitsubishi Electric Research Laboratories, Inc.; an acknowledgment of the authors and individual contributions to the work; and all applicable portions of the copyright notice. Copying, reproduction, or republishing for any other purpose shall require a license with payment of fee to Mitsubishi Electric Research Laboratories, Inc. All rights reserved.
Copyright c Mitsubishi Electric Research Laboratories, Inc., 1991 201 Broadway, Cambridge, Massachusetts 02139 MERLCoverPageSide2 witsuishi iletri eserh vortories
ehnil eport WIEHR hemeer ISD IWWI
y
ihrd gF ters
estrt
his tehnil report gthers together three ppers tht were written during IWWI nd sumitted for pulition in egw visp ointersF ih pper desries useful visp lgorithmF ghpter I upporting the egression esting of visp rogrms4 presents system lled rt tht mintins dtse of tests nd utomtilly runs them when requestedF his n tke lot of omputer timeD ut does not tke ny of the progrmmer9s timeF es resultD ny ugs found y running the tests|nd this is lot more ugs thn you might think|re essentilly found for freeF ghpter P hetermining the goverge of est uite4 presents system lled over tht n help ssess the overge of suite of test sesF hen suite of test ses for progrm is run in onjuntion with overD sttistis re kept on whih onditions in the ode for the progrm re exerised nd whih re notF fsed on this informtionD over n print report of wht hs een missedF fy devising tests tht exerise these onditionsD progrmmer n extend the test suite so tht it hs more omplete overgeF ghpter Q smplementing ueues in visp4 @oEuthored y F xorvigA presents severl dierent lgorithms for implementing queues in vispF st disusses why the ovious listEsed implementtion of queues is ineient nd the prtiulr situE tions where more omplex implementtions re ppropriteF
umitted to egw visp ointersD tnuryD xovemerD nd heemer IWWIF
PHI frodwy gmridge wsshusetts HPIQW ulition ristoryXE IF pirst printingD WIEHRD heemer IWWI PF ghpter I pulished s upporting the egression esting of visp rogrms4D egw visp ointersD R@PAXRU{SQD tune IWWIF
gopyright witsuishi iletri eserh vortoriesD IWWI PHI frodwyY gmridge wsshusetts HPIQW
his work my not e opied or reprodued in whole or in prt for ny ommeril purposeF ermission to opy in whole or in prt without pyment of fee is grnted for nonprot edE utionl nd reserh purposes provided tht ll suh whole or prtil opies inlude the followingX notie tht suh opying is y permission of witsuishi iletri eserh vE ortories of gmridgeD wsshusettsY n knowledgment of the uthors nd individul ontriutions to the workY nd ll pplile portions of the opyright notieF gopyingD reprodutionD or repulishing for ny other purpose shll require liense with pyment of fee to witsuishi iletri eserh vortoriesF ell rights reservedF visp elgorithms I
IF upporting the egression esting of visp rogrms
ihrd gF ters
row often hve you mde hnge in sysE ser9s wnul for tem to x ug or dd feture nd een toE tlly sure tht the hnge did not et nyE he funtionsD mrosD nd vriles tht thing elseD only to disover weeks or months mke up the rt regression tester re in pkE lter tht the hnge roke somethingc ge lled 44F he ten exported symols re sn my personl experieneD the single most doumented elowF sf you wnt to refer to these vlule softwre mintenne tool is regresE symols without pkge prexD you hve to sion testerD whih mintins suite of tests for use9 the pkgeF system nd n run them utomtilly when he si unit of onern of rt is the testF the system is hngedF he term regression ih test hs n identifying nme nd ody testing4 is usedD euse eh version of the sysE tht speies the tion of the testF puntions tem eing tested is ompred with the previous re provided for deningD redeningD removingD version to mke sure tht the new version hs nd performing individul tests nd the test not regressed y losing ny of the tested pE suite s wholeF sn dditionD informtion is ilitiesF he more omprehensive the test suite mintined out whih tests hve sueeded isD the more vlule this omprison eomesF nd whih hve filedF greting omprehensive test suite for system requires signint eortD nd running deftest nme form 8rest vlues test suite n require signint mounts of sndividul tests re dened using the mro omputer timeF roweverD given omprehenE deftestF he identifying nme is typilly sive test suiteD regression testing detets n imE numer or symolD ut n e ny visp formF pressive numer of ugs with remrkly little sf the test suite lredy ontins test with the humn eortF sme @equlA nmeD then this test is redened he rt regression tester presented here supE nd wrning messge printedF @his wrning ports the regression testing of systems written is importnt to lert the user when test suite in gommon vispF sn ddition to eing vluE denition le ontins two tests with the sme le toolD rt is n interesting exmple of the nmeFA hen the test is new oneD it is dded power of vispF to the end of the suiteF sn either seD nme is he unied nture of the visp progrmming returned s the vlue of deftest nd stored in environment nd the ft tht visp progrms the vrile BtestBF n e mnipulted s dt llows rt to e imE @deftest tEI @floor ISGUA P IGUA A tEI plemented in two pges of odeF werely impleE @deftest @t PA @list IA @IAA A @t PA menting thEmode regression tester using @deftest d @IC IA IA A d n elgolElike lnguge in typil progrmE @deftest good @IC IA PA A good ming environment would require muh more odeF smplementing highly intertive system he form n e ny kind of visp formF he like rt would e mjor undertkingF zero or more vlues n e ny kind of visp P FgF ters
ojetsF he test is performed y evluting every test from the test suite nd returns nilF form nd ompring the results with the vluesF qenerllyD it is dvisle for the whole test suite he test sueeds if nd only if form produes to pply to some one systemF hen swithing the orret numer of results nd eh one is from testing one system to testing notherD it is equl to the orresponding vlueF wise to remove ll the old tests efore eginning to dene new onesF BtestB nmeEofEurrentEtest he vrile BtestB ontins the nme of doEtests 8optionl @out BstndrdEoutputBA the test most reently dened or performedF st his funtion uses doEtest to run eh of is set y deftest nd doEtestF the tests in the test suite nd prints report of the results on outD whih n either e n outE doEtest 8optionl @nme BtestBA put strem or the nme of leF sf out is omitE he funtion doEtest performs the test idenE tedD it defults to BstndrdEoutputBF hoEtests tied y nmeD whih defults to BtestBF fefore returns t if every test sueeded nd nil if ny running the testD doEtest stores nme in the test filedF vrile BtestBF sf the test sueedsD doEtest es illustrted elowD the rst line of the reE returns nme s its vlueF sf the test filsD port produed y doEtests shows how mny doEtest returns nilD fter printing n error reE tests need to e performedF he lst line shows port on BstndrdEoutputBF he following exE how mny tests filed nd lists their nmesF mples show the results of performing two of hile the tests re eing performedD doEtests the tests dened oveF prints the nmes of the suessful tests nd the error reports from the unsuessful testsF @doEtest 9@t PAA A @t PA @doEtest 9dA A nil Y fter printingX @doEtests 4reportFtxt4A A nil est feh filed Y the le 4reportFtxt4 ontinsX pormX @IC IA hoing R pending tests of R tests totlF ixpeted vlueX I EI @ PA etul vlueX PF est feh filed pormX @IC IA ixpeted vlueX I BdoEtestsEwhenEdefinedB defult vlue nil etul vlueX PF sf the vlue of this vrile is nonEnullD eh qyyh I out of R totl tests filedX fehF test is performed t the moment tht it is deE nedF his is helpful when intertively onE st is est if the individul tests in the suite struting suite of testsF roweverD when lodE re totlly independent of eh otherF roweverD ing test suite for lter useD performing tests should the need rise for some interdependeneD s they re dened is not lile to e helpfulF you n rely on the ft tht doEtests will run tests in the order they were originlly denedF getEtest 8optionl @nme BtestBA his funtion returns the nmeD formD nd pendingEtests vlues of the speied testF hen test is dened or redenedD it is mrked s pendingF sn dditionD doEtest mrks @getEtest 9@t PAA A @@t PA @list IA @IAA the test to e run s pending efore running it remEtest 8optionl @nme BtestBA nd doEtests mrks every test s pending eE fore running ny of themF he only time test sf the indited test is in the test suiteD this is mrked s not pending is when it ompletes funtion removes it nd returns nmeF ytherE suessfullyF he funtion pendingEtests reE wiseD nil is returnedF turns list of the nmes of the urrently pendE remEllEtests ing testsF his funtion reinitilizes rt y removing @pendingEtestsA A @dA visp elgorithms Q
ontinueEtesting row orks his funtion is identil to doEtests exept he ode for rt is shown in pigures I 8 PF tht it only runs the tests tht re pending nd he rst gure shows the funtions for minE lwys writes its output on BstndrdEoutputBF tining the suite of testsF por the most prtD @ontinueEtestingA A nil Y fter printingX the ode is self explntoryF roweverD severl hoing I pending test out of R totl testsF points re worthy of noteF est feh filed he test suite is represented s list of test pormX @IC IA ixpeted vlueX I entries stored in the vrile BentriesBF he etul vlueX PF list egins with dummy entry of nil so tht I out of R totl tests filedX fehF insertion nd deletion of entries n e done y sideEeet without hving to hndle n empty gontinueEtesting hs speil mening if test suite s speil seF ih test entry lled t rekpoint generted while test is ontins ve piees of informtionX eing performedF he filure of test to reE turn the orret vlue does not trigger n error pend e g tht is nonEnull when the rekF roweverD there re mny kinds of things test is pendingF tht n go wrong while test is eing perE nme he nme of the test represented formed @eFgFD dividing y zeroA tht will use y the test entryF reksF form he form to evlute when sf ontinueEtesting is evluted in rek performing the testF generted during testingD it orts the urrent vls he vlues speifying wht the test @whih remins pendingA nd fores the form should returnF proessing of tests to ontinueF xote tht in defn e list ontining the nmeD formD suh rekpointD BtestB is ound to the nme nd vlsF of the test eing performed nd @getEtestA n e used to look t the testF por eienyD the entry dt struture is hen uilding systemD it is dvisle to represented s list where the pendD nmeD nd strt onstruting test suite for it s soon s form elds re dened in the norml wyD nd possileF ine individul tests re rther wekD the vls nd defn elds re overlpping tils of omprehensive test suite requires lrge numE the listF ers of testsF roweverD these n e umuE qetEentry is roken out s seprte funE lted over timeF sn prtiulrD whenever ug tionD rther thn eing prt of getEtestDeE is found y some mens other thn testingD it use it is lled y doEtest s wellF is wise to dd test tht would hve found the he reson why deftest is mro insted ug nd therefore will ensure tht the ug will of funtion is to llow tests to e dened withE not repperF out expliitly quoting the vrious prts of the ivery time the system is hngedD the entire denitionF test suite should e run to mke sure tht no he opyElist in ddEentry is needed to enE unintended hnges hve ourredF ypillyD sure tht evluting deftest seond time some tests will filF ometimesD this merely retes fresh entryF mens tht tests hve to e hnged to reet e desire to keep the entries on BentriesB hnges in the system9s speitionF yther in the order tht the tests re initilly dened timesD it indites ugs tht hve to e trked mkes the min loop in ddEentry somewht down nd xedF huring this phseD ontinueE omplexF he loop serhes through BentriesB testing is useful for fousing on the tests tht to see if there is preEexisting test with the re filingF roweverD for sfety skeD it is lwys sme nme s the one eing denedF sf there wise to reinitilize rtD redene the entire test isD the entry is repledF sf notD the new entry suiteD nd run doEtests one more time fter you is pled t the end of BentriesBF think ll of the tests re workingF he error reporting done y getEentry nd R FgF ters
@inEpkge 44 Xuse 9@4vs4AA @defun getEtest @8optionl @nme BtestBAA @defn @getEentry nmeAAA @provide 44A @defun getEentry @nmeA @export @let @@entry @find nme @dr BentriesBA 9@deftest getEtest doEtest remEtest Xkey 59nme remEllEtests doEtests pendingEtests Xtest 59equlAAA ontinueEtesting BtestB @when @null entryA BdoEtestsEwhenEdefinedBAA @reportEerror t @defvr BtestB nil 4gurrent test nme4A 4~7xo test with nme ~Xd@~~AF4 @defvr BdoEtestsEwhenEdefinedB nilA nmeAA @defvr BentriesB 9@nilA 4est dtse4A entryAA @defvr BinEtestB nil 4 sed y i4A @defmro deftest @nme form 8rest vluesA @defvr BdeugB nil 4por deugging4A @ddEentry 9@t Dnme Dform FDvluesAAA @defstrut @entry @XonEnme nilA @defun ddEentry @entryA @Xtype listAA @setq entry @opyElist entryAA pend nme formA @do @@l BentriesB @dr lAAA @nilA @defmro vls @entryA @dddr DentryAA @when @null @dr lAA @setf @dr lA @list entryAA @defmro defn @entryA @dr DentryAA @return nilAA @defun pendingEtests @A @when @equl @nme @dr lAA @do @@l @dr BentriesBA @dr lAA @nme entryAA @r nilAA @setf @dr lA entryA @@null lA @nreverse rAA @reportEerror nil @when @pend @r lAA 4edefining test ~dX@~~A4 @push @nme @r lAA rAAAA @nme entryAA @return nilAAA @defun remEllEtests @A @when BdoEtestsEwhenEdefinedB @setq BentriesB @list nilAA @doEentry entryAA nilA @setq BtestB @nme entryAAA @defun remEtest @8optionl @nme BtestBAA @defun reportEerror @errorc 8rest rgsA @do @@l BentriesB @dr lAAA @ond @BdeugB @@null @dr lAA nilA @pply 59formt t rgsA @when @equl @nme @dr lAA nmeA @if errorc @throw 9BdeugB nilAAA @setf @dr lA @ddr lAA @errorc @pply 59error rgsAA @return nmeAAAA @t @pply 59wrn rgsAAAA
pigure IX he ode for the prt of rt tht mintins the test suiteF
ddEentry is roken out into the seprte funE is used s n interlok to mke sure tht the tion reportEerror to provide greter uniformity funtion ontinueEtesting will only do throw nd filitting the testing of rtF when the pproprite th existsF he wy st is often dvisle to insert few hooks doEentry rst sets the pend eld of the entry to in system tht filitte testingF es illusE t nd then resets it to reet whether the test trted in the next setionD the use of the vriE hs sueeded uses the pend eld to remin t le BdeugB nd the ssoited throw mkes it when test is ortedF possile to test the error heking done y rt feuse it does lot of outputD doEentries without using error reks t testing timeF looks omplexF roweverD it tully does little pigure P shows the ode for running testsF more thn ll doEentry on eh pending testF ixept for the formt ontrol strings|whihD st ws deided tht gontinueEtesting did s lwysD re onvenient ut insrutle|most not need to hve strem rgumentD euse of the ode is self explntoryF xeverthelessD ontinueEtesting is only useful when using rt ouple of points re interestingF intertivelyF he th set up y doEentry is used y yne might e moved to sy tht the ode in ontinueEtesting to ort out of test tht hs pigures I 8 P is too trivil to e n impressive used n error rekF he vrile BinEtestB exmple of the power of vispF roweverD this visp elgorithms S
@defun doEtest @8optionl @nme BtestBAA @defun doEtests @8optionl @doEentry @getEentry nmeAAA @out BstndrdEoutputBAA @dolist @entry @dr BentriesBAA @defun doEentry @entry 8optionl @setf @pend entryA tAA @s BstndrdEoutputBAA @if @stremp outA @th 9BinEtestB @doEentries outA @setq BtestB @nme entryAA @withEopenEfile @setf @pend entryA tA @strem out Xdiretion XoutputA @letB @@BinEtestB tA @doEentries stremAAAA @BrekEonEwrningsB tA @r @multipleEvlueElist @defun doEentries @sA @evl @form entryAAAAA @formt s 4~8hoing ~e pending test~X ~ @setf @pend entryA of ~e tests totlF~74 @not @equl r @vls entryAAAA @ount t @dr BentriesBA @when @pend entryA Xkey 59pendA @formt s 4~8est ~Xd@~~A filed~ @length @dr BentriesBAAA ~7pormX ~~ @dolist @entry @dr BentriesBAA ~7ixpeted vlue~X ~ @when @pend entryA ~f~~~7~IUt~g~ @formt s 4~d~`~7~XY ~Xd@~~A~b~4 ~7etul vlue~X ~ @doEentry entry sAAAA ~f~~~7~ISt~gF~74 @let @@pending @pendingEtestsAAA BtestB @form entryA @if @null pendingA @length @vls entryAA @formt s 4~8xo tests filedF4A @vls entryA @formt s 4~8~e out of ~e ~ @length rA rAAAA totl tests filedX ~ @when @not @pend entryAA BtestBAA ~Xd@~f~`~7 ~IXY~~b~ ~D ~g~AF4 @defun ontinueEtesting @A @length pendingA @if BinEtestB @length @dr BentriesBAA @throw 9BinEtestB nilA pendingAA @doEentries BstndrdEoutputBAAA @null pendingAAA
pigure PX he ode for the prt of rt tht performs testsF would e tking too nrrow viewF he imE intertive running of individul test ses nd pressive thing out pigures I 8 P is not wht reporting of the resultsD userEinterfe modE they ontinD ut wht the do not hve to onE ule would hve to e writtenF o go eyond this tinF sn prtiulrD most of wht you would nd llow the intertive @reAdenition of testsD hve to write to implement rt in other lnE some espe to the surrounding operting sysE guges is provided y the visp environment nd tem would e required to ess the ompilerF does not hve to e written t llF o tke the nl step of llowing the testing gonsider wht it would e like to impleE of system to e intermixed with deuggingD ment rt in lnguge suh s edF feuse the implementtion would hve to e uilt s of the strong typing in edD one would proE n extension to n intertive progrmming enE ly e prevented from tking the simple pE vironmentF vike ny visp systemD rt gets the proh of storing eh test s omintion of enet of this t no ost to the implementor testing funtion to ll nd group of dt whteverF vluesF therD one would proly hve to en ixmple est uite dene eh test s seprte funtion of no rgumentsF his would llow you to use the eturning to the question of how rt n stndrd ed ompiler to prepre the tests for est e usedD onsider pigure QD whih shows exeutionY howeverD you would hve to write the eginnings of test suite for rt itselfF here some mount of ode outside of ed @eFgFD shell is it of grtuitous omplexity euse the sripts in unix systemA to mnge the proess system is eing used to test itselfF xeverthelessD of dening nd running testsF the gure is good exmple of wht typil por n ed implementtion to support the test suite looks likeF he rst three lines of the T FgF ters
@inEpkge 4 i4A gure speify tht the test suite is in the 4 i4 @require 44A pkge nd prepre rt for useF @useEpkge 44A he funtion setup is used y the tests to @defmro setup @8rest odyA rete sfe environment where experiments @doEsetup 9@progn FD odyAAA n e performed without eting the overE @defun doEsetup @formA ll test suite in the gureF sn preprtion for @let @@BtestB nilA these experimentsD setup denes two exmple @BdoEtestsEwhenEdefinedB nilA @rtXXBentriesB @list nilAA tests @tI nd @t PAAF etup ptures ny outE @rtXXBdeugB tA put reted y form in string nd returns resultA list of the lines of output s its rst vlueF etup @deftest tI R RA @deftest @t PA R QA inds rtXXBdeugB to t @see pigure IA nd inE @vlues ludes n pproprite th so tht the error @normlize heking done y rt n e testedF @withEoutputEtoEstring @BstndrdEoutputBA he funtion normlize overomes minor @setq result prolem in the portility of gommon vispF @th 9rtXXBdeugB everl of the formt ontrol strings in doEentry @evl formAAAAA resultAAA nd doEentries use the ontrol ode ~8 @see pigure PAF nfortuntelyD while this is etter @defun normlize @stringA @let @@l nilAA thn ~7 in mny situtionsD it is not gurnE @withEinputEfromEstring @s stringA teed to ehve dierentlyD nd gommon visp @loop @push @redEline s nil sA lA @when @eq @r lA sA implementtions vry widely in wht they doF @setq l @nreverse @dr lAAA xormlize removes ny lnk lines tht result @return nilAAAA from ~8 ting like ~7F @delete 44 l Xtest 59equlAAA he rst ve tests in pigure Q test the funE @remEllEtestsA tion getEtestF iven for this trivil funtionD @deftest getEtestEI severl tests re required to get resonle ovE @setup @getEtest 9tIAA erge of its pilitiesF qetEtestESD heks @A @tI R RAA @deftest getEtestEP tht getEtest reports n error when given the @setup @getEtest 9tIA BtestBA nme of nonEexistent testF @A @t PAA he lst three tests in pigure Q test the funE @deftest getEtestEQ @setup @getEtest 9@t PAAA tion doEtestF he full test suite for rt ontins @A @@t PA R QAA severl more tests of getEtest nd doEtestsD @deftest getEtestER nd some twenty more tests overllF @setup @let @@BtestB 9tIAA @getEtestAAA @A @tI R RAA eknowledgments @deftest getEtestES @setup @getEtest 9tHAA he onept of regression testing is n old @4xo test with nme HF4A nilA oneD nd mny @if not mostA lrge progrmming @deftest doEtestEI orgniztions hve regression testersF rt is the @setup @doEtest 9tIAA @A tIA result of ten yers of prtil use nd evoluE @deftest doEtestEP tionF wny of the ides in it me from onverE @setup @doEtest 9tIA BtestBA stions with ghrles ih nd uent itmnD @A tIA @deftest doEtestEQ who implemented similr systemsF @setup @doEtest 9@t PAAA his pper desries reserh done t the @4est @ PA filed4 mit i vortoryF upport ws provided y 4pormX R4 4ixpeted vlueX Q4 drpD nsfD imD nynexD iemensD perryD nd 4etul vlueX RF4A mF he views nd onlusions presented here nilA re those of the uthor nd should not e interE preted s representing the poliiesD expressed or pigure QX ome tests of rt itselfF impliedD of these orgniztionsF visp elgorithms U
ytining rt is written in portle gommon visp nd hs een tested in severl dierent gommon visp implementtionsF he omplete soure for rt is shown in pigures I{PF sn dditionD the soure n e otined over the internet y using ftpF gonnetion should e mde to the pFesFwsFih mhine @internet numE er IPVFSPFQPFTAF vogin s nonymous4 nd opy the les shown elowF st is dvisle to run the tests in rtEtestFlisp fter ompiling rt for the rst time on new systemF
sn the diretory GpuGlptrsG rtFlisp soure ode rtEtestFlisp test suite reEdoFtxt rief doumenttion
he ontents of pigures I 8 P nd the les ove re opyright IWWH y the wsshusetts snstitute of ehnologyD gmridge weF erE mission to useD opyD modifyD nd distriute this softwre for ny purpose nd without fee is herey grntedD provided tht this opyright nd permission notie pper in ll opies nd supporting doumenttionD nd tht the nmes of ws ndGor the uthor re not used in dE vertising or puliity pertining to distriution of the softwre without speiD written prior permissionF ws nd the uthor mke no repE resenttions out the suitility of this softE wre for ny purposeF st is provided s is4 without express or implied wrrntyF ws nd the uthor dislim ll wrrnties with regrd to this softwreD inluding ll imE plied wrrnties of merhntility nd tnessD in no event shll ws or the uthor e lile for ny speilD indiret or onsequentil dmE ges or ny dmges whtsoever resulting from loss of useD dt or protsD whether in n tion of ontrtD negligene or other tortious tionD rising out of or in onnetion with the use or performne of this softwreF V FgF ters visp elgorithms W
PF hetermining the goverge of est uite
ihrd gF ters
he vlue of suite of test ses depends ny test suite tht fils to exerise the ondition ritilly on its overgeF sdelly suite should where y is negtive will fil to detet the ug in test every fet of the speition for proE the next to lst line of the funtionF grm nd every fet of the lgorithms used @es n exmple of the ft tht overing to implement the speitionF nfortuntelyD ll the onditions in progrm does not gurE there is no prtil wy to e sure tht omE ntee tht every fet of either the lgorithm plete overge hs een hievedF roweverD or the speition will e overedD onsider something should e done to ssess the overE the ft tht the two test ses @myB PFI QA ge of test suiteD euse test suite with nd @myB EIGP EIGPA over ll four onditionsF poor overge hs little vlueF roweverD they do not detet the ug on the e trditionl pproximte method of ssessE next to lst line nd they do not detet the ft ing the overge of test suite is to hek tht tht myB fils to work on omplex numersFA every ondition tested y the progrm is exerE he over system determines whih onE isedF por every predite in the progrmD there ditions tested y progrm re exerised y should e t lest one test se tht uses the given test suiteF his is no sustitute for thinkE predite to e true nd one tht uses it to ing hrd out the overge of the test suiteF e flseF gonsider the funtion myB in pigure RD roweverD it provides useful strting point nd whih uses onvoluted lgorithm to ompute n indite some res where dditionl test the produt of two numersF ses should e devisedF he funtion myB ontins two preditesD @minusp xA nd @minusp yAD whih led to four ser9s wnul for gyi onditionsX x is negtiveD x is not negtiveD y is negtiveD nd y is not negtiveF o e t ll he funtionsD mrosD nd vriles tht thoroughD test suite must ontin tests exerE mke up the over system re in pkge ising ll four of these onditionsF por instneD lled 4gyi4F he six exported symols re doumented elowF
@defun myB @x yA @let @@sign IAA overXnnotte tEorEnil @when @minusp xA @setq sign @E signAA ivluting @overXnnotte tA triggers the @setq x @E xAAA proessing of funtion nd mro denitions y @when @minusp yA the over systemF ih susequent instne @setq sign @E signAA @setq y @E xAAA of defun or defmro is ltered y dding nE @B sign x yAAA nottion tht mintins informtion out the vrious onditions tested in the odyF pigure RX en exmple progrmF ivluting @overXnnotte nilA stops the IH FgF ters
speil proessing of funtion nd mro deE @setq overXBlineElimitB RQA A RQ nitionsF usequent denitions re not nnoE @overXresetA A ttedF roweverD if funtion or mro tht is @overXreportA A Y fter printingX urrently nnotted is redenedD the new deE YE Xiegr @hip x wB @ AA `Ib nition is nnotted s wellF @myB P PA A R he mro overXnnotte should only e used s topElevel formF hen nnottion is @overXreportA A Y fter printingX YC Xiegr @hip x wB @ AA `Ib triggeredD wrning messge is printedD nd t Y C Xiegr @rix @wsx A @i `Pb is returnedF ytherwiseD nil is returnedF Y E XxyxEx vv @wsx A `Rb Y C Xiegr @rix @wsx A @i `Tb @overXnnotte tA A tYfter printingX Y E XxyxEx vv @wsx A `Vb YYY rningX goverge nnottion ppliedF @myB EP PA A ER overXforgetEll @overXreportA A Y fter printingX YC Xiegr @hip x wB @ AA `Ib his funtionD whih lwys returns tD hs Y C Xiegr @rix @wsx A @i `Tb the eet of removing ll overge nnottion Y E XxyxEx vv @wsx A `Vb from every funtion nd mroF st is pproE @overXreport Xll tA A Y fter printingX prite to do this efore ompletely reompiling YC Xiegr @hip x wB @ AA `Ib Y C Xiegr @rix @wsx A @i `Pb the system eing tested or efore swithing to Y C XxyxEx vv @wsx A `Rb dierent system to e testedF Y C Xx vv @wsx A `Sb Y C Xiegr @rix @wsx A @i `Tb overXreset Y E XxyxEx vv @wsx A `Vb Y C Xx vv @wsx A `Wb ih ondition tested y n nnotted funE tion nd mro is ssoited with g tht pigure SX ixmple over reportsF trips when the ondition is exerisedF he funE tion overXreset resets ll these gsD nd reE turns tF st is pproprite to do this efore reE trunted to ensure tht it is no wider thn running test suite to reevlute its overgeF overXBlineElimitBF en exmpleF uppose tht the funtion overXreport 8key fn out ll myB in pigure R hs een nnotted nd tht no his funtion displys the informtion minE other funtions or mros hve een nnottedF tined y overD returning no vluesF pn must pigure S illustrtes the opertion of over nd e the nme of n nnotted funtion or mroF the reports printed y overXreportF sf fn is speiedD report is printed showing inE ih line in report ontins three piees of formtion out tht funtion or mro onlyF informtion out point in denitionX CGE ytherwiseD reports re printed out every nE speifying tht the point either hs @CAorhs notted funtion nd mroF not @EA een exerisedD messge inditing the yutD whih defults to BstndrdEoutputBD physil nd logil plement of the point in must either e n output strem or the nme the denitionD nd in ngle rkets `bD n inE of leF st speies where the reports should teger tht is unique identier for the pointF e printedF sndenttion is used to indite tht some points sf llD whih defults to nilD is nonEnull then re suordinte to others in the sense tht the the reports printed ontin informtion out suordinte points nnot e exerised without every onditionF ytherwiseD the reports re E lso exerising their superiorsF he order of the revited to highlight key onditions tht hve lines of the report is the sme s the order of not een exerisedF the points in the denitionF ih messge ontins lel @eFgFD XiegrD overXBlineElimitB defult vlue US Xx vvA nd piee of odeF here is point lE he output produed y overXreport is eled Xiegr orresponding to eh denition s visp elgorithms II
whole nd eh onditionl form within eh ell informtion out the speied points @nd denitionF uordinte points orresponding their suordintesA is forgottenF prom the point to the onditions onditionl form tests re of view of overXreportD the eet is s if the grouped under the point orresponding to the points never existedF @e forgotten point n formF es disussed in detil in the next suseE e retrieved y reevluting or reompiling the tionD the messges for the suordinte points funtion or mro denition ontining itFA he desrie the situtions in whih the onditions exmple elowD whih follows on fter the end re exerisedF vines tht would otherwise e of pigure SD shows the tion of overXforgetF too long to t on one line hve their messges trunted @eFgFD points `Pb nd `Tb in pigure SAF @overXforget TA A he rst three reports in pigure S re E @overXreport Xll tA A Y fter printingX revited sed on two priniplesF pirstD if YC Xiegr @hip x wB @ AA `Ib Y C Xiegr @rix @wsx A @i `Pb point p nd ll of its suordintes hve een Y C XxyxEx vv @wsx A `Rb exerisedD then p nd ll of its suordintes re Y C Xx vv @wsx A `Sb omitted from the reportF his is done to fous @overXreportA A Y fter printing the user9s ttention on the points tht hve not Yell points exerisedF een exerisedF eondD if point p hs not een exerisedD he revited report ove does not deE then ll of the points suordinte to it re omitE srie ny pointsD euse every point in myB ted from the reportF his reets the ft tht tht hs not een forgotten hs een exerisedF it is not possile for ny of these suordinte st is pproprite to forget point if there is points to hve een exerised nd one nnot some reson tht no test se n possily exE devise test se tht exerises ny of the suE erise the pointF roweverD it is muh etter to ordinte points without rst guring out how write your ode so tht every ondition n e to exerise pF testedF en dditionl ompliting ftor is tht @oint numers re ssigned sed on the over opertes in n inrementl fshion nd order in whih points re entered into over9s does notD in generlD hve full informtion out dtseF sn generlD whenever denition is the suordintes of points tht hve not een reevluted or reompiledD the numers of the exerisedF es resultD it is not lwys possile points within it hngeFA to present omplete reportF roweverD one n he wy onditionls re nnottedF hve totl ondene tht if the report sys tht pigure T shows le tht mkes use of overF every point hs een exerisedD this sttement pigure U shows the kind of report tht might e is sed on omplete informtionF produed y loding the leF feuseD myeE he rst report in pigure S shows tht none nd g re the only denitions tht hve een of the points within myB hs een exerisedF he nnottedD these re the only denitions tht seond report displys most of the points in myBD re reported onF he order of the reports is to set the ontext for the two points tht hve the sme s the order in whih the denitions not een exerisedF he third report omits `Pb were ompiledF he report on g indites tht nd its suordintesD sine they hve ll een the tests performed y runEtests exerise most exerisedF he fourth report shows omplete of the onditions tested y gF roweverD they report orresponding to the third revited do not exerise the sitution in whih the se reportF sttement is rehedD ut neither of its luses is seletedF overXforget 8rest ids here re no points within myeED euse his funtion gives the user greter onE the ode for myeE does not ontin ny onE trol over the reports produed y overXreportF ditionl formsF st is interesting to onsider the ih id must e n integer identifying pointF preise points tht over inludes for gF IP FgF ters
@inEpkge 4 i4A YC Xiegr @hipwegy wefiE @ AA `Ib YC Xiegr @hip x q @ AA `Pb @require 4gyi4 FFFA Y C Xiegr @gyxh @@exh 5 A A @ @ `Qb @defmro myeC @x yA Y C Xiegr @exh @x vv A A `Wb @if @numerp DxA @C Dx DyAAA Y C XpsEx vv @x vv A `IIb Y C XievEevv `IPb @overXnnotte tA Y C XpsExyxEx vv @exh @x vv A `Sb @defmro myeE @x yA Y C XpsExyxEx vv `Ub @if @numerp DxA @E Dx DyAAA Y C Xiegr @gei @I @wefiE `IQb Y C Xivig I `ISb @defun g @x yA Y C Xiegr @sp @x wfi A @E `IVb @ond @@nd @null xA yA yA Y C XxyxEx vv @x wfi A `PHb @y @se y Y C Xx vv @x wfi A `PIb @I @myeE x yAA Y C Xivig P `ITb @P @myeC x yAAAAAA Y E XivigExyxi `IUb Y C XevvEx vv `Vb @overXnnotte nilA @defun h @x yA FFFA pigure UX he report reted y pigure TF @overXresetA @runEtestsA here re two supoints orresponding to the @overXreport Xout 4report4 Xll tA two luses of the seF sn dditionD sine the lst luse does not egin with t or otherwiseD pigure TX ixmple of le using overF there is n dditionl point orresponding to the sitution where none of the luses of the re exeutedF hen over proesses denitionD lusE se he pttern of messges ssoited with ter of points is generted orresponding to eh ond is illustrted y the portion @reprodued onditionl form @iFeFD ifD whenD untilD ondD elowA of pigure U tht desries the ond in gF seD typeseD ndD nd orA tht is literlly present in the progrmF sn dditionD points re Y C Xiegr @gyxh @@exh 5 A A @ @ `Qb generted orresponding to onditionl forms Y C Xiegr @exh @x vv A A `Wb tht re produed y mros tht re nnotted Y C XpsExyxEx vv @exh @x vv A `Sb Y C XpsExyxEx vv `Ub @eFgFD the if produed y the myeE in the rst Y C XevvEx vv `Vb se luse in gAF roweverD nnottion is not pplied to onditionls tht ome from other here re suordinte points orresponding to soures @eFgFD from mros tht re dened outE the two luses nd the sitution where neither side of the system eing testedAF hese ondiE luse is exeutedF here is lso point `Wb tionls re omittedD euse there is no resonE orresponding to the nd tht is the predite le wy for the user to know how they relte of the rst ond luseF his point is pled to the odeD nd therefore there is no resonE diretly under `QbD euse it is not suordinte le wy for the user to devise test se tht to ny of the individul ond lusesF will exerise themF he tretment of nd @nd orA is prtiuE he messges ssoited with point9s suE lrly interestingF ometimes nd is used s ordintes desrie the situtions under whih ontrol onstrut on pr with ondF sn tht the suordintes re exerisedF he pttern of situtionD it is ler tht nd should e treted messges ssoited with se nd typese is nlogously to ondF roweverD t other timesD illustrted y the portion @reprodued elowA nd is used to ompute vlue tht is tested of pigure U tht desries the se in gF y nother onditionl formF sn tht situtionD over ould hoose to tret nd s simple Y C Xiegr @gei @I @wefiE `IQb funtionF roweverD it is nevertheless still reE Y C Xivig I `ISb Y C Xivig P `ITb sonle to think of n nd s hving onditionl Y E XivigExyxi `IUb points tht orrespond to dierent resons why visp elgorithms IQ the nd returns true or flse vlueF st is wise in the hit eld of the pointF his method of opE to inlude tests orresponding to eh of these ertion mkes it possile to reset the hit gs dierent resonsF of ll the points urrently in existene withE he pttern of messges ssoited with n out visiting ny of them @see the denition of nd is illustrted y the portion @reprodued overXresetAF elowA of pigure U tht desries the nd in gF he id is printed in reports nd used to identify points when lling overXforgetF he @overXreport Xll tA vrile BountB is used to generte the vluesF Y C Xiegr @exh @x vv A A `Wb Y C XpsEx vv @x vv A `IIb he sttus ontrols the reporting of pointF Y C XievEevv `IPb st is either Xry @shown in reportsAD Xrshhix @not shown in reportsD ut its suordintes my he nl supoint orresponds to the sitution eAD or Xpyqyix @neither it nor its suorE where ll of the rguments of the nd hve een dintes re shown in reportsAF @overXforget evlutedF he nd then returns whtever the hnges the sttus of the indited points to nl rgument returnedF XpyqyixFA pigure T illustrtes thEoriented use of he nme of point p desries its position overF roweverD over is most eetively in the denition ontining itF e nme hs the used in n intertive wyF st is reommended formX @lel ode F superiorEnmeA where lE tht you rst rete s omprehensive test el is n explntory lel suh s Xiegr or suite s you n nd pture it using tool suh Xx vvD ode is piee of odeD nd superiorE s rt IF he tests should then e run in onE nme is the nme of the point ontining p @if juntion with over nd repeted reports from nyAF ken togetherD the lel nd ode inE over generted s dditionl tests re reted dite the position of p in denition nd the until omplete overge of onditions hs een ondition under whih it is exerised @see the hievedF o roustly support this mode of opE disussion of pigure UAF ertionD over hs een refully designed so et ny given momentD the vrile BpointsB tht it will work with thEompiled deniE ontins list of points orresponding to the tionsD inrementllyEompiled denitionsD nd nnotted denitions known to overF @he interpreted denitionsF funtion overXforgetEll resets BpointsB to nilFA es n illustrtion of the point dt struE row gyi orks tureD pigure W shows the ontents of BpointsB he ode for over is shown in pigures VD orresponding to the seond report in pigure SF IHD IID nd IQF pigure V shows the denition of st is ssumed tht BhitB hs the vlue IF the primry dt struture used y over nd he funtion ddEtopEpoint dds new topE some of the entrl opertionsF e point struE level point orresponding to denition to the ture ontins ve piees of informtion out list BpointsBF sf there is lredy point for position in the ode for denitionF the denitionD the new point is put in the sme ple in the listF hit plg inditing whether the point he funtion reordEhit reords the ft hs een exerisedF tht point hs een exerisedF his my id nique integer identierF require loting the point in BpointsB using sttus plg tht ontrols reportingF lote or dding the point into BpointsB usE nme vogil nmeF ing ddEpointF reordEhit is optimized so tht sus vist of suordinte pointsF it is extremely fst when the point hs lredy een exerisedF his llows over to run with he hit g opertes s time stmp4F reltively little overhedF @he detils of the hen point is exerisedD this is reorded y wy reordEhit nd ddEpoint operte re disE storing the urrent vlue of the vrile BhitB ussed further in onjuntion with pigure IQFA IR FgF ters
@inEpkge 4gyi4 Xuse 9@4vs4AA @lispXdefun ddEtopEpoint @pA @setq p @opyEtree pAA @provide 4gyi4A @let @@old @find @fnEnme pA BpointsB @shdow 9@defun defmroAA Xkey 59fnEnmeAAA @ond @old @setf @id pA @id oldAA @export 9@nnotte report reset forget @nsustitute p old BpointsBAA forgetEll BlineElimitBAA @t @setf @id pA @inf BountBAA @defstrut @point @XonEnme nilA @setq BpointsB @Xtype listAA @non BpointsB @hit HA @list pAAAAAAA @id nilA @lispXdefun reordEhit @pA @sttus XshowA @unless @a @hit pA BhitBA @nme nilA @setf @hit pA BhitBA @sus nilAA @let @@old @lote @nme pAAAA @defvr BountB HA @if old @defvr BhitB IA @setf @hit oldA BhitBA @defvr BpointsB nilA @ddEpoint pAAAAA @defvr BnnottingB nilA @lispXdefun lote @nmeA @defvr BtestingB nilA @find nme @lispXdefun forget @8rest idsA @if @not @dr nmeAA @forgetI ids BpointsBA BpointsB tA @let @@p @lote @dr nmeAAAA @if p @sus pAAAA @lispXdefun forgetI @nmes psA Xkey 59nme Xtest 59equlAA @dolist @p psA @when @memer @id pA nmesA @lispXdefun ddEpoint @pA @setf @sttus pA XforgottenAA @let @@sup @lote @dr @nme pAAAAA @forgetI nmes @sus pAAAA @when sup @setq p @opyEtree pAA @lispXdefun forgetEll @A @setf @sus supA @setq BpointsB nilA @non @sus supA @list pAAA @setq BhitB IA @setf @id pA @inf BountBAA @setq BountB HA @dolist @p @sus pAA tA @setf @id pA @inf BountBAAAAAA @lispXdefun reset @A @inf BhitBA tA
pigure VX he si dt struture used y overF
@@I Xry I @5Ia@Xiegr @hip x wB @ AAAA @@P Xry I @5Pa@Xiegr @rix @wsx A @i sqx @E sqxAA @i @E AAAA 5I5A @@Q Xrshhix I @@Xiegr @wsx AA 5P5 5I5A xsvA @R Xry H @@XxyxEx vv @wsx AA 5P5 5I5A xsvA @S Xry I @@Xx vv @wsx AA 5P5 5I5A xsvAAA @T Xry I @5Ta@Xiegr @rix @wsx A @i sqx @E sqxAA @i @E AAAA 5I5A @@U Xrshhix I @@Xiegr @wsx AA 5T5 5I5A xsvA @V Xry H @@XxyxEx vv @wsx AA 5T5 5I5A xsvA @W Xry I @@Xx vv @wsx AA 5T5 5I5A xsvAAAAAA
pigure WX he ontents of BpointsB orresponding to the seond report in pigure SF
pigure IH shows the ode tht prints reE ennotting denitionsF pigure II shows portsF es n e seen y omprison of pigE the ode tht ontrols the nnottion of deniE ures S nd WD reports re reltively strightE tions y overF he rst time overXnnotte forwrd printout of prts of BpointsB with nestE is lledD it uses shdowingEimport to instll new ing indited y indenttion nd only the rst denitions for defun nd defmroF hether or prt of eh point9s nme shownF he funtion not nnottion is in eet is reorded in the reportP supports the revition desried in vrile BnnotteBF he vrile BtestingB onjuntion with pigure SF is used to mke it esier to test over using visp elgorithms IS
@defvr BlineElimitB USA @lispXdefun reportP @pA @se @sttus pA @prolim 9@speil BdepthB BllB @Xforgotten nilA BoutB BdoneBAA @Xhidden @mp 59reportP @sus pAAA @lispXdefun report @Xshow @8key @fn nilA @ond @@reportleEsus pA @out BstndrdEoutputBA @reportQ pA @ll nilAA @let @@BdepthB @IC BdepthBAAA @let @pA @mp 59reportP @sus pAAAA @ond @@reportle pA @@not @stremp outAA @reportQ pAAAAAA @withEopenEfile @lispXdefun reportle @pA @s out Xdiretion XoutputA @nd @eq @sttus pA XshowA @report Xfn fn Xll ll Xout sAAA @or BllB @@null BpointsBA @not @a @hit pA BhitBAAAAA @formt out 4~7xo definitions nnottedF4AA @lispXdefun reportleEsus @pA @@not fnA @nd @not @eq @sttus pA XforgottenAA @reportI BpointsB ll outAA @or BllB @not @reportle pAAA @@setq p @find fn BpointsB @some 59@lmd @sA Xkey 59fnEnmeAA @or @reportle sA @reportI @list pA ll outAA @reportleEsus sAAA @t @formt out 4~7~e is not nnottedF4 @sus pAAAA fnAAAA @vluesAA @lispXdefun reportQ @pA @setq BdoneB nilA @lispXdefun fnEnme @pA @letB @@BprintEprettyB nilA @let @@form @dr @r @nme pAAAAA @BprintElevelB QA @nd @onsp formA @BprintElengthB nilA @onsp @dr formAA @m @formt nil @dr formAAAA 4Y~d~XE~YC~~f ~~g4 BdepthB @lispXdefun reportI @ps BllB BoutBA @a @hit pA BhitBA @let @@BdepthB HA @BdoneB tAA @r @nme pAAAA @mp 59reportP psA @limit @E BlineElimitB VAAA @when BdoneB @when @b @length mA limitA @formt BoutB @setq m @suseq m H limitAAA 4~7Yell points exerisedF4AAAA @formt BoutB 4~7~e `~b4 m @id pAAAA pigure IHX he ode for the prt of over tht prints reportsF
rt IF into defmroF hey re indiretly supported edening defun nd defmro is onveE y overD s long s their denitions re red nient pproh to use for supporting overD fter overXnnotte hs een evlutedF howeverD it is in generl rther dngerous yn the fe of itD it is not orret to use thing to doF yne prolem is tht for over sulis to renme forms in odeD euse every to operte orretlyD overXnnotte must e instne of the indited symols is hngedD exeuted efore ny of the denitions you wish whether or not they re tully uses of the to nnotte re redF por instneD pigure T indited forms nd whether or not they re in would not work if n evlEwhen were wrpped quoted listsF xeverthelessD over uses sulis round the topElevel forms s groupF for two resonsF hen nnottion is in eetD the new defE pirstD in ontrst to ode wlkerD sulis is initions of defun nd defmro use sulis to very simpleF @he only understnding of visp reple every instne of ifD ondD etF with speE struture tht over needs is how to seprte il mros EifD EondD etF @see pigure IQAF the delrtions from the ody of denitionD hening forms reted y the user @eFgFD def see the funtion prseEodyFA in pigure IQA re typilly mros tht expnd wost prolems n esy e void y resistE IT FgF ters
@lispXdefmro nnotte @tEorEnilA @defvr BhekB @evlEwhen @evl lod ompileA 9@@or F EorA @nd F EndA @nnotteI DtEorEnilAAA @if F EifA @when F EwhenA @unless F EunlessA @lispXdefun nnotteI @flgA @ond F EondA @se F EseA @shdowingEimport @typese F EtypeseAAA @setEdifferene 9@defun defmroA @pkgeEshdowingEsymols BpkgeBAAA @lispXdefun proess @def def fn rgl A @when @nd flg @not BtestingBAA @if @not @or BnnottingB @wrn 4goverge nnottion ppliedF4AA @find fn @setq BnnottingB @not @null flgAAAA BpointsB Xkey 59fnEnmeAAA @lispXdefmro defun @n rgl 8ody A @Ddef Dfn Drgl FD A @proess 9defun 9lispXdefun n rgl AA @multipleEvlueEind @dels A @lispXdefmro defmro @n 8ody A @prseEody A @proess 9defmro 9lispXdefmro n AA @setq @sulis BhekB AA @let @@nme @lispXdefun prseEody @odyA @@Xreh @let @@dels nilAA @Ddef Dfn DrglAAAAA @when @stringp @r odyAA @evlEwhen @evl lod ompileA @push @pop odyA delsAA @ddEtopEpoint @loop @unless @nd @onsp @r odyAA 9D@mkeEpoint Xnme nmeAA @eq @r odyA @Ddef Dfn Drgl Dd dels 9delreAA D@H @mkeEpoint Xnme @return nilAA nmeA @push @pop odyA delsAA nme AAAAAAA @vlues @nreverse delsA odyAAA
pigure IIX he ode for the prt of over tht nnottes denitionsF
@ievErix @iev vyeh gywsviA @gyiXXehhEyEysx 9@xsv Xry H @5Ia@Xiegr @hip x wB @ AAAA xsvAA @vsXhip x wB @ A @gyiXXigyhErs 9@xsv Xry H @5I5A xsvAA @vi @@sqx IAA @gyiXXigyhErs 9@xsv Xry H @5Pa@Xiegr @rix @wsx A @i sqx @E sqxAA @i @E AAAA 5I5A @@xsv Xrshhix H @@Xiegr @wsx AA 5P5 5I5A xsvA @xsv Xry H @@XxyxEx vv @wsx AA 5P5 5I5A xsvA @xsv Xry H @@Xx vv @wsx AA 5P5 5I5A xsvAAAA @sp @yqx @gyiXXigyhErs 9@xsv Xrshhix H @@Xiegr @wsx AA 5P5 5I5A xsvAA @wsx AA @yqx @gyiXXigyhErs 9@xsv Xry H @@XxyxEx vv @wsx AA 5P5 5I5A xsvAA @i sqx @E sqxAA @i @E AAA @yqx @gyiXXigyhErs 9@xsv Xry H @@Xx vv @wsx AA 5P5 5I5A xsvAA xsvAA FFFAAA
pigure IPX rt of the nnotted denition of myB from pigure RF
ing the tempttion to use ifD ondD etF s vriE eondD the use of sulis supports two key le nmesF eny remining diulties n e fetures of over tht would e very diult tolerted euse over is merely prt of sfE to support using ode wlkerF st insures tht folding for testing system rther thn prt of only onditionl forms tht literlly pper in the system to e deliveredF e sutle diulty the denition re nnotted @s opposed to ones onerns nd nd orF hey re used s type tht ome from mro expnsionsAD nd yetD speiers s well s onditionl formsF his onditionls tht ome from the expnsion of diulty is prtly overome y the type deE nnotted mros re nnottedF @xote tht nitions t the end of pigure IQF the literls tht turn into onditionls in the visp elgorithms IU
@defvr BfixB @def Eif @pred then 8optionl @else nilAA 9@@Eor F orA @End F ndA @Eif F ifA @if D@Ehide predA @Ewhen F whenA @Eunless F unlessA D@ then XnonEnull predA @Eond F ondA @Ese F seA D@ else Xnull predAAA @Etypese F typeseAAA @def Ewhen @pred 8rest tionsA @prolim 9@speil BsusB BsupBAA @if D@Ehide predA D@ @progn FD tionsA @lispXdefmro supEm @A nilA XnonEnull predA @lispXdefmro def @nme rgs formA D@ nil Xnull predAAA @lispXdefmro Dnme @8whole w Dd rgs @def Eunless @pred 8rest tionsA 8environment envA @if @not D@Ehide predAA @letB @@BsusB nilA D@ @progn FD tionsA Xnull predA @BsupB D@ nil XnonEnull predAAA @@Xreh D@sulis BfixB wAA FD@mroexpndEI @def Eond @8rest sA @list 9supEmA envAAA @EondH @gensymA sAA @p @mkeEpoint Xnme BsupBAA @form DformAA @lispXdefun EondH @vr sA @setf @sus pA @nreverse BsusBAA @ond @@null sA @ nil XllEnullAA @H p BsupB @list formAAAAA @@eq @r sA tA @ @if @dr sA @lispXdefmro @ody 8rest msgA @progn FD@dr sAA @I @list DodyA msg XshowAA tA XfirstEnonEnull tAA @lispXdefmro Ehide @A @@dr sA @I @list DA @list Xreh A XhiddenAA @if D@Ehide @r sAA D@ @progn FD@dr sAA @evlEwhen @evl lod ompileA XfirstEnonEnull @r sAA @lispXdefun I @ m sA D@EondH vr @dr sAAAA @let @@n @ons @sulis BfixB @t @let @@Dvr @list FDmAA D@Ehide @r sAAAA BsupBAAA @if Dvr @push @mkeEpoint Xnme n Xsttus DsA D@ vr XfirstEnonEnull BsusBA @r sAA @H @mkeEpoint Xnme n Xsttus DsA D@EondH vr n DAAA @dr sAAAAAAA @lispXdefun H @p sup A @def Eor @8rest psA @EorH psAA @mrolet @@supEm @A 9DsupAA @reordEhit 9DpA @lispXdefun EorH @psA FDAA A @if @null @dr psAA @ @r psA XevlEll @r psAA @def Ese @key 8rest sA @let @@vr @gensymAAA @se D@Ehide keyA @let @@Dvr D@Ehide @r psAAAA FD@EseH sAAA @if Dvr @def Etypese @key 8rest sA D@ vr XfirstEnonEnull @typese D@Ehide keyA @r psAA FD@EseH sAAA D@EorH @dr psAAAAAAA @lispXdefun EseH @sA @def End @8rest psA @let @@stuff @mpr 59EseI sAAA @ond FD@mplist 59EndH @when @not @memer @r @lst sAA @or ps @list tAAAAA 9@t otherwiseAAA @lispXdefun EndH @psA @setq stuff @if @null @dr psAA @non stuff @t D@ @r psA XevlEll @r psAAA @@t D@ nil XseletEnoneAAAAAA @@not D@Ehide @r psAAA stuffAA D@ nil XfirstEnull @r psAAAAA @lispXdefun EseI @luseA @deftype End @8rest A @nd FD AA @D@r luseA D@ @progn FD @dr luseAA Xselet @deftype Eor @8rest A @or FD AA @r luseAAAA
pigure IQX he ode for the prt of over tht nnottes onditionlsF IV FgF ters
ode generted y mro re quoted in the erisedF roweverD it is essentil tht proessing ody of the mroFA e very fst when n exerised point is exerised pigure IP shows prt of the results of nE seond timeFA notting the funtion myB from pigure RF he eondD the sheme must work relily with nnotted denition is preeded y ll on interpreted odeD with ompiled ode loded ddEtopEpointD whih enters point desriing from lesD nd with ode tht is inrementlly the denition into BpointsBF ithin the defE ompiled on the yF his introdues numer initionD lls on reordEhit re introdued t of strong onstrintsF sn prtiulrD you nnot strtegi lotionsF ih ll ontins quoted depend on using some desriptive dt struE point tht is essentilly templte for wht ture uilt up during ompiltionD euse you should e introdued into BpointsBF he rst nnot ssume tht ompiltion will ourF yn when in myB is onverted into n if tht hs the other hndD if you use quoted dt struE ses orresponding to the suess nd filure tures s in pigure IPD you nnot mke ny of the predite tested y the whenF he ll ssumptions out wht shring will exist or on reordEhit tht preedes this if ontins whether they will e opiedD euse some visp point with supoints tht estlishes the ses ompilers feel free to mke mjor hnges in of the ifF his ensures tht oth ses of the quoted listsF if will e present in BpointsB s soon s the o hieve high eienyD reordEhit @see if is exerisedD even if only one of the ses is pigure VA lters its rgument y sideEeet to exerisedF mrk it exerisedF ideEeeting ompiled he hidden point ssoited with the prediE onstnt is inherently dngerousD ut is relE te tested y the when estlishes n ppropriE tively sfe hereD euse the hnged vlue is te ontext for points within the predite itE n integerD nd the point dt struture nnot selfF st is unneessry in this exmpleD euse e shred with ny other point dt strutureD there re no suh pointsF sn the ond in the euse no two points n hve the sme nmeF funtion g in pigure TD similr hidden point he rst time given ll on reordEhit ssoited with the rst predite tested serves is enounteredD it enters the point whih is its to orretly position the points ssoited with rgument into BpointsBF his is done y rst the nd @see pigure UAF looking to see if the point is lredy there @eFgFD euse it ws entered y n ddEtopEpoint or por the most prtD the mros in pigure IQ is suordinte point tht ws expliitly enE operte in strightforwrd wys to generte nE tered s prt of its superior pointAF sf it is not notted onditionlsF roweverD defD D ID nd thereD it is opied nd inserted s suordiE H intert in somewht sutle wy using nte point of the pproprite superior pointF mrolet to ommunite the nme of suE @fy this proessD BpointsB is dynmilly uilt perior point to its suordintesF his ould up in extly the sme wy when exeuting inE hve een done more simply with ompilerEletY terpreted nd ompiled odeFA sf the superior howeverD ompilerElet is slted to e removed point nnot e foundD nothing is doneF @his from gommon vispF n only hppen when the nnottion of the nderlying pprohF he nnottion urrently exeuting funtion hs een forgotE sheme used y over is designed to meet two tenFA golsF pirstD it must introdue s little overE he seond time ll on reordEhit is enE hed s possile when the nnotted funtion ountered the only thing it hs to do is hek runsF @st does not mtter if the proess of inE tht the point hs een exerisedF sf it hsD serting nnottion is expensive nd it does not nothing needs to e doneF sf overXreset hs mtter if the proess of printing reports is exE een doneD then the hek will filD nd reordE pensiveF st does not even mtter if proessing is hit relotes the point in BpointsBD nd sets the reltively expensive the rst time point is exE hit gF @his seond lookup ould e voided visp elgorithms IW if the quoted point hd een diretly inserted ytining gyi into BpointsB insted of opiedF roweverD this over is written in portle gommon visp is unsfe for two resonsF pirstD the shring nd hs een tested in severl dierent gomE would men tht sideEeets to BpointsB would mon visp implementtionsF he full soure for trnslte into sideEeets to ompiled list onE over is shown in pigures VD IHD IID nd IQF stntsF his will use mny visp systems to sn dditionD the soure n e otined over low up in unexpeted wysF eondD in some the internet y using ftpF gonnetion should visp systems ompiling n interpreted funtion e mde to pFesFwsFih @internet numer n use the quoted lists in it to e opiedF IPVFSPFQPFTAF vogin s nonymous4 nd opy es resultD you nnot depend tht ny shrE the les shown elowF ing set up etween glol dt struture nd quoted onstnts will e preservedFA sn the diretory GpuGlptrsG he opertion of over requires tht eh overFlisp soure ode point e given unique identifying nmeF he overEtestFlisp test suite overEdoFtxt rief doumenttion nming sheme used ssumes tht given onE ditionl form will not hve two predites tht he ontents of pigures VD IHD IID nd IQ re equl nd tht hunk of strightline ode nd the les ove re opyright IWWI y the will not ontin two onditionl forms tht re wsshusetts snstitute of ehnologyD gmE equlF sf this ssumption is violtedD over ridge weF ermission to useD opyD modifyD will merge the two resulting points into oneF nd distriute this softwre for ny purpose nd he power of vispF over is good exE without fee is herey grntedD provided tht mple of the power of visp s tool for uildE this opyright nd permission notie pper in ing progrmming environmentsF feuse visp ll opies nd supporting doumenttionD nd ontins simple representtion for visp proE tht the nmes of ws ndGor the uthor re grmsD it is esy to write systems tht onE not used in dvertising or puliity pertining vert progrms into other progrmsF feuse to distriution of the softwre without speiD visp enompsses oth the lnguge denition written prior permissionF ws nd the uthor nd the runEtime environmentD it is esy to mke no representtions out the suitility write systems tht oth mnipulte the lnE of this softwre for ny purposeF st is provided guge nd extend the runEtime environmentF s is4 without express or implied wrrntyF ystems like over re regulrly written for ws nd the uthor dislim ll wrrnties nd other elgolElike lngugesY howeverD this with regrd to this softwreD inluding ll imE is muh hrder to do thn in vispF plied wrrnties of merhntility nd tnessF sn no event shll ws or the uthor e lile for ny speilD indiret or onsequentil dmE eknowledgments ges or ny dmges whtsoever resulting from loss of useD dt or protsD whether in n tion he onept of ode overge is n old oneD of ontrtD negligene or other tortious tionD whih is used y mny @if not mostA lrge proE rising out of or in onnetion with the use or grmming orgniztionsF over is the result performne of this softwreF of severl yers of prtil use nd evolutionF his pper desries reserh done t the eferenes mit i vortoryF upport ws provided y drpD nsfD imD nynexD iemensD perryD nd I FgF tersD upporting the egression mF he views nd onlusions presented here esting of visp rogrmsD4 egw visp re those of the uthor nd should not e interE ointersD R@PAXRU{SQD tune IWWIF preted s representing the poliiesD expressed or impliedD of these orgniztionsF PH FgF ters visp elgorithms PI
QF smplementing ueues in visp
ihrd gF ters nd eter xorvig
e queue is dt struture where items re entered one t time nd removed one t time in the sme order|iFeFD rst in rst outF hey re the sme s stks exept tht in stkD items re removed in the reverse of the order they re entered|iFeFD lst in rst outF ueues re most preisely desried y the funtions tht t on themX
@mkeEqueueA gretes nd returns new empty queueF @queueEelements queueA eturns list of the elements in queue with the oldest element rstF he list returned my shre struture with queue nd therefore my e ltered y susequent lls on enqueue ndGor dequeueF @emptyEqueueEp queueA eturns t if queue does not ontin ny elements nd nil otherwiseF @queueEfront queueA eturns the oldest element in queue @iFeFD the element tht hs een in the queue the longestAF hen queue is emptyD the results re undenedF @dequeue queueA ueue is ltered @y sideEeetA y removing the oldest element in queueF he removed element is returnedF hen queue is emptyD the results re undenedF @enqueue queue itemA ueue is ltered @y sideEeetA y dding the element item into queueF he return vlue @if nyA is undenedF
@emptyEqueueEp @setq q @mkeEqueueAAA A t @progn @enqueue q 9A @enqueue q 9A @queueEfront qAA A @progn @enqueue q 9A @enqueue q 9dA @dequeue qAA A @queueEelements qA A @ dA
rving enqueue nd dequeue lter queue y sideEeet is onvenient for most uses of queues nd llows for eient implementtionsF roweverD it mens tht re must e tken when queues re mnipultedF por instneD if the output of queueEelements must e preserved eyond susequent use of enqueue or dequeue it must e opied @eFgFD with opyElistAF
ueues smplemented ith vists visp9s eponymous dt strutureD the listD n e used to represent wide vriety of dt strutures inluding queuesF he implementtion of queues in pigure IR represents queue s ons ell whose r is list of the elements in the queueD ordered with the oldest rstF he implementtion in pigure IR is simple nd esy to understndF he lose similrity of queues nd stks is highlighted y the ft tht dequeue is implemented using pop nd enqueue is implemented in wy tht is very similr to pushF he one thing tht my not e immeditely ler out the implementtion in pigure IR is the reson why heder ell is neessryD insted of just using the list of elements in the queue to represent the queueF he heder ell is needed so tht n element n e dded into n empty queue @nd the lst element removed from oneEelement queueA purely y sideEeetF por this to workD n empty queue must e some kind of mutle struture tht n e pointed to @eFgFD not PP FgF ters
@defun mkeEqueue @A @list nilAA @defun queueEelements @qA @r qAA Yspe time @defun emptyEqueueEp @qA @null @r qAAA Y P P @defun queueEfront @qA @r qAA Y P P @defun dequeue @qA @pop @r qAAA Y R R @defun enqueue @q itemA @setf @r qA @non @r q A @list itemAAAA Y R y@nA @setq q @mkeEqueueAA A @nilA @progn @enqueue q 9A @enqueue q 9A @enqueue q 9A qA A @@ AA
pigure IRX ueue implementtion using nonF just nilAF he funtions in pigure IR re divided into two groups to reet the ft tht the lst four funtions re lled muh more often thn the rst twoF es resultD it is more importnt tht they e eientF he rst olumn of numers on the right of pigure IR shows the size of the ode required if the orresponding funtion is ompiled in line t the point of useF he size is speied s the numer of primitive opertions @rD drD onsD listD nullD rplD rpldD setqD rnhingD generting onstnt nilD nd lling n outEofEline funtionA tht re neessryF por instneD dequeue requires R si opertions @ rD two drs nd rpldAF he spe numers nnot e tken s extly reeting ny prtiulr visp implementtionD euse given visp ompiler my rete ode tht performs unneessry opertionsD nd given hrdwre pltform my require multiple instrutions to support some of the primitive opertionsF roweverD this does not mtter gret delD euse the reltive ode size of funtions is the key thing tht is importnt in the ontext of this pperF @he vlidity of the numers in pigure IR s sis for this kind of omprison hs een veried y looking t the ode produed y the ompilers for the s ixplorer nd the ymolis visp whineFA en importnt virtue of the implementtion of queues in pigure IR is tht the funtions re oded omptly enough tht it is prtil to ompile ll of them in line @iFeFD y delring them inlineAF sn most gommon visp implementtionsD this is signintly more eient then using outEofEline funtion llsF he seond olumn of numers on the right of pigure IR shows the numer of si opertions tht hve to e exeuted t run timeF sf there is ny rnhing requiredD the numer reets the ontrol pth tht is most likely to e tkenF hese numers revel tht there is prolem with the implementtionF wost of the funtions hve smll xed osts tht re independent of the size of the queueF roweverD the time required to perform the non in enqueue is proportionl to the size of the queueF
ueeping ointer to the ind of the ueue
he prolem with non is not tht it mkes n expensive hnge @it merely performs one rpldAD ut tht it hs to serh down the entire list to lote the ons ell ontining the lst queue elementF his ineieny n e overome y mintining pointer to the end of the list of queue elementsF sn prtiulrD ffx visp supported queue dt struture extly like the one in pigure IR exept tht the dr of the heder ell ws used s pointer to the list ell ontining the lst element in the queue @if nyAF sing this pointerD the six queue funtions n e supported s shown in pigure ISF @sn ffx vispD the funtion enqueue ws lled tonFA he only dierene etween pigure IS nd pigure IR is in the implementtion of enqueueFst visp elgorithms PQ
@defun mkeEqueue @A @list nilAA @defun queueEelements @qA @r qAA Yspe time @defun emptyEqueueEp @qA @null @r qAAA Y P P @defun queueEfront @qA @r qAA Y P P @defun dequeue @qA @pop @r qAAA Y R R @defun enqueue @q itemA Y W V @let @@newElst @list itemAAA @if @null @r qAA @setf @r qA newElstA @setf @ddr qA newElstAA @setf @dr qA newElstAAA @setq q @mkeEqueueAA A @nilA @progn @enqueue q 9A @enqueue q 9A @enqueue q 9A qA A @@ F 5Ia@AA F 5I5A
pigure ISX imple queue implementtion using n end pointerF is trnsformed into onstntEtime opertion nd is therefore very muh fsterF nfortuntelyD enqueue is now too lrge to e omfortly ompiled in lineF he implementtion of enqueue in pigure IS is lrger thn in pigure IR primrily euse it hs to test for speil oundry onditionF hen the input queue is emptyD enqueue hs to do rpl to insert the @one elementA list of queue elements in the r of the heder ellY otherwise it hs to do rpld to extend the list of queue elementsF
woving the foundry est to fetter le
st is possile to remove the oundry test from enqueue y rerrnging the queue dt struture s followsF pirstD the two omponents of the heder ell re interhngedD putting the pointer to the end of the queue in the rF eondD onvention n e dopted tht n empty queue9s end pointer points to the queue itselfF hese two hnges llow the sme ode to e used for inserting n element into queue whether or not the queue is emptyD see pigure ITF nfortuntelyD while the two hnges ove simplify enqueueD they mke it more diult to implement dequeueF he prolem is tht dequeue now hs speil oundry ondition to test for|if the queue eomes emptyD the queue9s lst pointer hs to e mde to point to the queue itselfF roweverD euse this is simpler speil se thn the one in enqueue in pigure ISD it does not led to s muh overhedF elsoD sine some pplitions do signintly more enqueues thn dequeues nd no pplition does more dequeuesD the trdeEo is worthwhileF he implementtion pproh in pigure IT tkes sutle dvntge of the typeless nture of
@defun mkeEqueue @A @let @@q @list nilAAA @setf @r qA qAAA @defun queueEelements @qA @dr qAA Yspe time @defun emptyEqueueEp @qA @null @dr qAAA Y P P @defun queueEfront @qA @dr qAA Y P P @defun dequeue @qA Y U T @let @@elements @dr qAAA @unless @setf @dr qA @dr elementsAA @setf @r qA qAA @r elementsAAA @defun enqueue @q itemA @setf @r qA @setf @dr qA @list itemAAAA Y R R @setq q @mkeEqueueAA A 5Ia@5I5A @progn @enqueue q 9A @enqueue q 9A @enqueue q 9A qA A @5Ia@A F 5I5A
pigure ITX e ompt nd eient queue implementtionF PR FgF ters
@defun mkeEqueue @A @let @@q @list nilAAA @ons q qAAA @defun queueEelements @qA @dr qAA Yspe time @defun emptyEqueueEp @qA @null @dr qAAA Y Q Q @defun queueEfront @qA @dr qAA Y Q Q @defun dequeue @qA @r @setf @r qA @dr qAAAA Y R R @defun enqueue @q itemA @setf @dr qA @setf @ddr qA @list itemAAAA Y R R @setq q @mkeEqueueAA A @5Ia@nilA F 5IA @progn @enqueue q 9A @enqueue q 9A @enqueue q 9A qA A @@nil F 5Ia@AA F 5I5A
pigure IUX enother ompt nd eient queue implementtionF vispF sn most other lngugesD the heder ell for queue would e dierent type of struture from the ells forming the linked list of queue elementsF his would lok enqueue from treting the dr of the heder ell the sme s the dr of linked list ellF @sn some lngugesD this prolem ould e overome y judiious use of type unioning or typeEhek ypssingFA
iliminting the foundry est y edding gell e dierent wy to improve on pigure IS is to eliminte the need for ny oundry tests t llD y dding dummy ell into the list holding the elements in the queue s shown in pigure IUF his llows enqueue nd dequeue to operte essentilly s if the queue were never emptyF roweverD the other funtions hve to e djusted to skip over the dummy ellD nd therefore eome it longerF hether or not the implementtion in pigure IU is etter thn the one in pigure IT depends on the detils of your visp implementtion nd whih queue opertions you use mostF por instneD if lls on dequeue re prtiulrly infrequent @eFgFD euse list of the items queued is the primry result desiredAD then the implementtion in pigure IT is etterF sn ontrstD if the visp smplemenE ttion hs speil hrdwre support for following hins of pointers through ons ells @eFgFD the s ixplorerAD pigure IU is etterF
ueues smplemented ith etors
vists re onvenient sis for queuesF sn prtiulrD the intertion of ons nd grge olletion provides support for queues of unounded length without ny speil provisions hving to e mdeF roweverD listEsed implementtions re wsteful of memoryD euse n entire ons ell hs to e used to store eh element in the queueD nd s elements re enqueued nd dequeuedD new ons ells ontinully hve to e llotedF wemory eient implementtions of queues re possile using vetorsF his pproh is often tken in other lngugesF pigure IV shows n implementtion like those usully shown in introduE tory dtEstruture textsF he si pproh is to store the elements of queue s setion of vetor treted s ringF he elements re stored in reverse order in the vetor so tht omprison with zero n e used to detet when either the front or end pointers reh the edge of the vetorF he primry dvntge of vetorEsed implementtion is tht it requires only out hlf the memory to store the ontents of the queueF sf the queue elements re shorter thn word @eFgFD hrters or itsA even more svings re possileF sn dditionD enqueuing nd dequeuing elements does not generte ny grge t ll @unless the queue size gets so lrge tht n enlrged vetor hs to e llotedAF he primry disdvntge of vetorEsed implementtion is tht it is more omplitedF sn prtiulrD it hs to do ll its own memory mngementF his mens tht the queue still tkes up lot of spe even when it is emptyF sn dditionD provision hs to e mde for extending the vetor holding the queue if it eomes fullF @sn gure IVD this is supported y the funtion extendEqueue visp elgorithms PS
@defstrut q front end size elementsA @defun mkeEqueue @8optionl @size PHAA @mkeEq Xfront @IE sizeA Xend @IE sizeA Xsize size Xelements @mkeEsequene 9simpleEvetor sizeAAA @defun queueEelements @qA @when @not @emptyEqueueEp qAA @do @@i @IC @qEend qAA @IC iAA @result nilAA @nilA @when @a i @qEsize qAA @setq i HAA @push @svref @qEelements qA iA resultA @when @a i @qEfront qAA @return resultAAAAA Yspe time @defun emptyEqueueEp @qA @a @qEfront qA @qEend qAAA Y Q Q @defun queueEfront @qA @svref @qEelements qA @qEfront qAAA Y Q Q @defun dequeue @qA Y U T @let @@front @qEfront qAAA @progI @svref @qEelements qA frontA @when @zerop frontA @setq front @qEsize qAAA @setf @qEfront qA @IE frontAAAAA @defun enqueue @q itemA Y IH V @let @@end @qEend qAAA @setf @svref @qEelements qA endA itemA @when @zerop endA @setq end @qEsize qAAA @when @a @setf @qEend qA @IE endAA @qEfront qAA @extendEqueue qAAAA @defun extendEqueue @qA @letB @@elements @qEelements qAA @size @qEsize qAA @newEsize @B P sizeAA @divide @IC @qEfront qAAA @newEend @C divide size EIAA @new @mkeEsequene 9simpleEvetor newEsizeAAA @reple new elements XendP divideA @reple new elements XstrtI @IC newEendA XstrtP divideA @setf @qEelements qA newA @setf @qEend qA newEendA @setf @qEsize qA newEsizeAAA @progn @setq q @mkeEqueueAA @dotimes @i IUA @enqueue q 9EA @dequeue qAA @dotimes @i SA @enqueue q iAA qA A 5@queue front IU end P size PH elements 5@PIHEEEEEEEEEEEEEEERQAA
pigure IVX e trditionl vetorEsed queue implementtionF
nd fullness test in enqueueFA henever possileD it is good to strt the queue t size tht is suient to hold the mxiE mum expeted sizeD rther thn strting t n ritrry size like PHF por this reson the funtion mkeEqueue is extended y giving it n optionl size rgumentF qiven rm mximumEsize informE tion one ould go further nd dispense with extendEqueue nd the fullness test in enqueueF roweverD this is dngerous prtie nd sves reltively littleF st is worthy of note tht it would e mistke to use n djustle rry in the queue dt strutureF his would mke extending the rry little it esierD ut would slow up ll of the other opertions on the vetorF edjustle rrys re only helpful when there my e mny pointers diretly to the rry tht hs to e extendedF heneverD s hereD there is known to e only one pointerD it is muh etter to hnge the pointer to point to new rryD thn to extend the rry itselfF PT FgF ters
@defstrut q front end size elementsA @defun mkeEqueue @8optionl @size PHAA @mkeEq Xfront @E size IA Xend @E size IA Xsize size Xelements @mkeEsequene 9simpleEvetor sizeAAA @defun queueEelements @qA @do @@i @IC @qEend qAA @IC iAA @result nilAA @@b i @qEfront qAA resultA @push @svref @qEelements qA iA resultAAA Yspe time @defun emptyEqueueEp @qA @a @qEfront qA @qEend qAAA Y Q Q @defun queueEfront @qA @svref @qEelements qA @qEfront qAAA Y Q Q @defun dequeue @qA Y S S @progI @svref @qEelements qA @qEfront qAA @def @qEfront qAAAA @defun enqueue @q itemA Y V U @setf @svref @qEelements qA @qEend qAA itemA @when @minusp @def @qEend qAAA @shiftEqueue qAAA @defun shiftEqueue @qA @letB @@elements @qEelements qAA @new elementsAA @when @b @qEfront qA @G @qEsize qA PAA @setq new @mkeEsequene 9simpleEvetor @B P @qEsize qAAAA @setf @qEelements qA newA @setf @qEsize qA @B P @qEsize qAAAA @setf @qEend qA @E @qEsize qA P @qEfront qAAA @reple new elements XstrtI @IC @qEend qAAA @setf @qEfront qA @IE @qEsize qAAAAA @progn @setq q @mkeEqueueAA @dotimes @i IUA @enqueue q 9EA @dequeue qAA @dotimes @i SA @enqueue q iAA qA A 5@queue front IW end IR size PH elements 5@PIHEEEEEEEEEEEERQPIHAA
pigure IWX e fster vetorEsed queue implementtionF
enother prolem is tht queueEelements eomes n y@nA opertionD sine it hs to opy the queue ontents into listF sf you wnt to e le to esily get list of the elements in queueD it is etter to strt with listEsed implementtionF e nl prolem with pigure IV is the ineieny of some of the key opertionsF he funtions emptyEqueue nd queueEfront re smll nd ould e oded in lineF roweverD dequeue is on the orderline in size nd enqueue is quite lrgeF
hifting ss fetter hn sing ing pigure IW shows the kind of improvements thn n e otined using little ingenuityF he key dierene etween pigure IW nd pigure IV is tht the implementtion does not tret the vetor s ringF therD whenever the queue rehes the end of the vetorD it is shifted over @y the funtion shiftEqueueD whih lso extends the vetor if neessryAF yne might well imgine tht operting on the vetor s ring hd to e etter thn shifting everything over every time the queue rehes the edge of the vetorF roweverD s long s the queue is signintly shorter thn the vetor @sy only PGQ the length or lessA then shifting does not hve to our very oftenD nd performing osionl shifts ends up eing heper thn omplex derementing of the pointers ll of the timeF hequeue nd enqueue oth eome signintly more eientD nd dequeue eomes short enough to esily ode in lineF ell in llD exept for the ft tht the queue struture hs to e it igger for things to work visp elgorithms PU out eientlyD the implementtion in pigure IW is etter thn the one in pigure IV in ll respetsF qiven its memory eieny nd quite resonle speedD it is worth onsidering pigure IW s n lterntive to listEsed implementtion in ny sitution where the funtion queueEelements is not usedF
gonlusion visp provides n llEpurpose dt struture|the list|whih is often dequte for rpid proE totypingF fut when n eient solution is requiredD visp progrmmers must hoose their dt strutures refullyF pigures IT{IW show two eient list sed implementtions of queues nd two eient vetorEsed implementtionsF hih is pproprite to use depends on the detils of the ext sitution in questionF he vrious implementtions presented ove illustrte severl generl issues to keep in mind when seeking eient lgorithmsF sntroduing lignments of omponents n often eliminte speil ses @eFgFD the wy the queue dt struture is rerrnged in pigure ITAF ometimes omputtion n e moved from n expensive ontext to less expensive one @eFgFD moving the oundry test from enqueue to dequeue in pigure ITAF wny timesD it is etter to do little extr work ll the timeD then do n expensive hek to determine when extr work is relly needed @eFgFD indexing through the extr ell in pigure IU is etter in mny situtions thn testing for whether the list is emptyAF yther timesD it is etter to introdue extr work some of the time to eliminte stedy kground of work @eFgFD osionl wholesle shifting in pigure IW is etter thn ontinul performing omplex pointer steppingAF limming funtions down to inElineEle size n py ig prgmti dividendsF eove llD the only wy to get relly eient lgorithm is to experiment with mny lterntivesF