You are on page 1of 291

newLISP ForMacOSX,GNULinux,UnixandWindows

UserManualandReferencev.10.5.4201412

Copyright2013LutzMuellerwww.nuevatec.com.Allrightsreserved. Permissionisgrantedtocopy,distributeand/ormodifythisdocumentunderthetermsoftheGNUFreeDocumentationLicense, Version1.2oranylaterversionpublishedbytheFreeSoftwareFoundationwithnoInvariantSections,noFrontCoverTexts, andnoBackCoverTexts.AcopyofthelicenseisincludedinthesectionentitledGNUFreeDocumentationLicense. TheaccompanyingsoftwareisprotectedbytheGNUGeneralPublicLicenseV.3,June2007. newLISPisaregisteredtrademarkofLutzMueller.

Contents
UserManual
1. 2. 3. 4. Introduction Deprecatedfunctionsandfuturechanges InteractiveLispmode Commandlineoptions Commandlinehelpsummary SpecifyingfilesasURLs Noloadingofinit.lsp Stacksize Maximummemoryusage Directexecutionmode LoggingI/O Specifyingtheworkingdirectory newLISPasaTCP/IPserver TCP/IPdaemonmode SuppressingthepromptandHTTPprocessing ForcingpromptsinpipeI/Omode HTTPonlyservermode LocaldomainUnixsocketserver Connectiontimeout i n e t d daemonmode LinkingasourcefilewithnewLISPforanewexecutable 5. Startup,directories,environment

6. 7. 8.

9. 10. 11. 12.

13. 14.

15. 16.

17.

18.

19.

20. 21.

EnvironmentvariableNEWLISPDIR Theinitializationfilei n i t . l s p DirectoriesonLinux,BSD,MacOSX DirectoriesonWin32 ExtendingnewLISPwithsharedlibraries newLISPasasharedlibrary EvaluatingnewLISPexpressions Interactivemultilineexpressions Integer,floatingpointdataandoperators Biginteger,unlimitedprecisionarithmetic Evaluationrulesanddatatypes LambdaexpressionsinnewLISP n i l ,t r u e ,c o n s and( ) innewLISP Arrays Indexingelementsofstrings,listsandarrays Implicitindexingforn t h Implicitindexingandthedefaultfunctor Implicitindexingforr e s t ands l i c e Modifyreferencesinlists,arraysandstrings Destructiveversusnondestructivefunctions Makeadestructivefunctionnondestructive Earlyreturnfromfunctions,loops,blocks Usingc a t c h andt h r o w Usinga n d ando r Dynamicandlexicalscoping Contexts Symbolcreationincontexts Creatingcontexts Globalscope Symbolprotection Overwritingglobalsymbolsandbuiltins Variablesholdingcontexts Sequenceofcreatingcontexts Contextsasprogrammingmodules Contextsasdatacontainers Loadinganddeclaringcontexts Serializingcontextobjects Thecontextdefaultfunctor Functionswithmemory Hashfunctionsanddictionaries Passingdatabyreference Functionalobjectorientedprogramming FOOPclassesandconstructors Objects Thecolon: operatorandpolymorphism StructuringalargerFOOPprogram Concurrentprocessinganddistributedcomputing TheCilkAPI Distributednetworkcomputing JSON,XML,SXMLandXMLRPC Customization,localizationandUTF8 Customizingfunctionnames Switchingthelocale Decimalpointanddecimalcomma UnicodeandUTF8encoding FunctionsworkingonUTF8characters

FunctionsonlyavailableonUTF8enabledversions 22. Commasinparameterlists

FunctionReference
1. Syntaxofsymbolvariablesandnumbers 2. Datatypesandnamesinthereference 3. Functionsingroups Listprocessing,flowcontrol,andintegerarithmetic Stringandconversionfunctions Floatingpointmathandspecialfunctions Matrixfunctions Arrayfunctions Bitoperators Predicates Dateandtimefunctions Statistics,simulationandmodelingfunctions Patternmatching Financialmathfunctions FileandI/Ooperations ProcessesandtheCilkAPI Fileanddirectorymanagement HTTPnetworkingAPI SocketTCP/IP,UDPandICMPnetworkAPI Reflectionandcustomization Systemfunctions Importinglibraries newLISPinternalsAPI 4. Functionsinalphabeticalorder !+*/%AbApAsBaCaClCoCuDeDiDoEn ExFiFlGaGlInLaLiMaMuNetNewNtPa PrRaReaRegSeaSeqSlStSyTiTrUtWr

Appendix
ErrorCodes SystemSymbols GNUFreeDocumentationLicense GNUGeneralPublicLicense

()

newLISPUserManual
1.Introduction
newLISPfocusesonthecorecomponentsofLisp:lists,symbols,andlambdaexpressions.Tothese,newLISPaddsarrays,implicit indexingonlistsandarrays,anddynamicandlexicalscoping.Lexicalscopingisimplementedusingseparatenamespacescalled contexts.

TheresultisaneasiertolearnLispthatisevensmallerthanmostSchemeimplementations,butwhichstillhasabout350builtin functions.Notmuchover200kinsize,newLISPisbuiltforhighportabilityusingonlythemostcommonUnixsystemClibraries. Itloadsquicklyandhasasmallmemoryfootprint.newLISPisasfastorfasterthanotherpopularscriptinglanguagesandusesvery fewresources. Bothbuiltinanduserdefinedfunctions,alongwithvariables,sharethesameglobalsymboltreeandaremanipulatedbythesame functions.Lambdaexpressionsanduserdefinedfunctionscanbehandledlikeanyotherlistexpression. newLISPisdynamicallyscopedinsidelexicallyseparatedcontexts(namespaces).ContextsinnewLISPareusedformultiple purposes.Theyallow(1)partitioningofprogramsintomodules,(2)thedefinitionofClassesinFOOP(FunctionalObjectOriented Programming),(3)thedefinitionoffunctionswithstateand(4)thecreationofHashtreesforassociativekeyvaluestorage. newLISP'sefficientredblacktreeimplementationcanhandlemillionsofsymbolsinnamespacesorhasheswithoutdegrading performance. newLISPallocatesandreclaimsmemoryautomatically,withoutusingtraditionalasynchronousgarbagecollection.Allobjects exceptforcontexts,builtinprimitives,andsymbolsarepassedbyvalueandarereferencedonlyonce.Uponcreationobjectsare scheduledfordelayeddeletionandLispcellsarerecycledfornewlycreatedobjects.Thisresultsinpredictableprocessingtimes withoutthepausesfoundintraditionalgarbagecollection.newLISP'suniqueautomaticmemorymanagementmakesitthefastest interactiveLispavailable.MorethananyotherLisp,itimplementsthedataequalsprogramparadigmandfullselfreflection. ManyofnewLISP'sbuiltinfunctionsarepolymorphicandacceptavarietyofdatatypesandoptionalparameters.Thisgreatly reducesthenumberoffunctionsandsyntacticformsnecessarytolearnandimplement.Highlevelfunctionsareavailableforstring andlistprocessing,financialmath,statistics,andArtificialIntelligenceapplications. newLISPhasfunctionstomodify,insert,ordeleteelementsinsidecomplexnestedlistsormultidimensionalarraystructures. BecausestringscancontainnullcharactersinnewLISP,theycanbeusedtoprocessbinarydatawithmoststringmanipulating functions. newLISPcanalsobeextendedwithasharedlibraryinterfacetoimportfunctionsthataccessdatainforeignbinarydatastructures. ThedistributioncontainsmodulesforimportingpopularClibraryAPIs. newLISP'sHTTP,TCP/IP,andUDPsocketinterfacesmakeiteasytowritedistributednetworkedapplications.ItsbuiltinXML interface,alongwithitstextprocessingfeaturesPerlCompatibleRegularExpressions(PCRE)andtextparsingfunctions makenewLISPausefultoolforCGIprocessing.ThesourcedistributionincludesexamplesofHTMLformsprocessing.newLISP canberunaasaCGIcapablewebserverusingitsbuiltinhttpmodeoption. newLISPhasbuiltinsupportfordistributedprocessingonnetworksandparallel,concurrentprocessingonthesameCPUwithone ormoreprocessingcores. ThesourcedistributioncanbecompiledforLinux,MacOSX/Darwin,BSDsSolaris,andWin32.newLISPcanbecompiledasa 64bitLP64applicationforfull64bitmemoryaddressing.

newLISPGS
newLISPGScomprisesagraphicaluserinterface(GUI)andlibraryserver.TheGUIfrontendiswritteninnewLISP,whereasthe libraryserverisJavabasedandusesthestandardJavaruntimeenvironmentinstalledonallWindowsandMacOSXplatforms. ApplicationsbuiltwithnewLISPGScanhavethehostoperatingsystem'snativelookandfeel.InterfacestoGTK,Tcl/Tkand OpenGLgraphicslibrariesarealsoavailable. newLISPandJavaareavailableformostoperatingsystems.ThismakesnewLISPGSaplatformindependentsolutionforwriting GUIapplications. FormoreinformationonnewLISPGS,seenewLISPGS.

Licensing
newLISPandnewLISPGSarelicensedunderversion3oftheGPL(GeneralPublicLicense).ThenewLISPdocumentationas wellasotherdocumentationpackagedwithnewLISParelicensedundertheGNUFreeDocumentationLicense. ()

2.Deprecatedfunctionsandfuturechanges
Sinceversion10.3.0newLISPcanswitchbetweenIPv4andIPv6modesduringruntimeusingthenewnetipvfunction.The6 commandlineoptioncanbeusedtostartnewLISPinIPv6mode.AftertransitiontoIPv6the6 commandlineswitchwillbe changedto4 forstartingupinIPv4mode. Theoldwritingp a r s e d a t e ofdateparseisstillrecognizedbutdeprecatedsinceversion10.3.0.Theoldwritingwillberemoved inafutureversion. Sinceversion10.4.6newLISPhasabuiltinfunctionjsonparsefortranslatingJSONdataintoSexpressions.Themodulefile j s o n . l s p isremovedfromthedistribution. Sinceversion10.4.8newLISPhasbuiltinsupportforunlimitedprecisionintegers.ThismakestheGNUGMPmoduleg m p . l s p obsolete. ()

3.InteractiveLispmode
ThebestwaytoexperienceLispandexperimentwithit,isusinginteractivemodeinaterminalwindoworoperatingsystem commandshell.Sinceversion10.3,newLISP'sreadevalprintloop(REPL)acceptsmultilinestatements. Toenteramultilinestatementhitthe[enter]keyonanemptylineafterthesystemprompt.Toexitmultilinemode,hitthe[enter] keyagainonanemptyline.Inthefollowingexamplecomputeroutputisshowninboldletters:
> ( d e f i n e( f o oxy ) ( +xy ) ) ( l a m b d a( xy )( +xy ) ) >( f o o34 ) 7 >

Note,thatmultilinemodeisonlypossibleinanOScommandterminalwindoworcommandshell.ThemonitorwindowintheJava basednewLISPGSIDEwillnotacceptmultilinestatements. InteractiveLispmodecanacceptoperatingsystemshellcommands.TohitanOScommandenterthe'! 'characterrightafterthe prompt,immediatelyfollowedbytheshellcommand:


>! l s* . h t m l C o d e P a t t e r n s . h t m l E x p r e s s i o n E v a l u a t i o n . h t m l L i c e n s e . h t m l > M e m o r y M a n a g e m e n t . h t m l n e w L I S P d o c . h t m l m a n u a l _ f r a m e . h t m l n e w l i s p _ i n d e x . h t m l n e w L I S P 1 0 . 3 R e l e a s e . h t m l n e w l i s p _ m a n u a l . h t m l

Intheexampleal s shellcommandisenteredtoshowHTMLfilesinthecurrentdirectory.OnMSWindowsad i r commandcould beusedinthesamefashion. Themodecanalsobeusedtocallaneditororanyotherprogram:

>! v if o o . l s p

TheVieditorwillopentoedittheprogram"foo.lsp".Afterleavingtheeditortheprogramcouldberunusingaloadstatement:
>( l o a d" f o o . l s p " )

Theprogramf o o . l s p isnowrun.Thismodeusing'! 'canalsobeusedfromthenewLISPGSIDE. WhenusingaUnixterminalorcommandshell,tabexpansionforbuiltinnewLISPfunctionscanbeused:


>( p r i p r i n t >( p r i p r i n t l n p r i m i t i v e ?

Afterenteringthecharacters( p r i hitthe[tab]keyoncetoshowallthebuiltinfunctionsstartingwiththesamecharacters.When hitting[tab]twicebeforeafunctionnamehasstarted,allbuiltinfunctionnameswillbedisplayed. OnmostUnix,parenthesismatchingcanbeenabledonthecommandlinebyincludingthefollowinglineinthefile. i n p u t r c inthe homedirectory:


s e tb l i n k m a t c h i n g p a r e no n

Notallsystemshaveaversionofl i b r e a d l i n e advancedenoughforthistowork. ()

4.Commandlineoptions,startupanddirectories
Commandlinehelpsummary
WhenstartingnewLISPfromthecommandlineseveralswitchesandoptionsandsourcefilescanbespecified.Executing:
n e w l i s ph

inacommandshellwillproducethefollowingsummaryofoptionsandswitches:
ht h i sh e l p nn oi n i t . l s p( m u s tb ef i r s t ) x< s o u r c e >< t a r g e t >l i n k vv e r s i o n s< s t a c k s i z e > m< m a x m e m M B >c e l lm e m o r y e< q u o t e dl i s pe x p r e s s i o n > l< p a t h f i l e >l o gc o n n e c t i o n s L< p a t h f i l e >l o ga l l w< w o r k i n gd i r > cn op r o m p t s ,H T T P Cf o r c ep r o m p t s t< u s e c s e r v e r t i m e o u t > p< p o r t n o > d< p o r t n o >d e m o nm o d e h t t po n l y 6I P v 6m o d e

Beforeorafterthecommandlineswitches,filestoloadandexecutecanbespecified.IfanewLISPexecutableprogramisfollowed byparameters,theprogrammustfinishwithand( e x i t ) statement,elsenewLISPwilltakecommandlineparametersasadditional newLISPscriptstobeloadedandexecuted. OnLinuxandotherUnixsystems,an e w l i s p manpagecanbefound:


m a nn e w l i s p

ThiswilldisplayamanpageintheLinux/Unixshell.

SpecifyingfilesasURLs
newLISPwillloadandexecutefilesspecifiedonthecommandline.Filesarespecifiedwitheithertheirpathnameoraf i l e : / / URLonthelocalfilesystemorwithah t t p : / / URLonremotefilesystemsrunninganHTTPserver.ThatHTTPservercanbe newLISPrunninginHTTPservermode.
n e w l i s pa p r o g . l s pb p r o g . l s pp r o g . l s p n e w l i s ph t t p : / / n e w l i s p . o r g / e x a m p l e . l s p n e w l i s pf i l e : / / / u s r / h o m e / n e w l i s p / d e m o . l s p

Noloadingofinit.lsp
Thisoptionsuppressesloadingofanypresentinitializationfilei n i t . l s p or. i n i t . l s p .Inordertowork,thismustbethefirst optionspecified:
n e w l i s pn

Moreaboutinitializationfiles.

Stacksize
n e w l i s ps4 0 0 0 n e w l i s ps1 0 0 0 0 0a p r o gb p r o g n e w l i s ps6 0 0 0m y p r o g n e w l i s ps6 0 0 0h t t p : / / a s i t e . c o m / e x a m p l e . l s p

TheaboveexamplesshowstartingnewLISPwithdifferentstacksizesusingthes option,aswellasloadingoneormorenewLISP sourcefilesandloadingfilesspecifiedbyanURL.Whennostacksizeisspecified,thestackdefaultsto2048.Perstackposition about80bytesofmemoryarepreallocated.

Maximummemoryusage
n e w l i s pm1 2 8

ThisexamplelimitsnewLISPcellmemoryto128megabytes.In32bitnewLISP,eachLispcellconsumes16bytes,sothe argument1 2 8 wouldrepresentamaximumof8,388,608newLISPcells.Thisinformationisreturnedbysysinfoasthelist'ssecond element.AlthoughLispcellmemoryisnottheonlymemoryconsumedbynewLISP,itisagoodestimateofoveralldynamic memoryusage.

Directexecutionmode
SmallpiecesofnewLISPcodecanbeexecuteddirectlyfromthecommandline:
n e w l i s pe" ( +34 ) " 7;O nW i n 3 2a n dU n i x n e w l i s pe' ( a p p e n d" a b c "" d e f " ) ' " a b c d e f ";O nU n i x

Theexpressionenclosedinquotationmarksisevaluated,andtheresultisprintedtostandardout(STDOUT).InmostUnixsystem shells,singlequotescanalsobeusedascommandstringdelimiters.Notethatthereisaspacebetweene andthequotedcommand string.

LoggingI/O
Inanymode,newLISPcanwritealogwhenstartedwiththel orL option.DependingonthemodenewLISPisrunning, differentoutputiswrittentothelogfile.Bothoptionsalwaysmustspecifythepathofalogfile.Thepathmaybearelativepathand canbeeitherattachedordetachedtothel orL option.Ifthefiledoesnotexist,itiscreatedwhenthefirstloggingoutputis written.
n e w l i s pl . / l o g f i l e . t x tc n e w l i s pL/ u s r / h o m e / w w w / l o g . t x th t t pw/ u s r / h o m e / w w w / h t p d o c s

Thefollowingtableshowstheitemsloggedindifferentsituations: loggingmode
n e w l i s pl n e w l i s pL

commandlineandnetevalwithc logonlyinputandnetworkconnections logalsonewLISPoutput(w/oprompts)

HTTPserverwithh t t p logonlynetworkconnections logalsoHTTPrequests

Allloggingoutputiswrittentothefilespecifiedafterthel orL option.

Specifyingtheworkingdirectory
Thew optionspecifiestheinitialworkingdirectoryfornewLISPafterstartup:
n e w l i s pw/ u s r / h o m e / n e w l i s p

Allfilerequestswithoutadirectorypathwillnowbedirectedtothepathspecifiedwiththew option.

SuppressingthepromptandHTTPprocessing
Thecommandlinepromptandinitialcopyrightbannercanbesuppressed:
n e w l i s pc

Listenandconnectionmessagesaresuppressedifloggingisnotenabled.Thec optionisusefulwhencontrollingnewLISPfrom otherprogramsitismandatorywhensettingitupasanetevalserver. Thec optionalsoenablesnewLISPservernodestoanswerH T T PG E T ,P U T ,P O S T andD E L E T E requests,aswellasperformCGI processing.Usingthec option,togetherwiththew andd options,newLISPcanserveasastandaloneh t t p d webserver:
n e w l i s pcd8 0 8 0w/ u s r / h o m e / w w w

WhenrunningnewLISPasai n e t d orx i n e t d enabledserveronUnixmachines,use:


n e w l i s pcw/ u s r / h o m e / w w w

Inc mode,newLISPprocessescommandlinerequestsaswellasHTTPandnetevalrequests.RunningnewLISPinthismodeis onlyrecommendedonamachinebehindafirewall.Thismodeshouldnotberunonmachinesopenandaccessiblethroughthe Internet.Tosuppresstheprocessingofnetevalandcommandlinelikerequests,usethesaferh t t p option.

ForcingpromptsinpipeI/Omode

AcapitalC forcespromptswhenrunningnewLISPinpipeI/OmodeinsidetheEmacseditor:
n e w l i s pC

Tosuppressconsoleoutputfromreturnvaluesfromevaluations,usesilent.

newLISPasaTCP/IPserver
n e w l i s ps o m e . l s pp9 0 9 0

ThisexampleshowshownewLISPcanlistenforcommandsonaTCP/IPsocketconnection.Inthiscase,standardI/Oisredirected totheportspecifiedwiththep option.s o m e . l s p isanoptionalfileloadedduringstartup,beforelisteningforaconnectionbegins. Thep optionismainlyusedtocontrolnewLISPfromanotherapplication,suchasanewLISPGUIfrontendoraprogramwritten inanotherlanguage.Assoonasthecontrollingclientclosestheconnection,newLISPwillexit. AtelnetapplicationcanbeusedtotestrunningnewLISPasaserver.Firstenter:


n e w l i s pp4 7 1 1&

The& indicatestoaUnixshelltoruntheprocessinthebackground.OnWindows,starttheserverprocesswithoutthe& inthe foregroundandopenasecondcommandwindowforthetelnetapplication.Nowconnectwithatelnet:


t e l n e tl o c a l h o s t4 7 1 1

Ifconnected,thenewLISPsignonbannerandpromptappear.Insteadof4 7 1 1 ,anyotherportnumbercouldbeused. Whentheclientapplicationclosestheconnection,newLISPwillexit,too.

TCP/IPdaemonmode
Whentheconnectiontotheclientisclosedinp mode,newLISPexits.Toavoidthis,usethed optioninsteadofthep option:
n e w l i s pd4 7 1 1&

Thisworkslikethep option,butnewLISPdoesnotexitafteraconnectioncloses.Instead,itstaysinmemory,listeningforanew connectionandpreservingitsstate.Anexitissuedfromaclientapplicationclosesthenetworkconnection,andthenewLISP daemonremainsresident,waitingforanewconnection.Anyportnumbercouldbeusedinplaceof4 7 1 1 . Aftereachtransaction,whenaconnectioncloses,newLISPwillgothrougharesetprocess,reinitializestackandsignalsandgoto theM A I N context.Onlythecontentsofprogramandvariablesymbolswillbepreservedwhenrunningastatefulserver. Whenrunninginp ord mode,theopeningandclosingtags[ c m d ] and[ / c m d ] mustbeusedtoenclosemultilinestatements. Theymusteachappearonseparatelines.Thismakesitpossibletotransferlargerportionsofcodefromcontrollingapplications. Thefollowingvariantofthed modeisfrequentlyusedinadistributedcomputingenvironment,togetherwithnetevalontheclient side:
n e w l i s pcd4 7 1 1&

Thec specsuppressesprompts,makingthismodesuitableforreceivingrequestsfromthenetevalfunction. newLISPservernodesrunningwillalsoanswerH T T PG E T ,P U T andD E L E T E requests.Thiscanbeusedtoretrieveandstorefiles withgeturl,puturl,deleteurl,readfile,writefileandappendfile,ortoloadandsaveprogramsusingloadandsavefromandto remoteservernodes.Seethechaptersforthec andh t t p optionsformoredetails.

HTTPonlyservermode
newLISPcanbelimitedtoHTTPprocessingusingtheh t t p option.Withthismode,asecureh t t p d webserverdaemoncanbe configured:
n e w l i s ph t t pd8 0 8 0w/ u s r / h o m e / w w w

WhenrunningnewLISPasani n e t d orx i n e t d enabledserveronUnixmachines,use:


n e w l i s ph t t pw/ u s r / h o m e / w w w

TofurtherenhancesecurityandHTTPprocessing,loadaprogramduringstartupwhenusingthismode:
n e w l i s ph t t p d c o n f . l s ph t t pw/ u s r / h o m e / w w w

Thefileh t t p d c o n f . l s p containsacommandeventfunctionconfiguringauserdefinedfunctiontoanalyze,filterandtranslate requests.Seethereferenceforthisfunctionforaworkingexample. IntheHTTPmodesenabledbyeitherc orh t t p ,thefollowingfiletypesarerecognized,andacorrectlyformattedC o n t e n t T y p e : headerissentback: fileextension mediatype .avi video/xmsvideo .css .gif .htm .html .jpg .js .mov .mp3 .mpg .pdf .png .wav .zip anyother text/css image/gif text/htm text/html image/jpg application/javascript video/quicktime audio/mpeg video/mpeg application/pdf image/png audio/xwav application/zip text/plain

ToserveCGI,HTTPservermodeneedsa/ t m p directoryonUnixlikeplatformsoraC : \ t m p directoryonWin32.newLISPcan processGET,PUT,POSTandDELETErequestsandcreatecustomresponseheaders.CGIfilesmusthavetheextension. c g i and haveexecutablepermissiononUnix.MoreinformationaboutCGIprocessingfornewLISPservermodescanbefoundinthe documentCodePatternsinnewLISP. Inbothservermodesc andh t t p theenvironmentvariablesDOCUMENT_ROOT,HTTP_HOST,REMOTE_ADDR, REQUEST_METHOD,SERVER_SOFTWAREandQUERY_STRINGareset.ThevariablesCONTENT_TYPE, CONTENT_LENGTH,HTTP_HOST,HTTP_USER_AGENTandHTTP_COOKIEarealsoset,ifpresentintheHTTPheader sentbytheclient.

LocaldomainUnixsocketserver
Insteadofaport,alocaldomainUnixsocketpathcanbespecifiedinthed orp servermodes.
n e w l i s pcd/ t m p / m y s o c k e t&

TesttheserverusinganothernewLISPprocess:
n e w l i s pe' ( n e t e v a l" / t m p / m y s o c k e t "0" ( s y m b o l s ) " ) '

Alistofallbuiltinsymbolswillbeprintedtotheterminal Thismodewillworktogetherwithlocaldomainsocketmodesofnetconnect,netlisten,andneteval.Localdomainsocketsopened withn e t c o n n e c t andn e t l i s t e n canbeservedusingnetaccept,netreceive,andnetsend.Localdomainsocketconnections canbemonitoredusingnetpeekandnetselect. LocaldomainsocketconnectionsaremuchfasterthannormalTCP/IPnetworkconnectionsandpreferredforcommunications betweenprocessesonthesamelocalfilesystemindistributedapplications.ThismodeisnotavailableonWin32.

Connectiontimeout
Specifiesaconnectiontimeoutwhenrunninginp ord demonmode.AnewLISPServerwilldisconnectwhennofurtherinputis readafteracceptingaclientconnection.Thetimeoutisspecifiedinmicroseconds:
n e w l i s pct3 0 0 0 0 0 0d4 7 1 1&

Theexamplespecifiesatimeoutofthreeseconds.

i n e t d daemonmode

Thei n e t d serverrunningonvirtuallyallLinux/UnixOSescanfunctionasaproxyfornewLISP.TheserveracceptsTCP/IPor UDPconnectionsandpassesonrequestsviastandardI/OtonewLISP.i n e t d startsanewLISPprocessforeachclientconnection. Whenaclientdisconnects,theconnectionisclosedandthenewLISPprocessexits.


i n e t d andnewLISPtogethercanhandlemultipleconnectionsefficientlybecauseofnewLISP'ssmallmemoryfootprint,fast

executable,andshortprogramloadtimes.Whenworkingwithneteval,thismodeispreferredforefficientlyhandlingmultiple requestsinadistributedcomputingenvironment. Twofilesmustbeconfigured:s e r v i c e s andi n e t d . c o n f .BothareASCIIeditableandcanusuallybefoundat/ e t c / s e r v i c e s and/ e t c / i n e t d . c o n f . Putoneofthefollowinglinesintoi n e t d . c o n f :


n e t e v a l s t r e a m t c p n o w a i t r o o t / u s r / b i n / n e w l i s pc #a sa na l t e r n a t i v e ,ap r o g r a mc a na l s ob ep r e l o a d e d n e t e v a l s t r e a m t c p n o w a i t r o o t / u s r / b i n / n e w l i s pcm y p r o g . l s p

Insteadofr o o t ,anotheruserandoptionalgroupcanbespecified.Fordetails,seetheUnixmanpagefori n e t d . Thefollowinglineisputintothes e r v i c e s file:


n e t e v a l 4 7 1 1 / t c p #n e w L I S Pn e t e v a lr e q u e s t s

OnMacOSXandsomeUnixsystems,x i n e t d canbeusedinsteadofi n e t d .Savethefollowingtoafilenamedn e t e v a l inthe / e t c / x i n e t d . d / directory:


s e r v i c en e t e v a l { s o c k e t _ t y p e=s t r e a m w a i t=n o u s e r=r o o t s e r v e r=/ u s r / b i n / n e w l i s p p o r t=4 7 1 1

s e r v e r _ a r g s=c o n l y _ f r o m=l o c a l h o s t

Forsecurityreasons,r o o t shouldbechangedtoadifferentuserandfilepermissionsofthewwwdocumentdirectoryadjusted accordingly.Theo n l y _ f r o m speccanbeleftouttopermitremoteaccess. Seethemanpagesforx i n e t d andx i n e t d . c o n f forotherconfigurationoptions. Afterconfiguringthedaemon,i n e t d orx i n e t d mustberestartedtoallowtheneworchangedconfigurationfilestoberead:
k i l lH U P< p i d >

Replace< p i d > withtheprocessIDoftherunningx i n e t d process. Anumberornetworkprotocolotherthan4711orTCPcanbespecified. newLISPhandleseverythingasiftheinputwerebeingenteredonanewLISPcommandlinewithoutaprompt.Totestthei n e t d setup,thet e l n e t programcanbeused:


t e l n e tl o c a l h o s t4 7 1 1

newLISPexpressionscannowbeentered,andi n e t d willautomaticallyhandlethestartupandcommunicationsofanewLISP process.Multilineexpressionscanbeenteredbybracketingthemwith[ c m d ] and[ / c m d ] tags,eachonseparatelines. newLISPservernodesanswerH T T PG E T andP U T requests.Thiscanbeusedtoretrieveandstorefileswithgeturl,puturl,read file,writefileandappendfile,ortoloadandsaveprogramsusingloadandsavefromandtoremoteservernodes.

LinkingasourcefilewithnewLISPforanewexecutable
SourcecodeandthenewLISPexecutablecanbelinkedtogethertobuildaselfcontainedapplicationbyusingthex commandline flag.
; ;u p p e r c a s e . l s p-L i n ke x a m p l e ( p r i n t l n( u p p e r c a s e( m a i n a r g s1 ) ) ) ( e x i t )

Theprogramu p p e r c a s e . l s p takesthefirstwordonthecommandlineandconvertsittouppercase. Tobuildthisprogramasaselfcontainedexecutable,followthesesteps:


#o nO S X ,L i n u xa n do t h e rU N I X n e w l i s pxu p p e r c a s e . l s pu p p e r c a s e c h m o d7 5 5u p p e r c a s e#g i v ee x e c u t a b l ep e r m i s s i o n #o nW i n d o w st h et a r g e tn e e d s. e x ee x t e n s i o n n e w l i s pxu p p e r c a s e . l s pu p p e r c a s e . e x e

newLISPwillfindanewLISPexecutableintheexecutionpathoftheenvironmentandlinkacopyofthesourcecode.
u p p e r c a s e" c o n v e r tm et ou p p e r c a s e "

Theconsoleshouldprint:
C O N V E R TM ET OU P P E R C A S E

Notethatneitheroneoftheinitializationfilesi n i t . l s p nor. i n i t . l s p isloadedduringstartupoflinkedprograms. ()

5.Startup,directories,environment
EnvironmentvariableN E W L I S P D I R
Duringstartup,newLISPsetstheenvironmentvariableN E W L I S P D I R ,ifitisnotsetalready.OnLinux,BSDs,MacOSXandother Unixesthevariableissetto/ u s r / s h a r e / n e w l i s p .OnWin32thevariableissetto% P R O G R A M F I L E S % / n e w l i s p . TheenvironmentvariableN E W L I S P D I R isusefulwhenloadingfilesinstalledwithnewLISP:
( l o a d( a p p e n d( e n v" N E W L I S P D I R " )" / g u i s e r v e r . l s p " ) ) ( l o a d( a p p e n d( e n v" N E W L I S P D I R " )" / m o d u l e s / m y s q l . l s p " ) )

Apredefinedfunctionm o d u l e canbeusedtoshortenthesecondstatementloadingfromthem o d u l e s / directory:


( m o d u l e" m y s q l . l s p " )

Theinitializationfilei n i t . l s p
Beforeloadinganyfilesspecifiedonthecommandline,andbeforethebannerandpromptareshown.newLISPtriestoloadafile . i n i t . l s p fromthehomedirectoryoftheuserstartingnewLISP.OnMacOSX,LinuxandotherUnixthehomedirectoryis foundintheH O M E environmentvariable.OnWin32thedirectorynameiscontainedintheU S E R P R O F I L E orD O C U M E N T _ R O O T environmentvariable. Ifa. i n i t . l s p cannotbefoundinthehomedirectorynewLISPtriestoloadthefilei n i t . l s p fromthedirectoryfoundinthe environmentvariableN E W L I S P D I R . WhennewLISPisrunasasharedlibrary,aninitializationfileislookedforintheenvironmentvariableN E W L I S P L I B _ I N I T .Thefull pathnameoftheinitializationfilemustbespecified.IfN E W L I S P L I B _ I N I T isnotdefined,noinitializationfilewillbeloadedbythe librarymodule. AlthoughnewLISPdoesnotrequirei n i t . l s p torun,itisconvenientfordefiningfunctionsandsystemwidevariables. Notethatneitheroneoftheinitializationfilesi n i t . l s p nor. i n i t . l s p isloadedduringstartupoflinkedprograms.

DirectoriesonLinux,BSD,MacOSXandotherUnix
Thedirectory/ u s r / s h a r e / n e w l i s p / m o d u l e s containsmoduleswithusefulfunctionsPOP3mail,etc.Thedirectory / u s r / s h a r e / n e w l i s p / g u i s e r v e r containssampleprogramsforwritingGUIapplicationswithnewLISPGS.Thedirectory / u s r / s h a r e / d o c / n e w l i s p / containsdocumentationinHTMLformat.

DirectoriesonWin32
OnWin32systems,allfilesareinstalledinthedefaultdirectory% P R O G R A M F I L E S % \ n e w l i s p .P R O G R A M F I L E S isaWin32 environmentvariablethatresolvestoC : \ P r o g r a mf i l e s \ n e w l i s p \ inEnglishlanguageinstallations.Thesubdirectories % P R O G R A M F I L E S % \ n e w l i s p \ m o d u l e s and% P R O G R A M F I L E S % \ n e w l i s p \ g u i s e r v e r containmodulesforinterfacingtoexternal librariesandsampleprogramswrittenfornewLISPGS. ()

6.ExtendingnewLISPwithsharedlibraries
ManysharedlibrariesonUnixandWin32systemscanbeusedtoextendnewLISP'sfunctionality.Examplesarelibrariesfor writinggraphicaluserinterfaces,librariesforencryptionordecryptionandlibrariesforaccessingdatabases. Thefunctionimportisusedtoimportfunctionsfromexternallibraries.Thefunctioncallbackisusedtoregistercallbackfunctionsin externallibraries.Otherfunctionslikepack,unpack,getstring,getintandgetlongexisttofacilitateformattinginputandoutputto andfromimportedlibraryfunctions. Seealsothechapter23.ExtendingnewLISPintheCodePatternsinnewLISPdocument. ()

7.newLISPasasharedlibrary
newLISPcanbecompiledasasharedlibrary.OnLinux,BSDsandotherUnixflavorsthelibraryiscalledn e w l i s p . s o .On Windowsitiscalledn e w l i s p . d l l andn e w l i s p . d y l i b onMacOSX.AnewLISPsharedlibraryisusedlikeanyothershared library. Themainfunctiontoimportisn e w l i s p E v a l S t r .Likeevalstring,thisfunctiontakesastringcontaininganewLISPexpressionand storestheresultinastringaddress.Theresultcanberetrievedusinggetstring.Thereturnedstringisformattedlikeoutputfroma commandlinesession.Itcontainsterminatinglinefeedcharacters,butnotthepromptstring. Whencallingn e w l i s p E v a l S t r ,outputnormallydirectedtotheconsole(e.g.returnvaluesorprintstatements)isreturnedinthe formofanintegerstringpointer.Theoutputcanbeaccessedbypassingthispointertotheg e t s t r i n g function.Tosilencethe outputfromreturnvalues,usethesilentfunction. Whenpassingmultilinesourceton e w l i s p E v a l S t r ,thatsourceshouldbebracketedby[ c m d ] ,[ / c m d ] tags,eachonadifferent line:
( s e t' c o d e[ t e x t ] [ c m d ] . . . . . . . . . [ / c m d ] [ / t e x t ] )

Sincev.10.3.3callbackscanalsoberegisteredusingn e w l i s p C a l l b a c k .Formoreinformationreadthechapter24.newLISP compiledasasharedlibraryintheCodePatternsinnewLISPdocument. ()

8.EvaluatingnewLISPexpressions
ThefollowingisashortintroductiontonewLISPstatementevaluationandtheroleofintegerandfloatingpointarithmeticin newLISP. Toplevelexpressionsareevaluatedwhenusingtheloadfunctionorwhenenteringexpressionsinconsolemodeonthecommand line.

Interactivemultilineexpressions
Multilineexpressionscanbeenteredbyenteringanemptylinefirst.Onceinmultilinemode,anotheremptylinereturnsfromentry

modeandevaluatesthestatement(s)entered:
> ( d e f i n e( f o oxy ) ( +xy ) ) ( l a m b d a( xy )( +xy ) ) >( f o o34 ) 7 >_

Enteringmultilinemodebyhittingtheenterkeyonanemptylinesuppressestheprompt.Enteringanotheremptylinewillleavethe multilinemodeandevaluateexpressions. Asanalternativotoenteringemptylines,the[ c m d ] and[ / c m d ] tagsareused,eachenteredonseparatelines.Thismodeisusedby someinteractiveIDEscontrollingnewLISPandinternallybythenetevalfunction.The[ c m d ] and[ / c m d ] tagsmustalsobeused intheconsolepartofthenewLISPGSJavaIDE.

Integer,floatingpointdataandoperators
newLISPfunctionsandoperatorsacceptintegerandfloatingpointnumbers,convertingthemintotheneededformat.Forexample,a bitmanipulatingoperatorconvertsafloatingpointnumberintoanintegerbyomittingthefractionalpart.Inthesamefashion,a trigonometricfunctionwillinternallyconvertanintegerintoafloatingpointnumberbeforeperformingitscalculation. Thesymboloperators(+ * / % $ ~ | ^ < < > > )returnvaluesoftypeinteger.Functionsandoperatorsnamedwithawordinsteadof asymbol(e.g.,a d d ratherthan+ )returnfloatingpointnumbers.Integeroperatorstruncatefloatingpointnumberstointegers, discardingthefractionalparts. newLISPhastwotypesofbasicarithmeticoperators:integer(+ * / )andfloatingpoint(a d d s u b m u l d i v ).Thearithmetic functionsconverttheirargumentsintotypescompatiblewiththefunction'sowntype:integerfunctionargumentsintointegers, floatingpointfunctionargumentsintofloatingpoints.TomakenewLISPbehavemorelikeotherscriptinglanguages,theinteger operators+ ,,* ,and/ canberedefinedtoperformthefloatingpointoperatorsa d d ,s u b ,m u l ,andd i v :
( c o n s t a n t' +a d d ) ( c o n s t a n t' -s u b ) ( c o n s t a n t' *m u l ) ( c o n s t a n t' /d i v ) ; ;o ra l l4o p e r a t o r sa to n c e ( c o n s t a n t' +a d d' -s u b' *m u l' /d i v )

Nowthecommonarithmeticoperators+ ,,* ,and/ acceptbothintegerandfloatingpointnumbersandreturnfloatingpointresults. Caremustbetakenwhenimportingfromlibrariesthatusefunctionsexpectingintegers.Afterredefining+ ,,* ,and/ ,adouble floatingpointnumbermaybeunintentionallypassedtoanimportedfunctioninsteadofaninteger.Inthiscase,floatingpoint numberscanbeconvertedintointegersbyusingthefunctionint.Likewise,integerscanbetransformedintofloatingpointnumbers usingthefloatfunction:
( i m p o r t" m y l i b . d l l "" f o o " ) ( f o o( i n tx ) ) ( i m p o r t" m y l i b . d l l "" b a r " ) ( b a r( f l o a ty ) ) ;i m p o r t i n gi n tf o o ( i n tx )f r o mC ;p a s s e da r g u m e n ta si n t e g e r ;i m p o r t i n gCi n tb a r ( d o u b l ey ) ;f o r c ed o u b l ef l o a t

SomeofthemodulesshippingwithnewLISParewrittenassumingthedefaultimplementationsof+ ,,* ,and/ .Thisgives importedlibraryfunctionsmaximumspeedwhenperformingaddresscalculations. ThenewLISPpreferenceistoleave+ ,,* ,and/ definedasintegeroperatorsandusea d d ,s u b ,m u l ,andd i v whenexplicitly required.Sinceversion8.9.7,integeroperationsinnewLISPare64bitoperations,whereas64bitdoublefloatingpointnumbers offeronly52bitsofresolutionintheintegerpartofthenumber.

Biginteger,multipleprecisionarithmetic
Theintegerarithmeticoperators,+*/++%andthecomparisonoperators<>=<=>=!=andthefunctionsabs,even?,odd?, length,number?andzero?nowacceptbigintegerswithunlimitedprecision.Ifthefirstargumentinanyoftheseoperatorsand functionsisabiginteger,thecalculationperformedwillbeinbigintegermode.Nomorethantwoargumentsareallowedinbig integerarithmeticoperations.Useapplywithareduceparameterof2toworkaroundthis. Literalintegervaluesgreaterthan9223372036854775807orsmallerthan9223372036854775808,orintegerswithanappended letterL,willbeconvertedandprocessedinbigintegermode.Thefunctionbigintcanbeusedtoconvertfrominteger,floatorstring formattobiginteger.Thepredicatebigint?checksforbigintegertype.
;f i r s ta r g u m e n tt r i g g e r sb i gi n t e g e rm o d eb e c a u s ei t ' sb i ge n o u g h ( +1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 01 2 3 4 5 )1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 8 0 2 3 5 L ;f i r s ts m a l ll i t e r a lp u ti nb i gi n t e g e rf o r m a tb y ;a p p e n d i n gLt og u a r a n t e eb i gi n t e g e rm o d e ( +1 2 3 4 5 L1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 )1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 8 0 2 3 5 L ( s e t qx1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 ) ( *xx )1 5 2 4 1 5 7 8 7 5 3 2 3 8 8 3 6 7 5 0 4 9 5 3 3 4 7 9 9 5 7 3 3 8 6 6 9 1 2 0 5 6 2 3 9 9 0 2 5 L ;c o n v e r s i o nf r o mb i g i n tt of l o a ti n t r o d u c e sr o u n d i n ge r r o r s ( b i g i n t( f l o a t( *xx ) ) )1 5 2 4 1 5 7 8 7 5 3 2 3 8 8 3 7 2 5 3 4 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 L ;o n l y2a r g u m e n t sa r ea l l o w e di nb i gi n t e g e ro p e r a t i o n s ;a p p l yw i t hr e d u c ep a r a m e t e r2g u a r a n t e e s2a r g sa tat i m e ;s e q u e n c ei t s e l fd o e sn o tt a k eb i gi n t e g e r s ,b e f o r eu s i n g ;a p p l y ,t h es e q u e n c ei sc o n v e r t e dw i t hb i g i n t ( a p p l y*( m a pb i g i n t( s e q u e n c e11 0 0 ) )2 );c a l c u l a t e1 0 0 ! 9 3 3 2 6 2 1 5 4 4 3 9 4 4 1 5 2 6 8 1 6 9 9 2 3 8 8 5 6 2 6 6 7 0 0 4 9 0 7 1 5 9 6 8 2 6 4 3 8 1 6 2 1 4 6 8 5 9 2 9 6 3 8 9 5 2 1 7 5 9 9 9 9 3 2 2 9 9 1 5 6 0 8 9 4 1 4 6 3 9 7 6 1 5 6 5 1 8 2 8 6 2 5 3 6 9 7 9 2 0 8 2 7 2 2 3 7 5 8 2 5 1 1 8 5 2 1 0 9 1 6 8 6 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 L ;l e n g t ho nb i gi n t e g e r sr e t u r n st h en u m b e ro fd e c i m a ld i g i t s ( l e n g t h( a p p l y*( m a pb i g i n t( s e q u e n c e11 0 0 ) )2 ) ) 1 5 8;d e c i m a ld i g i t s ;a l lf i b o n a c c in u m b e r su pt o2 0 0 ,o n l yt h ef i r s tn u m b e r ;n e e d st ob ef o r m a t t e da sb i gi n t e g e r ,t h er e s tf o l l o w s ;a u t o m a t i c a l l y-w h e ne x e c u t e df r o mt h ec o m m a n dl i n ei n ;a1 2 0c h a rw i d et e r m i n a l ,t h i ss h o w sab e a u t i f u lp a t t e r n ( l e t( x1 L )( s e r i e sx( f n( y )( +x( s w a pyx ) ) )2 0 0 ) )

Whendoingmixedinteger/bigintegerarithmetic,thefirstargumentshouldbeabigintegertoavoiderraticbehaviour.
;b e c a u s et h ef i r s ta r g u m e n ti s6 4 b i t ,n ob i gi n t e g e ra r i t h m e t i c ;w i l lb ed o n e ,a l t h o u g ht h es e c o n da r g u m e n ti sb i gi n t e g e r ( +1 2 31 2 3 4 5 L ) 1 2 4 6 8 ;t h es e c o n da r g u m e n ti sr e c o g n i z e da sab i gi n t e g e r ;a n do v e r f l o w st h ec a p a c i t yo fa6 4 b i ti n t e g e r ( +1 2 31 2 3 4 5 3 4 5 6 7 3 5 6 4 5 6 3 4 5 6 5 4 6 3 5 6 3 5 4 6 ) E R R :n u m b e ro v e r f l o w si nf u n c t i o n+ ;n o wt h ef i r s ta r g u m e n tc o n v e r t st ob i gi n t e g e ra n dt h e ;w h o l ee x p r e s s i o ne v a l u a t e si nb i gi n t e g e rm o d e ( +1 2 3 L1 2 3 4 5 3 4 5 6 7 3 5 6 4 5 6 3 4 5 6 5 4 6 3 5 6 3 5 4 6 ) 1 2 3 4 5 3 4 5 6 7 3 5 6 4 5 6 3 4 5 6 5 4 6 3 5 6 3 6 6 9 L

Undermostcircumstancesmixingfloat,integersandbigintegersistransparent.Functionsautomaticallydoconversionswhen neededonthesecondargument.Theoverflowbehaviorwhenusingnormalintegersandfloatsonly,hasnotchangedfrom newLISPversionspreviousto10.5.0.

Evaluationrulesanddatatypes
Evaluateexpressionsbyenteringandeditingthemonthecommandline.Morecomplicatedprogramscanbeenteredusingeditors likeEmacsandVI,whichhavemodestoshowmatchingparentheseswhiletyping.Loadasavedfilebackintoaconsolesessionby usingtheloadfunction. Alinecommentbeginswitha; (semicolon)ora# (numbersign)andextendstotheendoftheline.newLISPignoresthisline duringevaluation.The# isusefulwhenusingnewLISPasascriptinglanguageinLinux/Unixenvironments,wherethe# is commonlyusedasalinecommentinscriptsandshells. Whenevaluationoccursfromthecommandline,theresultisprintedtotheconsolewindow. Thefollowingexamplescanbeenteredonthecommandlinebytypingthecodetotheleftofthesymbol.Theresultthat appearsonthenextlineshouldmatchthecodetotherightofthesymbol. nilandtrueareBooleandatatypesthatevaluatetothemselves:
n i l t r u e n i l t r u e

Integers,bigintegersandfloatingpointnumbersevaluatetothemselves:
1 2 3 1 2 3 0 x E 8 2 3 2 0 5 5 4 5 0 b 1 0 1 0 1 04 2 1 . 2 3 1 . 2 3 1 2 3 e 3 0 . 1 2 3 ;d e c i m a li n t e g e r ;h e x a d e c i m a lp r e f i x e db y0 x ;o c t a lp r e f i x e db y0( z e r o ) ;b i n a r yp r e f i x e db y0 b ;f l o a t ;f l o a ti ns c i e n t i f i cn o t a t i o n

1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 L;p a r s e st ob i gi n t e g e r

Integersare64bitincludingthesignbit.Validintegersarenumbersbetween9,223,372,036,854,775,808and +9,223,372,036,854,775,807.Largernumbersconvertedfromfloatingpointnumbersaretruncatedtooneofthetwolimits.Integers internaltonewLISP,whicharelimitedto32bitnumbers,overflowtoeither+2,147,483,647or2,147,483,648. FloatingpointnumbersareIEEE75464bitdoubles.Unsignednumbersupto18,446,744,073,709,551,615canbedisplayedusing specialformattingcharactersforformat. Bigintegersareofunlimitedprecisionandonlylimitedinsizebymemory.Thememoryrequirementofabigintegeris: bytes=4*ceil(digits/9)+4. Wheredigitsaredecimaldigits,bytesare8bitsandceilistheceilingfunctionroundinguptothenextinteger. Stringsmaycontainnullcharactersandcanhavedifferentdelimiters.Theyevaluatetothemselves.


" h e l l o " " \ 0 3 2 \ 0 3 2 \ 0 6 5 \ 0 3 2 " " \ x 2 0 \ x 2 0 \ x 4 1 \ x 2 0 " " \ t \ r \ n " " \ x 0 9 \ x 0 d \ x 0 a " " h e l l o " " A" " A" " \ t \ r \ n " " \ t \ r \ n "

; ;n u l lc h a r a c t e r sa r el e g a li ns t r i n g s : " \ 0 0 0 \ 0 0 1 \ 0 0 2 " " \ 0 0 0 \ 0 0 1 \ 0 0 2 " { t h i s" i s "as t r i n g }" t h i s\ " i s \ "as t r i n g " ; ;u s e[ t e x t ]t a g sf o rt e x tl o n g e rt h a n2 0 4 7b y t e s :

[ t e x t ] t h i si sas t r i n g ,t o o [ / t e x t ] " t h i si sas t r i n g ,t o o "

Stringsdelimitedby" (doublequotes)willalsoprocessthefollowingcharactersescapedwitha\ (backslash): character description


\ " \ n \ r \ b \ t \ f \ n n n \ x n n \ u n n n n \ \

foradoublequoteinsideaquotedstring foralinefeedcharacter(ASCII10) forareturncharacter(ASCII13) forabackspaceBScharacter(ASCII8) foraTABcharacter(ASCII9) foraformfeedFFcharacter(ASCII12) forathreedigitASCIInumber(nnnformatbetween000and255) foratwodigithexASCIInumber(xnnformatbetweenx00andxff) foraunicodecharacterencodedinthefourn n n n hexadecimaldigits.newLISPwilltranslatethistoaUTF8character intheUTF8enabledversionsofnewLISP. forthebackslashcharacter(ASCII92)itself

Quotedstringscannotexceed2,048characters.Longerstringsshouldusethe[ t e x t ] and[ / t e x t ] tagdelimiters.newLISP automaticallyusesthesetagsforstringoutputlongerthan2,048characters. The{ (leftcurlybracket),} (rightcurlybracket),and[ t e x t ] ,[ / t e x t ] delimitersdonotperformescapecharacterprocessing. Lambdaandlambdamacroexpressionsevaluatetothemselves:


( l a m b d a( x )( *xx ) ) ( l a m b d a( x )( *xx ) ) ( l a m b d a m a c r o( ab )( s e t( e v a la )b ) ) ( l a m b d a m a c r o( ab )( s e t( e v a la )b ) ) ( f n( x )( *xx ) ) ( l a m b d a( x )( *xx ) ) ;a na l t e r n a t i v es y n t a x

Symbolsevaluatetotheircontents:
( s e t' s o m e t h i n g1 2 3 ) 1 2 3 s o m e t h i n g 1 2 3

Contextsevaluatetothemselves:
( c o n t e x t' C T X ) C T X C T X C T X

Builtinfunctionsalsoevaluatetothemselves:
a d d ( e v a l( e v a la d d ) ) ( c o n s t a n t' +a d d ) + a d d< B 8 4 5 7 7 0 D > a d d< B 8 4 5 7 7 0 D > a d d< B 8 4 5 7 7 0 D > a d d< B 8 4 5 7 7 0 D >

Intheaboveexample,thenumberbetweenthe<>(anglebrackets)isthehexadecimalmemoryaddress(machinedependent)ofthe a d d function.Itisdisplayedwhenprintingabuiltinprimitive. Quotedexpressionsloseone'(singlequote)whenevaluated:


' s o m e t h i n g s o m e t h i n g ' ' ' ' a n y ' ' ' a n y ' ( abcd ) ( abcd )

Asinglequoteisoftenusedtoprotectanexpressionfromevaluation(e.g.,whenreferringtothesymbolitselfinsteadofitscontents ortoalistrepresentingdatainsteadofafunction). Listsareevaluatedbyfirstevaluatingthefirstlistelementbeforetherestoftheexpression(asinScheme).Theresultofthe evaluationisappliedtotheremainingelementsinthelistandmustbeoneofthefollowing:al a m b d a expression,l a m b d a m a c r o

expression,orp r i m i t i v e (builtin)function.
( +1234 ) 1 0 ( d e f i n e( d o u b l ex )( +xx ) ) ( l a m b d a( x )( +xx ) )

or
( s e t' d o u b l e( l a m b d a( x )( +xx ) ) ) ( d o u b l e2 0 ) 4 0 ( ( l a m b d a( x )( *xx ) )5 ) 2 5

Forauserdefinedlambdaexpression,newLISPevaluatestheargumentsfromlefttorightandbindstheresultstotheparameters (alsofromlefttoright),beforeusingtheresultsinthebodyoftheexpression. LikeScheme,newLISPevaluatesthefunctor(functionobject)partofanexpressionbeforeapplyingtheresulttoitsarguments.For example:


( ( i f( >X1 0 )*+ )XY )

DependingonthevalueofX,thisexpressionappliesthe* (product)or+ (sum)functiontoXandY. Becausetheirargumentsarenotevaluated,l a m b d a m a c r o expressionsareusefulforextendingthesyntaxofthelanguage.Most builtinfunctionsevaluatetheirargumentsfromlefttoright(asneeded)whenexecuted.Someexceptionstothisruleareindicatedin thereferencesectionofthismanual.Lispfunctionsthatdonotevaluateallorsomeoftheirargumentsarecalledspecialforms. Arraysevaluatetothemselves:


( s e t' A( a r r a y22' ( 1234 ) ) )( ( 12 )( 34 ) ) ( e v a lA ) ( ( 12 )( 34 ) )

Shellcommands:Ifan! (exclamationmark)isenteredasthefirstcharacteronthecommandlinefollowedbyashellcommand,the commandwillbeexecuted.Forexample,! l s onUnixor! d i r onWin32willdisplayalistingofthepresentworkingdirectory.No spacesarepermittedbetweenthe! andtheshellcommand.Symbolsbeginningwithan! arestillallowedinsideexpressionsoron thecommandlinewhenprecededbyaspace.Note:Thismodeonlyworkswhenrunningintheshellanddoesnotworkwhen controllingnewLISPfromanotherapplication. ToexitthenewLISPshellonLinux/Unix,pressC t r l D onWin32,type( e x i t ) orC t r l C ,thenthexkey. UsetheexecfunctiontoaccessshellcommandsfromotherapplicationsortopassresultsbacktonewLISP. ()

9.LambdaexpressionsinnewLISP
LambdaexpressionsinnewLISPevaluatetothemselvesandcanbetreatedjustlikeregularlists:
( s e t' d o u b l e( l a m b d a( x )( +xx ) ) ) ( s e t' d o u b l e( f n( x )( +xx ) ) ) ;a l t e r n a t i v es y n t a x ( l a s td o u b l e ) ( +xx ) ;t r e a tl a m b d aa sal i s t

Note:No' isnecessarybeforethelambdaexpressionbecauselambdaexpressionsevaluatetothemselvesinnewLISP. Thesecondlineusesthekeywordf n ,analternativesyntaxfirstsuggestedbyPaulGrahamforhisArclanguageproject. Alambdaexpressionisalambdalist,asubtypeoflist,anditsargumentscanassociatefromlefttorightorrighttoleft.Whenusing append,forexample,theargumentsassociatefromlefttoright:


( a p p e n d( l a m b d a( x ) )' ( ( +xx ) ) ) ( l a m b d a( x )( +xx ) )

cons,ontheotherhand,associatestheargumentsfromrighttoleft:

( c o n s' ( x )( l a m b d a( +xx ) ) ) ( l a m b d a( x )( +xx ) )

Notethatthel a m b d a keywordisnotasymbolinalist,butadesignatorofaspecialtypeoflist:thelambdalist.
( l e n g t h( l a m b d a( x )( +xx ) ) ) 2 ( f i r s t( l a m b d a( x )( +xx ) ) ) ( x )

Lambdaexpressionscanbemappedorappliedontoargumentstoworkasuserdefined,anonymousfunctions:
( ( l a m b d a( x )( +xx ) )1 2 3 ) 2 4 6 ( a p p l y( l a m b d a( x )( +xx ) )' ( 1 2 3 ) ) 2 4 6 ( m a p( l a m b d a( x )( +xx ) )' ( 123 ) ) ( 246 )

Alambdaexpressioncanbeassignedtoasymbol,whichinturncanbeusedasafunction:
( s e t' d o u b l e( l a m b d a( x )( +xx ) ) ) ( l a m b d a( x )( +xx ) ) ( d o u b l e1 2 3 ) 2 4 6

Thedefinefunctionisjustashorterwayofassigningalambdaexpressiontoasymbol:
( d e f i n e( d o u b l ex )( +xx ) ) ) ( l a m b d a( x )( +xx ) ) ( d o u b l e1 2 3 ) 2 4 6

Intheaboveexample,theexpressionsinsidethelambdalistarestillaccessiblewithind o u b l e :
( s e t' d o u b l e( l a m b d a( x )( +xx ) ) ) ( l a m b d a( x )( +xx ) ) ( l a s td o u b l e ) ( +xx )

Alambdalistcanbemanipulatedasafirstclassobjectusinganyfunctionthatoperatesonlists:
( s e t f( n t h1d o u b l e )' ( m u l2x ) ) ( l a m b d a( x )( m u l2x ) ) d o u b l e ( l a m b d a( x )( m u l2x ) ) ( d o u b l e1 2 3 ) 2 4 6

Allargumentsareoptionalwhenapplyinglambdaexpressionsanddefaultton i l whennotsuppliedbytheuser.Thismakesit possibletowritefunctionswithmultipleparametersignatures. ()

10.n i l ,t r u e ,c o n s ,and( )
InnewLISP,n i l andt r u e representboththesymbolsandtheBooleanvaluesfalseandtrue.Dependingontheircontext,n i l and t r u e aretreateddifferently.Thefollowingexamplesusen i l ,buttheycanbeappliedtot r u e bysimplyreversingthelogic. Evaluationofn i l yieldsaBooleanfalseandistreatedassuchinsideflowcontrolexpressionssuchasi f ,u n l e s s ,w h i l e ,u n t i l , andn o t .Likewise,evaluatingt r u e yieldstrue.
( s e t' l s t' ( n i ln i ln i l ) ) ( n i ln i ln i l ) ( m a ps y m b o l ?l s t ) ( t r u et r u et r u e )

Intheaboveexample,n i l representsasymbol.Inthefollowingexample,n i l andt r u e areevaluatedandrepresentBoolean values:


( i fn i l" n o "" y e s " ) " y e s " ( i ft r u e" y e s "" n o " )" y e s " ( m a pn o tl s t ) ( t r u et r u et r u e )

InnewLISP,n i l andtheemptylist( ) arenotthesameasinsomeotherLisps.Onlyinconditionalexpressionsaretheytreatedasa Booleanfalse,asina n d ,o r ,i f ,w h i l e ,u n l e s s ,u n t i l ,andc o n d . Evaluationof( c o n s' x' ( ) ) yields( x ) ,but( c o n s' xn i l ) yields( xn i l ) becausen i l istreatedasaBooleanvaluewhen evaluated,notasanemptylist.Thec o n s oftwoatomsinnewLISPdoesnotyieldadottedpair,butratheratwoelementlist.The

predicatea t o m ? istrueforn i l ,butfalsefortheemptylist.TheemptylistinnewLISPisonlyanemptylistandnotequalton i l . AlistinnewLISPisanewLISPcelloftypelist.Itactslikeacontainerforthelinkedlistofelementsmakingupthelistcell's contents.ThereisnodottedpairinnewLISPbecausethecdr(tail)partofaLispcellalwayspointstoanotherLispcellandneverto abasicdatatype,suchasanumberorasymbol.Onlythecar(head)partmaycontainabasicdatatype.EarlyLispimplementations usedcarandcdrforthenamesheadandtail. ()

11.Arrays
newLISP'sarraysenablefastelementaccesswithinlargelists.Newarrayscanbeconstructedandinitializedwiththecontentsofan existinglistusingthefunctionarray.Listscanbeconvertedintoarrays,andviceversa.Mostofthesamefunctionsusedfor modifyingandaccessinglistscanbeappliedtoarrays,aswell.Arrayscanholdanytypeofdataorcombinationthereof. Inparticular,thefollowingfunctionscanbeusedforcreating,accessing,andmodifyingarrays: function append array arraylist array? det first invert last mat multiply nth rest setf slice description appendsarrays createsandinitializesanarraywithupto16dimensions convertsanarrayintoalist checksifexpressionisanarray returnsthedeterminantofamatrix returnsthefirstrowofanarray returnstheinversionofamatrix returnsthelastrowofanarray performscalaroperationsonmatrices multipliestwomatrices returnsanelementofandarray returnsallbutthefirstrowofanarray setscontentsofanarrayreference returnsasliceofanarray

sort sorttheelementsinanarray transpose transposesamatrix

newLISPrepresentsmultidimensionalarrayswithanarrayofarrays(i.e.,theelementsofthearrayarethemselvesarrays). Whenusedinteractively,newLISPprintsanddisplaysarraysaslists,withnowayofdistinguishingbetweenthem. Usethesourceorsavefunctionstoserializearrays(orthevariablescontainingthem).Thearraystatementisincludedaspartofthe definitionwhenserializingarrays. Likelists,negativeindicescanbeusedtoenumeratetheelementsofanarray,startingfromthelastelement. Anoutofboundsindexwillcauseanerrormessageonanarrayorlist. Arrayscanbenonrectangular,buttheyaremaderectangularduringserializationwhenusingsourceorsave.Thearrayfunction alwaysconstructsarraysinrectangularform. Thematrixfunctionsdet,transpose,multiply,andinvertcanbeusedonmatricesbuiltwithnestedlistsorarraysbuiltwitharray.

Formoredetails,seearray,array?,andarraylistinthereferencesectionofthismanual. ()

12.Indexingelementsofstrings,lists,andarrays
Somefunctionstakearray,list,orstringelements(characters)specifiedbyoneormoreintindex(integerindex).Thepositive indicesrun0 ,1 , ,N 2 ,N 1 ,whereN isthenumberofelementsinthelist.Ifintindexisnegative,thesequenceisN ,N + 1 , ,2 ,1 .AddingN tothenegativeindexofanelementyieldsthepositiveindex.Unlessafunctiondoesotherwise,anindex greaterthanN 1 orlessthenNcausesanoutofboundserrorinlistsandarrays.

Implicitindexingforn t h
Implicitindexingcanbeusedinsteadofnthtoretrievetheelementsofalistorarrayorthecharactersofastring:
( s e t' l s t' ( abc( de )( fg ) ) ) ( l s t0 ) ( l s t3 ) ( l s t31 ) ( l s t1 ) a ;s a m ea s( n t h0l s t ) ( de ) e ;s a m ea s( n t h' ( 31 )l s t ) ( fg )

( s e t' m y a r r a y( a r r a y32( s e q u e n c e16 ) ) ) ( m y a r r a y1 ) ( 34 ) ( m y a r r a y10 ) 3 ( m y a r r a y01 ) 2 ( " n e w L I S P "3 ) " L "

Indicesmayalsobesuppliedfromalist.Inthisway,implicitindexingworkstogetherwithfunctionsthattakeorproduceindex vectors,suchaspush,pop,refandrefall.
( l s t' ( 31 ) ) ( s e t' v e c( r e f' el s t ) ) ( l s tv e c ) e ( 31 ) e

NotethatimplicitindexingisnotbreakingnewLISPsyntaxrulesbutismerelyanexpansionofexistingrulestootherdatatypesin thefunctorpositionofansexpression.InoriginalLisp,thefirstelementinansexpressionlistisappliedasafunctiontotherest elementsasarguments.InnewLISP,alistinthefunctorpositionofansexpressionassumesselfindexingfunctionalityusingthe indexargumentsfollowingit. Implicitindexingisfasterthantheexplicitforms,buttheexplicitformsmaybemorereadabledependingoncontext. NotethatintheUTF8enabledversionofnewLISP,implicitindexingofstringsorusingthenthfunctionworkoncharacterrather thansinglebyteboundaries.

Implicitindexingandthedefaultfunctor
Thedefaultfunctorisafunctorinsideacontextwiththesamenameasthecontextitself.SeeThecontextdefaultfunctionchapter. Adefaultfunctorcanbeusedtogetherwithimplicitindexingtoserveasamechanismforreferencinglists:
( s e t' M y L i s t : M y L i s t' ( abcdefg ) ) ( M y L i s t0 ) a ( M y L i s t3 ) d ( M y L i s t1 ) g

( 32M y L i s t )( de ) ( 3M y L i s t ) ( efg ) ( s e t' a L i s tM y L i s t ) ( a L i s t3 ) d

Inthisexample,a L i s t referencesM y L i s t : M y L i s t ,notacopyofit.Formoreinformationaboutcontexts,seeVariablesholding contexts. Theindexeddefaultfunctorcanalsobeusedwithsetfasshowninthefollowingexample:


( s e t' M y L i s t : M y L i s t' ( abcdefg ) ) ( s e t f( M y L i s t3 )9 9 9 ) ( M y L i s t3 ) M y L i s t : M y L i s t 9 9 9 9 9 9 ( abc9 9 9efg )

Implicitindexingforr e s t ands l i c e
Implicitformsofrestandslicecanbecreatedbyprependingalistwithoneortwonumbersforoffsetandlength.Ifthelengthis negativeitcountsfromtheendofthelistorstring:
( s e t' l s t' ( abcdefg ) ) ;o ra sa r r a y ( s e t' l s t( a r r a y7' ( abcdefg ) ) ) ( 1l s t ) ( 2l s t ) ( 23l s t ) ( 32l s t ) ( 22l s t ) ( bcdefg ) ( cdefg ) ( cde ) ( ef ) ( cde )

( s e t' s t r" a b c d e f g " ) ( 1s t r ) ( 2s t r ) ( 23s t r ) ( 32s t r ) ( 22s t r ) " b c d e f g " " c d e f g " " c d e " " e f " " c d e "

Thefunctionsrest,firstandlastworkonmultibytecharacterboundariesinUTF8enabledversionsofnewLISP.Buttheimplicit indexingformsforslicingandrestingwillalwaysworkonsinglebyteboundariesandcanbeusedforbinarycontent.Offsetand lengthresultsfromtheregularexpressionfunctionsfindandregexarealsoinsinglebytecountsandcanbefurtherprocessedwith sliceorit'simplicitform.

Modifyreferencesinlists,arraysandstrings
Partsinlists,arraysandstringsreferencedbyindicescanbemodifiedusingsetf:
;l i s t s ( s e t' l s t' ( abcd( efg ) ) ) ( l s t1 )b ( s e t f( l s t1 )' z )z l s t( azcd( efg ) ) ( s e t f( l s t1 )' ( EFG ) )( EFG )

l s t( azcd( EFG ) ) ;a r r a y s ( s e t' m y a r r a y( a r r a y23( s e q u e n c e16 ) ) )( ( 123 )( 456 ) ) ( s e t f( m y a r r a y12 )6 6 )6 6 m y a r r a y( ( 123 )( 456 6 ) ) ;s t r i n g s ( s e t' s" N e w L I S P " ) ( s e t f( s0 )" n " )" n " s" n e w L I S P "

Notethatonlyfullelementsornestedlistsorarrayscanbechangedthisway.Slicesorrestpartsoflistsorarraysasusedinimplicit restingorslicingcannotbesubstitutedatonceusingsetf,butwouldhavetobesubstitutedelementbyelement.Instringsonlyone charactercanbereplacedatatime,butthatcharactercanbereplacedbyamulticharacterstring. ()

13.Destructiveversusnondestructivefunctions
MostoftheprimitivesinnewLISParenondestructive(nosideeffects)andleaveexistingobjectsuntouched,althoughtheymay createnewones.Thereareafewdestructivefunctions,however,thatdochangethecontentsofavariable,list,array,orstring: function ++ bind constant extend dec define inc netreceive pop popassoc push read receive replace reverse rotate set setfsetq setref setrefall sort swap description incrementsnumbersinintegermode decrementsnumbersinintegermode bindsvariableassociationsinalist setsthecontentsofavariableandprotectsit extendsalistorstring decrementsanumberreferencedbyavariable,listorarray setsthecontentsofavariable incrementsanumberreferencedbyavariable,listorarray readsintoabuffervariable popsanelementfromalistorstring removesanassociationfromanassociationlist pushesanewelementontoalistorstring readsintoabuffervariable receivesamessagefromaparentorchildprocess replaceselementsinalistorstring reversesalistorstring rotatestheelementsofalistorcharactersofastring setsthecontentsofavariable setsthecontentsofavariable,list,arrayorstring searchesforanelementinanestedlistandreplacesit searchesforanelementinanestedlistandreplacesallinstances sortstheelementsofalistorarray swapstwoelementsinsidealistorstring

Makeadestructivefunctionnondestructive
Somedestructivefunctionscanbemadenondestructivebywrappingthetargetobjectintothecopyfunction.
( s e t' a L i s t' ( abcdef ) ) ( r e p l a c e' c( c o p ya L i s t ) )( abdef ) a L i s t( abcdef )

Thelistina L i s t isleftunchanged. ()

14.Earlyreturnfromfunctions,loops,andblocks
Whatfollowsaremethodsofinterruptingthecontrolflowinsidebothloopsandthebeginexpression. Theloopingfunctionsdolistanddotimescantakeoptionalconditionalexpressionstoleavetheloopearly.catchandthrowarea moregeneralformtobreakoutofaloopbodyandarealsoapplicabletootherformsorstatementblocks.

Usingc a t c h andt h r o w
BecausenewLISPisafunctionallanguage,itusesnob r e a k orr e t u r n statementstoexitfunctionsoriterations.Instead,ablockor functioncanbeexitedatanypointusingthefunctionscatchandthrow:
( d e f i n e( f o ox ) . . . ( i fc o n d i t i o n( t h r o w1 2 3 ) ) . . . 4 5 6 ) ; ;i fc o n d i t i o ni st r u e ( c a t c h( f o op ) ) 1 2 3 ; ;i fc o n d i t i o ni sn o tt r u e ( c a t c h( f o op ) ) 4 5 6

Breakingoutofloopsworksinasimilarway:
( c a t c h ( d o t i m e s( iN ) ( i f( =( f o oi )1 0 0 )( t h r o wi ) ) ) ) v a l u eo fiw h e nf o o ( i )e q u a l s1 0 0

TheexampleshowshowaniterationcanbeexitedbeforeexecutingN times. Multiplepointsofreturncanbecodedusingthrow:


( c a t c h( b e g i n ( f o o 1 ) ( f o o 2 ) ( i fc o n d i t i o n A( t h r o w' x ) ) ( f o o 3 )

( i fc o n d i t i o n B( t h r o w' y ) ) ( f o o 4 ) ( f o o 5 ) ) )

Ifc o n d i t i o n A istrue,x willbereturnedfromthec a t c h expressionifc o n d i t i o n B istrue,thevaluereturnedisy .Otherwise, theresultfromf o o 5 willbeusedasthereturnvalue. Asanalternativetocatch,theerroreventfunctioncanbeusedtocatcherrorscausedbyfaultycodeoruserinitiatedexceptions. Thethrowerrorfunctionmaybeusedtothrowuserdefinederrors.

Usinga n d ando r
Usingthelogicalfunctionsandandor,blocksofstatementscanbebuiltthatareexiteddependingontheBooleanresultofthe enclosedfunctions:
( a n d ( f u n c a ) ( f u n c b ) ( f u n c c ) ( f u n c d ) )

Theandexpressionwillreturnassoonasoneoftheblock'sfunctionsreturnsn i l oran( ) (emptylist).Ifnoneofthepreceding functionscausesanexitfromtheblock,theresultofthelastfunctionisreturned. orcanbeusedinasimilarfashion:


( o r ( f u n c a ) ( f u n c b ) ( f u n c c ) ( f u n c d ) )

Theresultoftheorexpressionwillbethefirstfunctionthatreturnsavaluewhichisnotn i l or( ) . ()

15.Dynamicandlexicalscoping
newLISPusesdynamicscopinginsidecontexts.Acontextisalexicallyclosednamespace.Inthisway,partsofanewLISP programcanliveindifferentnamespacestakingadvantageoflexicalscoping. Whentheparametersymbolsofalambdaexpressionareboundtoitsarguments,theoldbindingsarepushedontoastack.newLISP automaticallyrestorestheoriginalvariablebindingswhenleavingthelambdafunction. Thefollowingexampleillustratesthedynamicscopingmechanism.ThetextinboldistheoutputfromnewLISP:
>( s e t' x1 ) 1 >( d e f i n e( f )x ) ( l a m b d a( )x ) >( f ) 1 >( d e f i n e( gx )( f ) ) ( l a m b d a( x )( f ) ) >( g0 ) 0 >( f ) 1 >_

Thevariablex isfirstsetto1 .Butwhen( g0 ) iscalled,x isboundto0 andx isreportedby( f ) as0 duringexecutionof( g0 ) . Afterexecutionof( g0 ) ,thecallto( f ) willreportx as1 again. ThisisdifferentfromthelexicalscopingmechanismsfoundinlanguageslikeCorJava,wherethebindingoflocalparameters occursinsidethefunctiononly.InlexicallyscopedlanguageslikeC,( f ) wouldalwaysprinttheglobalbindingsofthesymbolx with1 . Beawarethatpassingquotedsymbolstoauserdefinedfunctioncausesanameclashifthesamevariablenameisusedasafunction parameter:
( d e f i n e( i n c s y m b o lxy )( i n c( e v a lx )y ) ) ( s e t' y2 0 0 ) ( i n c s y m b o l' y1 2 3 ) 2 4 6 y 2 0 0 ;yi ss t i l l2 0 0

Becausetheglobaly sharesthesamesymbolasthefunction'ssecondparameter,i n c s y m b o l returns246(123+123),leavingthe globaly unaffected.Dynamicscoping'svariablecapturecanbeadisadvantagewhenpassingsymbolreferencestouserdefined functions.newLISPoffersseveralmethodstoavoidvariablecapture. Thefunctionargscanbeusedwhenpassingsymbols. Oneormoreuserdefinedfunctionscanbeplacedintheirownnamespacecalledacontext.Asymbolnameclashcannot occurwhenaccessingsymbolsandcallingfunctionsfromoutsideofthedefiningcontext. Contextsshouldbeusedtogrouprelatedfunctionswhencreatinginterfacesorfunctionlibraries.Thissurroundsthefunctionswith alexical"fence",thusavoidingvariablenameclasheswiththecallingfunctions. newLISPusescontextsfordifferentformsoflexicalscoping.SeethechaptersContextsanddefaultfunctorsformoreinformation. ()

16.Contexts
InnewLISP,symbolscanbeseparatedintonamespacescalledcontexts.Eachcontexthasaprivatesymboltableseparatefromall othercontexts.Symbolsknowninonecontextareunknowninothers,sothesamenamemaybeusedindifferentcontextswithout conflict. Contextsareusedtobuildmodulesofisolatedvariableandfunctiondefinitions.Theycanalsobecopiedanddynamicallyassigned tovariablesorpassedasarguments.BecausecontextsinnewLISPhavelexicallyseparatednamespaces,theyallowprogramming withlexicalscopingandsoftwareobjectstylesofprogramming. ContextsareidentifiedbysymbolsthatarepartoftherootorM A I N context.Althoughcontextsymbolsareuppercasedinthis chapter,lowercasesymbolsmayalsobeused. Inadditiontocontextnames,M A I N containsthesymbolsforbuiltinfunctionsandspecialsymbolssuchast r u e andn i l .TheM A I N contextiscreatedautomaticallyeachtimenewLISPisrun.ToseeallthesymbolsinM A I N ,enterthefollowingexpressionafter startingnewLISP:
( s y m b o l s )

Symbolcreationincontexts
Thefollowingrulesshouldsimplifytheprocessofunderstandingcontextsbyidentifyingtowhichcontextthecreatedsymbolsare beingassigned. 1. newLISPfirstparsesandtranslateseachtoplevelexpression.Thesymbolsarecreatedduringthisphase.Aftertheexpression

istranslated,itgetsevaluated. 2. AsymboliscreatedwhennewLISPfirstseesit,whilecallingtheload,sym,orevalstringfunctions.WhennewLISPreadsa sourcefile,symbolsarecreatedbeforeevaluationoccurs. 3. Whenanunknownsymbolisencounteredduringcodetranslation,asearchforitsdefinitionbeginsinsidethecurrentcontext. Failingthat,thesearchcontinuesinsideM A I N forabuiltinfunction,context,orglobalsymbol.Ifnodefinitionisfound,the symboliscreatedlocallyinsidethecurrentcontext. 4. Onceasymboliscreatedandassignedtoaspecificcontext,itwillbelongtothatcontextpermanently. 5. Whenauserdefinedfunctionisevaluated,thecontextisswitchedtothenamespacewhichownsthethatsymbol. 6. Acontextswitchonlyinfluencessymbolcreationduringload,sym,orevalstring.loadbydefaultloadsintoMAINexcept whencontextswitchesoccuronthetoplevelofthefileloaded.Thecontextshouldalwaysbespecifiedwhenthefunctions symandevalstringareused.Whenthisruleisfollowed,acontextswitchshouldonlyoccuronthetoplevelofaprogram, neverinsideafunction.

Creatingcontexts
Contextscanbecreatedeitherbyusingthecontextfunctionorviaimplicitcreation.Thefirstmethodisusedwhenwritinglarger portionsofcodebelongingthesamecontext:
( c o n t e x t' F O O ) ( s e t' v a r1 2 3 ) ( d e f i n e( f u n cxyz ) . . .) ( c o n t e x tM A I N )

Ifthecontextdoesnotexistyet,thecontextsymbolmustbequoted.Ifthesymbolisnotquoted,newLISPassumesthesymbolisa variableholdingthesymbolofthecontexttocreate.Becauseacontextevaluatestoitself,existingcontextslikeMAINdonot requirequoting. WhennewLISPreadstheabovecode,itwillread,thenevaluatethefirststatement:( c o n t e x t' F O O ) .ThiscausesnewLISPto switchthenamespacetoFOOandthefollowingsymbolsv a r ,x ,y andz willallbecreatedintheFOOcontextwhenreadingand evaluatingtheremainingexpressions. Torefertov a r orf u n c fromanywhereelseoutsidetheFOOnamespacetheyneedtobeprefixedwiththecontextname:
F O O : v a r1 2 3 ( F O O : f u n cpqr )

Thesymbolsfunctionisusedtoshowallsymbolsbelongingtoacontext:
( s y m b o l sF O O )( F O O : f u n cF O O : v a rF O O : xF O O : yF O O : z )

Implicitlycreatingcontexts Acontextisimplicitlycreatedwhenreferringtoonethatdoesnotyetexist.Unlikethec o n t e x t function,thecontextisnot switched.ThefollowingstatementsareallexecutedinsidetheM A I N context:


>( s e t' A C T X : v a r" h e l l o " ) " h e l l o " >A C T X : v a r " h e l l o " >_

Notethatonlythesymbolsprefixedwiththeircontextnamewillbepartofthecontext:
( d e f i n e( A C T X : f o oxy ) ( +xy ) )

WhenabovecodeisloadedinMAINonlyf o o willbepartofA C T X .Thesymbolsx andy willstillbepartofM A I N . Loadingmodulefiles Whenloadingsourcefilesonthecommandlinewithload,orwhenexecutingthefunctionsevalstringorsym,thec o n t e x t functiontellsnewLISPwheretoputallofthesymbolsanddefinitions:


; ; ;f i l eM Y _ P R O G . L S P ; ; ; ;e v e r y t h i n gf r o mh e r eo ng o e si n t oG R A P H ( c o n t e x t' G R A P H ) ( d e f i n e( d r a w t r i a n g l exyz ) ( ) ) ( d e f i n e( d r a w c i r c l e ) ( ) ) ; ;s h o wt h er u n t i m ec o n t e x t ,w h i c hi sG R A P H ( d e f i n e( f o o ) ( c o n t e x t ) ) ; ;s w i t c hb a c kt oM A I N ( c o n t e x t' M A I N ) ; ;e n do ff i l e

Thed r a w t r i a n g l e andd r a w c i r c l e functionsalongwiththeirx ,y ,andz parametersarenowpartoftheG R A P H context. ThesesymbolsareknownonlytoG R A P H .Tocallthesefunctionsfromanothercontext,prefixthemwithG R A P H :


( G R A P H : d r a w t r i a n g l e123 ) ( G R A P H : f o o ) G R A P H

ThelaststatementshowshowtheruntimecontexthaschangedtoG R A P H (functionf o o 'scontext). Asymbol'snameandcontextareusedwhencomparingsymbolsfromdifferentcontexts.Thetermfunctioncanbeusedtoextract thetermpartfromafullyqualifiedsymbol.


; ;s a m es y m b o ln a m e ,b u td i f f e r e n tc o n t e x tn a m e ( =' A : v a l' B : v a l ) n i l ( =( t e r m' A : v a l )( t e r m' B : v a l ) ) t r u e

Note:Thesymbolsarequotedwitha' (singlequote)becauseweareinterestedinthesymbolitself,notinthecontentsofthe symbol.

Globalscope
Bydefault,onlybuiltinfunctionsandsymbolsliken i l andt r u e arevisibleinsidecontextsotherthanM A I N .Tomakeasymbol visibletoeverycontext,usetheglobalfunction:
( s e t' a V a r1 2 3 )1 2 3 ( g l o b a l' a V a r ) a V a r ( c o n t e x t' F O O ) F O O a V a r 1 2 3

Withouttheg l o b a l statement,theseconda V a r wouldhavereturnedn i l insteadof1 2 3 .IfF O O hadapreviouslydefinedsymbol (a V a r inthisexample)thatsymbol'svalueandnottheglobal'swouldbereturnedinstead.Notethatonlysymbolsfromthe

M A I N contextcanbemadeglobal.

Onceitismadevisibletocontextsthroughtheglobalfunction,asymbolcannotbehiddenfromthemagain.

Symbolprotection
Byusingtheconstantfunction,symbolscanbebothsetandprotectedfromchangeatthesametime:
>( c o n s t a n t' a V a r1 2 3 ) 1 2 3 >( s e t' a V a r9 9 9 ) E R R :s y m b o li sp r o t e c t e di nf u n c t i o ns e t:a V a r > _

Asymbolneedingtobebothaconstantandaglobalcanbedefinedsimultaneously:
( c o n s t a n t( g l o b a l' a V a r )1 2 3 )

Inthecurrentcontext,symbolsprotectedbyc o n s t a n t canbeoverwrittenbyusingthec o n s t a n t functionagain.Thisprotectsthe symbolsfrombeingoverwrittenbycodeinothercontexts.

Overwritingglobalsymbolsandbuiltins
Globalandbuiltinfunctionsymbolscanbeoverwritteninsideacontextbyprefixingthemwiththeirowncontextsymbol:
( c o n t e x t' A c c o u n t ) ( d e f i n e( A c c o u n t : n e w ) ( ) ) ( c o n t e x t' M A I N )

Inthisexample,thebuiltinfunctionnewisoverwrittenbyA c c o u n t : n e w ,adifferentfunctionthatisprivatetotheA c c o u n t context.

Variablescontainingcontexts
Variablescanbeusedtorefertocontexts:
( s e t' F O O : x1 2 3 ) ( s e t' c t xF O O ) c t x : x F O O 1 2 3

( s e t' c t x : x9 9 9 ) 9 9 9 F O O : x 9 9 9

Contextvariablesareusefulwhenwritingfunctions,whichneedtoswitchcontextsorusecontextswhichdonotexistyet:
( d e f i n e( u p d a t ec t xv a l ) ( s e t' c t x : s u mv a l ) ( c t x : f u n c9 9 9 ) ) ( c o n t e x t' F O O ) ( d e f i n e( f u n cx ) ( p r i n t l n" = > "x ) ) ( c o n t e x tM A I N )

Thefollowingshowsaterminalsessionusingabovedefinitions.Theprogramoutputisshowninboldface:

>( u p d a t eF O O1 2 3 ) = >9 9 9 >F O O : s u m 1 2 3 >

Thesameonefunctionu p d a t e candisplaydifferentbehaviordependingonthecontextpassedasfirstparameter.

Sequenceofcreatingorloadingcontexts
Thesequenceinwhichcontextsarecreatedorloadedcanleadtounexpectedresults.Enterthefollowingcodeintoafilecalled d e m o :
; ;d e m o-f i l ef o rl o a d i n gc o n t e x t s ( c o n t e x t' F O O ) ( s e t' A B C1 2 3 ) ( c o n t e x tM A I N ) ( c o n t e x t' A B C ) ( s e t' F O O4 5 6 ) ( c o n t e x t' M A I N )

Nowloadthefileintothenewlispshell:
>( l o a d" d e m o " ) E R R :s y m b o li sp r o t e c t e di nf u n c t i o ns e t:F O O >_

LoadingthefilecausesanerrormessageforF O O ,butnotforA B C .WhenthefirstcontextF O O isloaded,thecontextA B C doesnot existyet,soalocalvariableF O O : A B C getscreated.WhenA B C loads,F O O alreadyexistsasaglobalprotectedsymbolandwillbe correctlyflaggedasprotected.
F O O couldstillbeusedasalocalvariableintheA B C contextbyexplicitlyprefixingit,asinA B C : F O O .

Thefollowingpatterncanbeappliedtoavoidunexpectedbehaviorwhenloadingcontextsbeingusedasmodulestobuildlarger applications:
; ;b e g i no ff i l e-M y M o d u l e . l s p ( l o a d" T h i s . l s p " ) ( l o a d" T h a t . l s p " ) ( l o a d" O t h e r . l s p " ) ( c o n t e x t' M y M o d u l e ) ( d e f i n e( f u n cxyz )( ) ) ( c o n t e x t' M A I N ) ( M y M o d u l e : f u n c123 ) ( e x i t ) ; ;e n do ff i l e

Alwaysloadthemodulesrequiredbyacontextbeforethemodule'sc o n t e x t statement.Alwaysfinishbyswitchingbacktothe M A I N context,wherethemodule'sfunctionsandvaluescanbesafelyaccessed.

Contextsasprogrammingmodules

ContextsinnewLISParemainlyusedforpartitioningsourceintomodules.Becauseeachmodulelivesinadifferentnamespace, modulesarelexicallyseparatedandthenamesofsymbolscannotclashwithidenticalnamesinothermodules. Themodules,whicharepartofthenewLISPdistribution,areagoodexampleofhowtoputrelatedfunctionsintoamodulefile,and howtodocumentmodulesusingthenewLISPdocutility. Forbestprogrammingpractice,afileshouldonlycontainonemoduleandthefilenameshouldbesimilarifnotidenticaltothe contextnameused:


; ;f i l ed b . l s p ,c o m m o n l yu s e dd a t a b a s ef u n c t i o n s ( c o n t e x t' d b ) ; ;V a r i a b l e su s e dt h r o u g h o u tt h i sn a m e s p a c e ( d e f i n ed b : h a n d l e ) ( d e f i n ed b : h o s t" h t t p : / / l o c a l h o s t " ) ; ;C o n s t a n t s ( c o n s t a n t' M a x _ N1 0 0 0 0 0 0 ) ( c o n s t a n t' P a t h" / u s r / d a t a / " ) ; ;F u n c t i o n s ( d e f i n e( d b : o p e n. . .) . . .) ( d e f i n e( d b : c l o s e. . .) . . .) ( d e f i n e( d b : u p d a t e. . .) . . .)

Theexampleshowsagoodpracticeofpredefiningvariables,whichareglobalinsidethenamespace,anddefiningasconstantsthe variablesthatwillnotchange. Ifafilecontainsmorethanonecontext,thentheendofthecontextshouldbemarkedwithaswitchbacktoM A I N :


; ;M u l t ic o n t e x tf i l em u l t i . l s p ( c o n t e x t' A c t x ) . . . ( c o n t e x tM A I N ) ( c o n t e x t' B c t x ) . . . ( c o n t e x tM A I N ) ( c o n t e x t' C c t x ) . . . ( c o n t e x tM A I N )

Contextsasdatacontainers
Contextsarefrequentlyusesasdatacontainers,e.g.forhashlikedictionariesandconfigurationdata:
; ;C o n f i g . l s p-c o n f i g u r a t i o ns e t u p ( c o n t e x t' C o n f i g ) ( s e t' u s e r n a m e" a d m i n " ) ( s e t' p a s s w o r d" s e c r e t " ) ( s e t' d b n a m e" / u s r / d a t a / d b . l s p " ) . . . ; ;e o f

LoadingtheC o n f i g namespacewillnowloadawholevariablesetintomemoryatonce:
( l o a d" C o n f i g . l s p " ) ( s e t' f i l e( o p e nC o n f i g : d b n a m e" r e a d " ) ) . . . . . .

Inasimilarfashionawholedatasetcanbesaved:
( s a v e" C o n f i g . l s p "' C o n f i g )

ReadmoreaboutthisinthesectionSerializingcontexts.

Loadinganddeclaringcontexts
Modulefilesareloadedusingtheloadfunction.Ifaprogrammingprojectcontainsnumerousmodulesthatrefertoeachother,they shouldbepredeclaredtoavoidproblemsduetocontextforwardreferencesthatcanoccurbeforetheloadingofthatcontext.
; ;p r e d e c l a r i n gc o n t e x t s ,f i n i s hw i t hM a i nt or e t u r n ( m a pc o n t e x t' ( U t i l i t i e sC o n f i gA c q u i s i t i o nA n a l y s i sS y s L o gM A I N ) ) ; ;l o a d i n gc o n t e x tm o d u l ef i l e s ( l o a d" U t i l i t i e s . l s p "" A c q u i s i t i o n . l s p " ) ( l o a d" h t t p : / / 1 9 2 . 1 6 8 . 1 . 3 4 / C o n f i g . l s p " );l o a dm o d u l ef r o mr e m o t el o c a t i o n ( l o a d" A n a l y s i s . l s p "" S y s L o g . l s p " ) ( d e f i n e( r u n ) . . .) ( r u n ) ; ;e n do ff i l e

Whenpredeclaringandloadingmodulesasshownintheexample,thesequenceofdeclarationorloadingcanbeneglected.All forwardreferencestovariablesanddefinitionsinmodulesnotloadedyetwillbetranslatedcorrectly. ModulesnotstartingwithacontextswitcharealwaysloadedintoM A I N exceptwhentheloadstatementspecifiesatargetcontextas thelastparameter.TheloadfunctioncantakeU R L stoloadmodulesfromremotelocations,viaH T T P . Thecurrentcontextaftertheloadstatementwillalwaysbethesameasbeforetheload.

Serializingcontexts
Serializationmakesasoftwareobjectpersistentbyconvertingitintoacharacterstream,whichisthensavedtoafileorstringin memory.InnewLISP,anythingreferencedbyasymbolcanbeserializedtoafilebyusingthesavefunction.Likeothersymbols, contextsaresavedjustbyusingtheirnames:
( s a v e" m y c o n t e x t . l s p "' M y C t x ) ( l o a d" m y c o n t e x t . l s p " ) ;s a v eM y C t xt om y c o n t e x t . l s p ;l o a d sM y C t xi n t om e m o r y

( s a v e" m y c o n t e x t s . l s p "' C t x 1' C t x 2' C t x 3 ) ;s a v em u l t i p l ec o n t e x t sa to n c e

Fordetails,seethefunctionssave(mentionedabove)andsource(forserializingtoanewLISPstring). ()

17.Thecontextdefaultfunctor
Adefaultfunctorordefaultfunctionisasymboloruserdefinedfunctionormacrowiththesamenameasitsnamespace.Whenthe contextisusedasthenameofafunctionorinthefunctorpositionofansexpression,newLISPexecutesthedefaultfunction.
; ;t h ed e f a u l tf u n c t i o n ( d e f i n e( F o o : F o oabc )( +abc ) ) ( F o o123 ) 6

IfadefaultfunctioniscalledfromacontextotherthanM A I N ,thecontextmustalreadyexistorbedeclaredwithaforward declaration,whichcreatesthecontextandthefunctionsymbol:


; ;f o r w a r dd e c l a r a t i o no fad e f a u l tf u n c t i o n ( d e f i n eF u b a r : F u b a r ) ( c o n t e x t' F o o ) ( d e f i n e( F o o : F o oabc ) ( F u b a rab ) ;f o r w a r dr e f e r e n c e ( ) ) ;t od e f a u l tf u n c t i o n ( c o n t e x tM A I N ) ; ;d e f i n i t i o no fp r e v i o u s l yd e c l a r e dd e f a u l tf u n c t i o n ( c o n t e x t' F u b a r ) ( d e f i n e( F u b a r : F u b a rxy ) ( ) ) ( c o n t e x tM A I N )

Defaultfunctionsworklikeglobalfunctions,buttheyarelexicallyseparatefromthecontextinwhichtheyarecalled. Likealambdaorlambdamacrofunction,defaultfunctionscanbeusedwithmaporapply.

Functionswithmemory
Adefaultfunctioncanupdatethelexicallyisolatedstaticvariablescontainedinsideitsnamespace:
; ;af u n c t i o nw i t hm e m o r y ( d e f i n e( G e n : G e nx ) ( i fG e n : a c c ( i n cG e n : a c cx ) ( s e t qG e n : a c cx ) ) ) ( G e n1 ) ( G e n1 ) ( G e n2 ) ( G e n3 ) 1 2 4 7

g e n : a c c 7

ThefirsttimetheG e n functioniscalled,itsaccumulatorissettothevalueoftheargument.EachsuccessivecallincrementsG e n 's accumulatorbytheargument'svalue. ThedefinitionofG e n : G e n shows,howafunctionisputinitsownnamespacewithoutusingthesurrounding( c o n t e x t' G e n ) and ( c o n t e x tM A I N ) statements.InthatcaseonlysymbolsqualifiedbythenamespaceprefixwillendupintheG e n context.Inthe aboveexamplethevariablex isstillpartofM A I N .

Hashfunctionsanddictionaries
Thereareseveralfunctionsthatcanbeusedtoplacesymbolsintonamespacecontexts.Whenusingdictionariesassimplehashlike collectionsofvariablevaluepairs,usetheuninitializeddefaultfunctor:
( d e f i n eM y h a s h : M y h a s h );c r e a t en a m e s p a c ea n dd e f a u l tf u n c t o r ;o ra sa na l t e r n a t i v eu s e ( n e wT r e e' M y H a s h );c r e a t ef r o mb u i l t i nt e m p l a t e

EithermethodcanbeusedtomaketheM y H a s h dictionaryspaceanddefaultfunctor.Creatingkeyvaluepairsandretrievingavalue iseasy:


( M y h a s h" v a r "1 2 3 );c r e a t ea n ds e tv a r i a b l e / v a l u ep a i r ( M y h a s h" v a r " );1 2 3;r e t r i e v ev a l u e

Notethatthedefaultfunctorshouldnotbeinitializedtoanyvalueotherthann i l .Thedefaultfunctorworkslikeadictionaryhash functioncreatingthesymbolsinthestringfollowingitandsettingittothevalueifspecified. SymbolvariablescreatedthiswaycancontainspacesorothercharactersnormallynotallowedinnewLISPsymbolnames:


( d e f i n eF o o : F o o ) ( F o o" J o h nD o e "1 2 3 ) 1 2 3 ( F o o" # 1 2 3 4 "" h e l l ow o r l d " ) " h e l l ow o r l d " ( F o o" v a r "' ( abcd ) ) ( abcd ) ( F o o" J o h nD o e " ) 1 2 3 ( F o o" # 1 2 3 4 " ) " h e l l ow o r l d " ( F o o" v a r " ) ( abcd )

Anentrywhichdoesn'texistwillreturnn i l :
( F o o" b a r " ) n i l

Settinganentryton i l willeffectivelydeleteitfromthenamespace. Anassociationlistcanbegeneratedfromthecontentsofthenamespace:


( F o o )( ( " # 1 2 3 4 "" h e l l ow o r l d " )( " J o h nD o e "1 2 3 )( " v a r "( abcd ) ) )

Entriesinthedictionarycanalsobecreatedfromalist:
( F o o' ( ( " # 1 2 3 4 "" h e l l ow o r l d " )( " J o h nD o e "1 2 3 )( " v a r "( abcd ) ) )F o o

Thelistcanalsobeusedtoiteratethroughthesortedkey>valuepairs:
( d o l i s t( i t e m( F o o ) )( p r i n t l n( i t e m0 )">"( i t e m1 ) ) ) # 1 2 3 4>h e l l ow o r l d J o h nD o e>1 2 3 v a r>( abcd )

Likemanybuiltinfunctionshashexpressionsreturnareferencetotheircontentwhichcanbemodifieddirectly:
( p o p( F o o" v a r " ) )a ( F o o" v a r " )( bcd ) ( p u s h' z( F o o" v a r " ) )( zbcd ) ( F o o" v a r " )( zbcd )

Whensettinghashvaluestheanaphoricsystemvariable$ i t canbeusedtorefertotheoldvaluewhensettingthenew:
( F o o" b a r "" h e l l ow o r l d " )

( F o o" b a r "( u p p e r c a s e$ i t ) ) ( F o o" b a r " )" H E L L OW O R L D "

Hashvaluesalsocanbemodifiedusingsetf:
( F o o" b a r "1 2 3 ) 1 2 3

( s e t f( F o o" b a r " )4 5 6 )4 5 6 ( F o o" b a r " ) 4 5 6

Butsupplyingthevalueasasecondparametertothehashfunctionsisshortertowriteandfaster. Dictionariescaneasilybesavedtoafileandreloadedlater:
;s a v ed i c t i o n a r y ( s a v e" F o o . l s p "' F o o ) ;l o a dd i c t i o n a r y ( l o a d" F o o . l s p " )

Internallythekeystringsarecreatedandstoredassymbolsinthehashcontext.Allkeystringsareprependedwithan_ underscore character.Thisprotectsagainstoverwritingthedefaultsymbolandsymbolslikes e t ands y m ,whichareneededwhenloadinga hashnamespacefromdiskoroverH T T P .Notethefollowingdifference:


( F o o )( ( " # 1 2 3 4 "" h e l l ow o r l d " )( " J o h nD o e "1 2 3 )( " v a r "( abcd ) ) ) ( s y m b o l sF o o )( F o o : F o oF o o : _ # 1 2 3 4F o o : _ J o h nD o eF o o : _ v a r )

Inthefirstlinehashsymbolsareshownasstringswithouttheprecedingunderscorecharacters.Thesecondlineshowstheinternal formofthesymbolswithprependedunderscorecharacters. Foramoredetailedintroductiontonamespaces,seethechapteronContexts.

Passingdatabyreference
Adefaultfunctorcanalsobeusedtoholddata.Ifthisdatacontainsalistorstring,thecontextnamecanbeusedasareferenceto thedata:
; ;t h ed e f a u l tf u n c t o rf o rh o l d i n gd a t a ( d e f i n eM y l i s t : M y l i s t' ( abcdefg ) ) ( M y l i s t3 )d ( s e t f( M y l i s t3 )' D )D M y l i s t : M y l i s t( abcDefg ) ; ;a c c e s sl i s to rs t r i n gd a t af r o mad e f a u l tf u n c t o r ( f i r s tM y l i s t )a ( r e v e r s eM y l i s t )( gfeDcba ) ( s e t' S t r : S t r" a c d e f g h i j k l m n o p " ) ( u p p e r c a s eS t r )" A C D E F G H I J K L M N O P "

Mostofthetime,newLISPpassesparametersbyvaluecopy.Thisposesapotentialproblemwhenpassinglargelistsorstringsto userdefinedfunctionsormacros.Stringsandlists,whicharepackedinanamespaceusingdefaultfunctors,arepassed automaticallybyreference:

; ;u s ead e f a u l tf u n c t o rt oh o l dal i s t ( s e t' M y d b : M y d b( s e q u e n c e11 0 0 0 0 0 ) ) ( d e f i n e( c h a n g e d bo b ji d xv a l u e ) ( s e t f( o b ji d x )v a l u e ) ) ;p a s sb yc o n t e x tr e f e r e n c e ( c h a n g e d bM y d b1 2 3 4" a b c d e f g " ) ( M y d b1 2 3 4 ) " a b c d e f g "

Anyargumentofabuiltinfunctioncallingforeitheralistorastringbutnootherdatatypecanreceivedatapassedby reference.Anyuserdefinedfunctioncantakeeithernormalvariables,orcantakeacontextnameforpassingareferencetothe defaultfunctorcontainingalistorstring. Notethatonlistswithlessthanabout100elementsorstringsoflessthanabout50000characters,thespeeddifferencebetween referenceandvaluepassingisnegligible.Butonbiggerdataobjects,differencesinbothspeedandmemoryusagebetween referenceandvaluepassingcanbesignificant. Builtinanduserdefinedfunctionsaresuitableforbothtypesofarguments,butwhenpassingcontextnames,datawillbepassedby reference. Quotedsymbolscanalsobeusedtopassdatabyreference,butthismethodhasdisadvantages:


( d e f i n e( c h a n g e l i s ta L i s t )( p u s h9 9 9( e v a la L i s t ) ) ) ( s e t' d a t a' ( 12345 ) ) ;n o t et h eq u o t e'i nf r o n to fd a t a ( c h a n g e l i s t' d a t a ) ( 9 9 912345 ) d a t a ( 9 9 912345 )

Althoughthismethodissimpletounderstandanduse,itposesthepotentialproblemofvariablecapturewhenpassingthesame symbolasusedasafunctionparameter:
; ;p a s sd a t ab ys y m b o lr e f e r e n c e >( s e t' a L i s t' ( abcd ) ) ( abcd ) >( c h a n g e l i s t' a L i s t ) E R R :l i s to rs t r i n ge x p e c t e d:( e v a la L i s t ) c a l l e df r o mu s e rd e f i n e df u n c t i o nc h a n g e l i s t >

Atthebeginningofthechapteritwasshownhowtopackagedatainanamespaceusingadefaultfunctor.Notonlythedefault functorbutanysymbolincontextcanbeusedtoholddata.Thedisadvantageisthatthecallingfunctionmusthaveknowledge aboutthesymbolbeingused:


; ;p a s sd a t ab yc o n t e x tr e f e r e n c e ( s e t' M y d b : d a t a( s e q u e n c e11 0 0 0 0 0 ) ) ( d e f i n e( c h a n g e d bo b ji d xv a l u e ) ( s e t f( o b j : d a t ai d x )v a l u e ) ) ( c h a n g e d bM y d b1 2 3 4" a b c d e f g " ) ( n t h1 2 3 4M y d b : d a t a ) " a b c d e f g " ;o r ( M y d b : d a t a1 2 3 4 ) " a b c d e f g "

Thefunctionreceivesthenamespaceinthevariableo b j ,butitmusthavetheknowledgethatthelisttoaccessiscontainedinthe d a t a symbolofthatnamespace(context).

()

18.Functionalobjectorientedprogramming
Functionalobjectorientedprogramming(FOOP)isbasedonthefollowingfiveprinciples: Classattributesandmethodsarestoredinthenamespaceoftheobjectclass. Thenamespacedefaultfunctorholdstheobjectconstructormethod. Anobjectisconstructedusingalist,thefirstelementofwhichisthecontextsymboldescribingtheclassoftheobject. Polymorphismisimplementedusingthe: (colon)operator,whichselectstheappropriateclassfromtheobject. Atargetobjectinsideaclassmethodfunctionisaccessedviatheselffunction. ThefollowingparagraphsareashortintroductiontoFOOPasdesignedbyMichaelMichaelsfromneglook.com.

FOOPclassesandconstructors
Classattributesandmethodsarestoredinthenamespaceoftheobjectclass.Noobjectinstancedataisstoredinthis namespace/context.Datavariablesintheclassnamespaceonlydescribetheclassofobjectsasawholebutdon'tcontainanyobject specificinformation.AgenericFOOPobjectconstructorcanbeusedasatemplateforspecificobjectconstructorswhencreating newobjectclasseswithn e w :
;b u i l t i ng e n e r i cF O O Po b j e c tc o n s t r u c t o r ( d e f i n e( C l a s s : C l a s s ) ( c o n s( c o n t e x t )( a r g s ) ) ) ;c r e a t es o m en e wc l a s s e s ( n e wC l a s s' R e c t a n g l e ) ( n e wC l a s s' C i r c l e ) R e c t a n g l e C i r c l e

;c r e a t es o m eo b j e c t su s i n gt h ed e f a u l tc o n s t r u c t o r ( s e t' r e c t( R e c t a n g l e1 02 0 ) ) ( s e t' c i r c( C i r c l e1 01 02 0 ) ) ( R e c t a n g l e1 02 0 ) ( C i r c l e1 01 02 0 )

;c r e a t eal i s to fo b j e c t s ;b u i l d i n gt h el i s tu s i n gt h el i s tf u n c t i o ni n s t e a do fa s s i g n i n g ;aq u o t e dl i s te n s u r e st h a tt h eo b j e c tc o n s t r u c t o r sa r ee x e c u t e d ( s e t' s h a p e s( l i s t( C i r c l e581 2 )( R e c t a n g l e48 )( C i r c l e771 5 ) ) ) ( ( C i r c l e581 2 )( R e c t a n g l e48 )( C i r c l e771 5 ) )

ThegenericFOOPconstructorisalreadypredefined,andFOOPcodecanstartwith( n e wC l a s s. . . ) statementsrightaway. Asamatterofstyle,newclassesshouldonlybecreatedintheMAINcontext.Ifcreatinganewclasswhileinadifferent namespace,thenewclassnamemustbeprefixedwithMAINandthestatementshouldbeonthetoplevel:


( c o n t e x t' G e o m e t r y ) ( n e wC l a s s' M A I N : R e c t a n g l e ) ( n e wC l a s s' M A I N : C i r c l e ) . . .

CreatingthenamespaceclassesusingnewreservestheclassnameasacontextinnewLISPandfacilitatesforwardreferences.At thesametime,asimpleconstructorisdefinedforthenewclassforinstantiatingnewobjects.Asaconvention,itisrecommendedto startclassnamesinuppercasetosignalthatthenamestandsforanamespace.

Insomecases,itmaybeusefultooverwritethesimpleconstructor,thatwascreatedduringclasscreation,withn e w :
;o v e r w r i t es i m p l ec o n s t r u c t o r ( d e f i n e( C i r c l e : C i r c l exyr a d i u s ) ( l i s tC i r c l exyr a d i u s ) )

Aconstructorcanalsospecifydefaults:
;c o n s t r u c t o rw i t hd e f a u l t s ( d e f i n e( C i r c l e : C i r c l e( x1 0 )( y1 0 )( r a d i u s3 ) ) ( l i s tC i r c l exyr a d i u s ) ) ( C i r c l e )( C i r c l e1 01 03 )

Inmanycasestheconstructorascreatedwhenusingn e w issufficientandoverwritingitisnotnecessary.

Objectsandassociations
FOOPrepresentsobjectsaslists.Thefirstelementofthelistindicatestheobject'skindorclass,whiletheremainingelements containthedata.Thefollowingstatementsdefinetwoobjectsusinganyoftheconstructorsdefinedpreviously:
( s e t' m y r e c t( R e c t a n g l e551 02 0 ) )( R e c t a n g l e551 02 0 ) ( s e t' m y c i r c l e( C i r c l e121 0 ) )( C i r c l e121 0 )

Anobjectcreatedisidenticaltothefunctionnecessarytocreateit(henceFOOP).Nestedobjectscanbecreatedinasimilarmanner:
;c r e a t ec l a s s e s ( n e wC l a s s' P e r s o n ) ( n e wC l a s s' A d d r e s s ) ( n e wC l a s s' C i t y ) ( n e wC l a s s' S t r e e t ) ;c r e a t ea no b j e c tc o n t a i n i n go t h e ro b j e c t s ( s e t' J o h n D o e( P e r s o n( A d d r e s s( C i t y" B o s t o n " )( S t r e e t1 2 3" M a i nS t r e e t " ) ) ) ) ( P e r s o n( A d d r e s s( C i t y" B o s t o n " )( S t r e e t1 2 3" M a i nS t r e e t " ) ) )

ObjectsinFOOPnotonlyresemblefunctionstheyalsoresembleassociations.Theassocfunctioncanbeusedtoaccessobjectdata byname:
( a s s o cA d d r e s sJ o h n D o e )( A d d r e s s( C i t y" B o s t o n " )( S t r e e t1 2 3" M a i nS t r e e t " ) ) ( a s s o c( l i s tA d d r e s sS t r e e t )J o h n D o e )( S t r e e t1 2 3" M a i nS t r e e t " )

Inasimilarmannersetftogetherwithassoccanbeusedtomodifyobjectdata:
( s e t f( a s s o c( l i s tA d d r e s sS t r e e t )J o h n D o e )' ( S t r e e t4 5 6" M a i nS t r e e t " ) ) ( S t r e e t4 5 6" M a i nS t r e e t " )

Thestreetnumberhasbeenchangedfrom1 2 3 to4 5 6 . Notethatinnoneofthea s s o c statementsA d d r e s s andS t r e e t needtocarryquotes.Thesameistrueinthesetstatement:( s e t ' J o h n D o e( P e r s o n. . . ) ) forthedatapartassigned.Inbothcaseswedonotdealwithsymbolsorlistsofsymbolsbutratherwith contextsandFOOPobjectswhichevaluatetothemselves.Quotingwouldnotmakeadifference.

Thecolon: operatorandpolymorphism
InnewLISP,thecoloncharacter: isprimarilyusedtoconnectthecontextsymbolwiththesymbolitisqualifying.Secondly,the colonfunctionisusedinFOOPtoresolveafunction'sapplicationpolymorphously. Thefollowingcodedefinestwofunctionscalleda r e a ,eachbelongingtoadifferentnamespace/class.Bothfunctionscouldhave beendefinedindifferentmodulesforbetterseparation,butinthiscasetheyaredefinedinthesamefileandwithoutbracketing

contextstatements.Here,onlythesymbolsr e c t a n g l e : a r e a andc i r c l e : a r e a belongtodifferentnamespaces.Thelocal parametersp ,c ,d x ,andd y areallpartofM A I N ,butthisisofnoconcern.


; ;c l a s sm e t h o d sf o rr e c t a n g l e s ( d e f i n e( R e c t a n g l e : a r e a ) ( m u l( s e l f3 )( s e l f4 ) ) ) ( d e f i n e( R e c t a n g l e : m o v ed xd y ) ( i n c( s e l f1 )d x ) ( i n c( s e l f2 )d y ) ) ; ;c l a s sm e t h o d sf o rc i r c l e s ( d e f i n e( C i r c l e : a r e a ) ( m u l( p o w( s e l f3 )2 )( a c o s0 )2 ) ) ( d e f i n e( C i r c l e : m o v ed xd y ) ( i n c( s e l f1 )d x ) ( i n c( s e l f2 )d y ) )

Byprefixingthea r e a orm o v e symbolwiththe: (colon),wecancallthesefunctionsforeachclassofobject.Althoughthereisno spacebetweenthecolonandthesymbolfollowingit,newLISPparsesthemasdistinctentities.Thecolonworksasafunctionthat processesparameters:


( : a r e am y r e c t )2 0 0;s a m ea s( :a r e am y r e c t ) ( : a r e am y c i r c l e )3 1 4 . 1 5 9 2 6 5 4;s a m ea s( :a r e am y c i r c l e ) ; ;m a pc l a s sm e t h o d su s e sc u r r yt oe n c l o s et h ec o l o no p e r a t o ra n dc l a s sf u n c t i o n ( m a p( c u r r y: a r e a )( l i s tm y r e c tm y c i r c l e ) )( 2 0 03 1 4 . 1 5 9 2 6 5 4 ) ( m a p( c u r r y: a r e a )' ( ( R e c t a n g l e551 02 0 )( C i r c l e121 0 ) ) )( 2 0 03 1 4 . 1 5 9 2 6 5 4 ) ; ;o b j e c t sa r em u t a b l e( s i n c ev 1 0 . 1 . 8 ) ( : m o v em y r e c t23 ) ( : m o v em y c i r c l e45 ) m y r e c t ( R e c t a n g l e781 02 0 ) m y c i r c l e ( C i r c l e571 0 )

Inthisexample,thecorrectqualifiedsymbol(r e c t a n g l e : a r e a orc i r c l e : a r e a )isconstructedandappliedtotheobjectdatabased onthesymbolfollowingthecolonandthecontextname(thefirstelementoftheobjectlist). Note,thatalthoughthecallerspecifiesthecalledtargetobjectofthecall,themethoddefinitiondoesnotincludetheobjectasa parameter.WhenwritingfunctionstomodifyFOOPobjects,insteadthefunctionselfisusedtoaccessandindextheobject.

StructuringalargerFOOPprogram
Inallthepreviousexamples,classfunctionmethodswheredirectlywrittenintotheMAINcontextnamespace.Thisworksandis adequateforsmallerprogramswrittenbyjustoneprogrammer.Whenwritinglargersystems,allthemethodsforoneclassshouldbe surroundedbycontextstatementstoprovidebetterisolationofparametervariablesusedandtocreateanisolatedlocationfor potentialclassvariables. Classvariablescouldbeusedinthisexampleasacontainerforlistsofobjects,countersorotherinformationspecifictoaclassbut nottoaspecificobject.Thefollowingcodesegmentrewritestheexamplefromaboveinthisfashion. Eachcontext/namespacecouldgointoanextrafilewiththesamenameastheclasscontained.Classcreation,startupcodeandthe maincontrolcodeisinafileM A I N . l s p :
;f i l eM A I N . l s p-d e c l a r ea l lc l a s s e su s e di nM A I N ( n e wC l a s s' R e c t a n g l e )

( n e wC l a s s' C i r c l e ) ;s t a r tu pc o d e ( l o a d" R e c t a n g l e . l s p " ) ( l o a d" C i r c l e . l s p " ) ;m a i nc o n t r o lc o d e ;e n do ff i l e

Eachclassisinaseparatefile:
;f i l eR e c t a n g l e . l s p-c l a s sm e t h o d sf o rr e c t a n g l e s ( c o n t e x tR e c t a n g l e ) ( d e f i n e( R e c t a n g l e : a r e a ) ( m u l( s e l f3 )( s e l f4 ) ) ) ( d e f i n e( R e c t a n g l e : m o v ed xd y ) ( i n c( s e l f1 )d x ) ( i n c( s e l f2 )d y ) ) ;e n do ff i l e

AndtheC i r c l e classfilefollows:
;f i l eC i r c l e . l s p-c l a s sm e t h o d sf o rc i r c l e s ( c o n t e x tC i r c l e ) ( d e f i n e( C i r c l e : a r e a ) ( m u l( p o w( s e l f3 )2 )( a c o s0 )2 ) ) ( d e f i n e( C i r c l e : m o v ed xd y ) ( i n c( s e l f1 )d x ) ( i n c( s e l f2 )d y ) ) ;e n do ff i l e

Allsetsofclassfunctionsarenowlexicallyseparatedfromeachother. ()

19.Concurrentprocessinganddistributedcomputing
newLISPhashighlevelAPIstocontrolmultipleprocessesonthesameCPUordistributedontodifferentcomputernodesona TCP/IPnetwork.

CilkAPI
newLISPimplementsaCilklikeAPItolaunchandcontrolconcurrentprocesses.TheAPIcantakeadvantageofmulticore computerarchitectures.Onlythreefunctions,spawn,syncandabort,arenecessarytostartmultipleprocessesandcollecttheresults inasynchronizedfashion.TheunderlyingoperatingsystemdistributesprocessesontodifferentcoresinsidetheCPUorexecutes themonthesamecoreinparalleliftherearenotenoughcorespresent.NotethatnewLISPonlyimplementstheAPIoptimized schedulingofspawnedproceduresisnotperformedasinCilk.Functionsarestartedintheordertheyappearins p a w n statements andaredistributedandscheduledontodifferentcoresintheCPUbytheoperatingsystem. Whenmultiplecoresarepresent,thiscanincreaseoverallprocessingspeedbyevaluatingfunctionsinparallel.Butevenwhen runningonsinglecoreCPUs,theCilkAPImakesconcurrentprocessingmucheasierfortheprogrammerandmayspeedup

processingifsubtasksincludewaitingforI/Oorsleeping. Sinceversion10.1sendandreceivemessagefunctionsareavailableforcommunicationsbetweenparentandchildprocesses.The functionscanbeusedinblockingandnonblockingcommunicationsandcantransferanykindofnewLISPdataorexpressions. Transmittedexpressionscanbeevaluatedintherecipientsenvironment. Internally,newLISPusesthelowerlevelfork,waitpid,destroy,andsharefunctionalitiestocontrolprocessesandsynchronizethe passingofcomputedresultsviaasharedmemoryinterface. OnlyonMacOSXandotherUnixeswilltheCilkAPIparallelizetasks.OnWin32,theAPIpartlysimulatesthebehavioronUnix butexecutestaskssequentially.Thisway,codecanbewrittenthatrunsonallplatforms.

Distributednetworkcomputing
Withonlyonefunction,neteval,newLISPimplementsdistributedcomputing.Usingn e t e v a l ,differenttaskscanbemappedand evaluatedondifferentnodesrunningonaTCP/IPnetworkorlocaldomainUnixsocketsnetworkwhenrunningonthesame computer.n e t e v a l doesallthehousekeepingrequiredtoconnecttoremotenodes,transferfunctionstoexecute,andcollectthe results.n e t e v a l canalsouseacallbackfunctiontofurtherstructureconsolidationofincomingresultsfromremotenodes. Thefunctionsreadfile,writefile,appendfileanddeletefileallcantakeURLsinsteadofpathfilenames.ServersidenewLISP runningindemonmodeoranotherHTTPserverlikeApache,receivestandardHTTPrequestsandtranslatethemintothe correspondingactionsonfiles. ()

20.JSON,XML,SXML,andXMLRPC
JSONsupport JSONencodeddatacanbeparsedintoSexpressionsusingthejsonparsefunction.ErrorinformationforfailedJSONtranslations canberetrievedusingjsonerror. ForadescriptionoftheJSONformat(JavaScriptObjectNotation)consultjson.org.ExamplesforcorrectformattedJSONtextcan beseenatjson.org/examples.html. ToretrievedatainnestedlistsresultingfromJSONtranslation,usetheassoc,lookupandreffunctions. SeethedescriptionofjsonparseforacompleteexampleofparsingandprocessingJSONdata. XMLsupport newLISP'sbuiltinsupportforXMLencodeddataordocumentscomprisesthreefunctions:xmlparse,xmltypetags,andxml error. UsethexmlparsefunctiontoparseXMLencodedstrings.Whenx m l p a r s e encountersanerror,n i l isreturned.Todiagnose syntaxerrorscausedbyincorrectlyformattedXML,usethefunctionxmlerror.Thexmltypetagsfunctioncanbeusedtocontrolor suppresstheappearanceofXMLtypetags.ThesetagsclassifyXMLintooneoffourcategories:text,rawstringdata,comments, andelementdata. XMLsource:
< ? x m lv e r s i o n = " 1 . 0 " ? > < D A T A B A S En a m e = " e x a m p l e . x m l " > < ! T h i si sad a t a b a s eo ff r u i t s > < F R U I T > < N A M E > a p p l e < / N A M E >

< C O L O R > r e d < / C O L O R > < P R I C E > 0 . 8 0 < / P R I C E > < / F R U I T > < / D A T A B A S E >

Parsingwithoutoptions:
( x m l p a r s e( r e a d f i l e" e x a m p l e . x m l " ) ) ( ( " E L E M E N T "" D A T A B A S E "( ( " n a m e "" e x a m p l e . x m l " ) )( ( " T E X T "" \ r \ n " ) ( " C O M M E N T "" T h i si sad a t a b a s eo ff r u i t s " ) ( " T E X T "" \ r \ n " ) ( " E L E M E N T "" F R U I T "( )( ( " T E X T "" \ r \ n \ t " ) ( " E L E M E N T "" N A M E "( )( ( " T E X T "" a p p l e " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" C O L O R "( )( ( " T E X T "" r e d " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" P R I C E "( )( ( " T E X T "" 0 . 8 0 " ) ) ) ( " T E X T "" \ r \ n \ t " ) ) ) ( " T E X T "" \ r \ n " ) ) ) )

SXMLcanbegenerateddirectlyfromXMLusingxmltypetagsandthespecialoptionparametersofthexmlparsefunction: SXMLgenerationusingalloptions:
( x m l t y p e t a g sn i ln i ln i ln i l ) ( x m l p a r s e( r e a d f i l e" e x a m p l e . x m l " )( +12481 6 ) ) ( ( D A T A B A S E( @( n a m e" e x a m p l e . x m l " ) ) ( F R U I T( N A M E" a p p l e " ) ( C O L O R" r e d " ) ( P R I C E" 0 . 8 0 " ) ) ) )

SXMLisXMLreformattedasnewLISPSexpressions.The@ (atsymbol)denotesanXMLattributespecification. ToretrievedatainnestedlistsresultingfromSXMLtranslation,usetheassoc,lookupandreffunctions. Seexmlparseinthereferencesectionofthemanualfordetailsonparsingandoptionnumbers,aswellasforalongerexample. XMLRPC TheremoteprocedurecallingprotocolXMLRPCusesHTTPpostrequestsasatransportandXMLfortheencodingofmethod names,parameters,andparametertypes.XMLRPCclientlibrariesandservershavebeenimplementedformostpopularcompiled andscriptinglanguages. FormoreinformationaboutXML,visitwww.xmlrpc.com. XMLRPCclientsandserversareeasytowriteusingnewLISP'sbuiltinnetworkandXMLsupport.AstatelessXMLRPCserver implementedasaCGIservicecanbefoundinthefilee x a m p l e s / x m l r p c . c g i .Thisscriptcanbeusedtogetherwithawebserver, likeApache.ThisXMLRPCservicescriptimplementsthefollowingmethods: method
s y s t e m . l i s t M e t h o d s s y s t e m . m e t h o d H e l p s y s t e m . m e t h o d S i g n a t u r e n e w L I S P . e v a l S t r i n g

description Returnsalistofallmethodnames Returnshelpforaspecificmethod Returnsalistofreturn/callingsignaturesforaspecificmethod EvaluatesaBase64newLISPexpressionstring

ThefirstthreemethodsarediscoverymethodsimplementedbymostXMLRPCservers.ThelastoneisspecifictothenewLISP XMLRPCserverscriptandimplementsremoteevaluationofaBase64encodedstringofnewLISPsourcecode.newLISP's base64encandbase64decfunctionscanbeusedtoencodeanddecodeBase64encodedinformation.

Inthem o d u l e s directoryofthesourcedistribution,thefilex m l r p c c l i e n t . l s p implementsaspecificclientinterfaceforallofthe abovemethods.


( l o a d" x m l r p c c l i e n t . l s p " ) ;l o a dX M L R P Cc l i e n tr o u t i n e s ( X M L R P C : n e w L I S P . e v a l S t r i n g " h t t p : / / l o c a l h o s t : 8 0 8 0 / x m l r p c . c g i " " ( +34 ) " ) " 7 "

Inasimilarfashion,standards y s t e m . x x x callscanbeissued. Allfunctionsreturneitheraresultifsuccessful,orn i l ifarequestfails.Incaseoffailure,theexpression( X M L R P C : e r r o r ) canbe evaluatedtoreturnanerrormessage. Formoreinformation,pleaseconsulttheheaderofthefilem o d u l e s / x m l r p c c l i e n t . l s p . ()

21.Customization,localization,andUTF8
Customizingfunctionnames
AllbuiltinprimitivesinnewLISPcanbeeasilyrenamed:
( c o n s t a n t' p l u s+ )

Now,p l u s isfunctionallyequivalentto+ andrunsatthesamespeed. Theconstantfunction,ratherthanthes e t function,mustbeusedtorenamebuiltinprimitivesymbols.Bydefault,allbuiltin functionsymbolsareprotectedagainstaccidentaloverwriting. Itispossibletoredefineallintegerarithmeticoperatorstotheirfloatingpointequivalents:


( c o n s t a n t' +a d d ) ( c o n s t a n t' -s u b ) ( c o n s t a n t' *m u l ) ( c o n s t a n t' /d i v )

Alloperationsusing+ ,,* ,and/ arenowperformedasfloatingpointoperations. Usingthesamemechanism,thenamesofbuiltinfunctionscanbetranslatedintolanguagesotherthanEnglish:


( c o n s t a n t' w u r z e ls q r t ) ;G e r m a nf o r' s q u a r e r o o t '

;m a k et h en e ws y m b o lg l o b a la tt h es a m et i m e ( c o n s t a n t( g l o b a l' i m p r i m e )p r i n t ) ;S p a n i s hf o r' p r i n t '

Thenewsymbolcanbemadeglobalatthesametimeusingglobal.

Switchingthelocale
newLISPcanswitchlocalesbasedontheplatformandoperatingsystem.Onstartup,nonUTF8enablednewLISPattemptstoset theISOCstandarddefaultPOSIXlocale,availableformostplatformsandlocales.OnUTF8enablednewLISPthedefaultlocale fortheplatformisset.Thesetlocalefunctioncanalsobeusedtoswitchtothedefaultlocale:
( s e t l o c a l e" " )

Thisswitchestothedefaultlocaleusedonyourplatform/operatingsystemandensurescharacterhandling(e.g.,uppercase)works

correctly. ManyUnixsystemshaveavarietyoflocalesavailable.TofindoutwhichonesareavailableonaparticularLinux/Unix/BSD system,executethefollowingcommandinasystemshell:


l o c a l ea

Thiscommandprintsalistofallthelocalesavailableonyoursystem.Anyofthesemaybeusedasargumentstosetlocale:
( s e t l o c a l e" e s _ U S " )

ThiswouldswitchtoaU.S.Spanishlocale.AccentsorothercharactersusedinaU.S.Spanishenvironmentwouldbecorrectly converted. Seethemanualdescriptionformoredetailsontheusageofsetlocale.

Decimalpointanddecimalcomma
Manycountriesuseacommainsteadofaperiodasadecimalseparatorinnumbers.newLISPcorrectlyparsesnumbersdepending onthelocaleset:
;s w i t c ht oG e r m a nl o c a l eo naL i n u x o rO S Xs y s t e m ( s e t l o c a l e" d e _ D E " )( " d e _ D E "" , " ) ;n e w L I S Ps o u r c ea n do u t p u tu s ead e c i m a lc o m m a ( d i v1 , 23 ) 0 , 4

ThedefaultPOSIXClocale,whichissetwhennewLISPstartsup,usesaperiodasadecimalseparator. Thefollowingcountriesuseaperiodasadecimalseparator: Australia,Botswana,Canada(Englishspeaking),China,CostaRica,DominicanRepublic,ElSalvador,Guatemala, Honduras,HongKong,India,Ireland,Israel,Japan,Korea(bothNorthandSouth),Malaysia,Mexico,Nicaragua, NewZealand,Panama,Philippines,PuertoRico,SaudiArabia,Singapore,Switzerland,Thailand,UnitedKingdom, andUnitedStates. Thefollowingcountriesuseacommaasadecimalseparator: Albania,Andorra,Argentina,Austria,Belarus,Belgium,Bolivia,Brazil,Bulgaria,Canada(Frenchspeaking),Croatia, Cuba,Chile,Colombia,CzechRepublic,Denmark,Ecuador,Estonia,Faroes,Finland,France,Germany,Greece, Greenland,Hungary,Indonesia,Iceland,Italy,Latvia,Lithuania,Luxembourg,Macedonia,Moldova,Netherlands, Norway,Paraguay,Peru,Poland,Portugal,Romania,Russia,Serbia,Slovakia,Slovenia,Spain,SouthAfrica, Sweden,Ukraine,Uruguay,Venezuela,andZimbabwe.

UnicodeandUTF8encoding
NotethatformanyEuropeanlanguages,thesetlocalemechanismissufficienttodisplaynonASCIIcharactersets,aslongaseach characterispresentedasonebyteinternally.UTF8encodingisonlynecessaryformultibytecharactersetsasdescribedinthis chapter. newLISPcanbecompiledasaUTF8enabledapplication.UTF8isamultibyteencodingoftheinternationalUnicodecharacter set.AUTF8enablednewLISPrunningonanoperatingsystemwithUTF8enabledcanhandleanycharacteroftheinstalled locale. ThefollowingstepsmakeUTF8workwithnewLISPonaspecificoperatingsystemandplatform:
( 1 ) Useoneofthemakefilesendinginu t f 8 tocompilenewLISPasaUTF8application.IfnoUTF8makefileisavailablefor

yourplatform,thenormalmakefileforyouroperatingsystemcontainsinstructionsonhowtochangeitforUTF8. TheMacOSXbinaryinstallercontainsaUTF8enabledversionbydefault.
( 2 ) EnabletheUTF8localeonyouroperatingsystem.CheckandsetaUTF8localeonUnixandUnixlikeOSesbyusingthe l o c a l e commandorthes e t l o c a l e functionwithinnewLISP.OnLinux,thelocalecanbechangedbysettingtheappropriate

environmentvariable.Thefollowingexampleusesb a s h tosettheU.S.locale:
e x p o r tL C _ C T Y P E = e n _ U S . U T F 8 ( 3 ) TheUTF8enablednewLISPautomaticallyswitchestothelocalefoundontheoperatingsystem.Makesurethecommand

shellisUTF8enabled.TheU.S.versionofWinXP'sn o t e p a d . e x e candisplayUnicodeUTF8encodedcharacters,butthe commandshellcannot.OnLinuxandotherUnixes,theXtermshellcanbeusedwhenstartedasfollows:


L C _ C T Y P E = e n _ U S . U T F 8x t e r m

ThefollowingprocedurecannowbeusedtocheckforUTF8support.AfterstartingnewLISP,type:
( p r i n t l n( c h a r9 3 7 ) ) ;d i s p l a y sG r e e ku p p e r c a s eo m e g a ( p r i n t l n( l o w e r c a s e( c h a r9 3 7 ) ) ) ;d i s p l a y sl o w e r c a s eo m e g a

Whiletheuppercaseomega()lookslikeabigOontwotinylegs,thelowercaseomega()hasashapesimilartoasmallw inthe Latinalphabet. Note:Onlytheoutputofp r i n t l n willbedisplayedasacharacterp r i n t l n 'sreturnvaluewillappearontheconsoleasamultibyte ASCIIcharacter. WhenUTF8enablednewLISPisusedonanonUTF8enableddisplay,boththeoutputandthereturnvaluewillbetwo characters.Thesearethetwobytesnecessarytoencodetheomegacharacter.

FunctionsworkingonUTF8characters
WhenUTF8enablednewLISPisused,thefollowingstringfunctionsworkononeormultibytecharactersratherthanone8bit byteboundaries: function char chop date dostring explode first last lowercase nth pop push rest select titlecase trim uppercase description translatesbetweencharactersandASCII/Unicode chopscharactersfromtheendofastring convertsdatenumbertostring(whenusedwiththethirdargument) evaluatesonceforeachcharacterinastring transformsastringintoalistofcharacters getsfirstelementinalist(car,head)orstring returnsthelastelementofalistorstring convertsastringtolowercasecharacters getsthenthelementofalistorstring deletesanelementfromalistorstring insertsanewelementinalistorstring getsallbutthefirstelementofalist(cdr,tail)orstring selectsandpermuteselementsfromalistorstring convertsthefirstcharacterofastringtouppercase trimsastringfrombothsides convertsastringtouppercasecharacters

Allotherstringfunctionsworkon8bitbytes.Whenpositionsarereturned,asinfindorregex,theyaresingle8bitbytepositions ratherthancharacterpositionswhichmaybemultibyte.Thegetcharandslicefunctionsdonottakemultibytecharacteroffsets, butsinglebyteoffsets,eveninUTF8enabledversionsofnewLISP.Thereversefunctionreversesabytevector,notacharacter vector.ThelastthreefunctionscanstillbeusedtomanipulatebinarynontextualdataintheUTF8enabledversionofnewLISP. ToenableUTF8inPerlCompatibleRegularExpressions(PCRE)usedbydirectory,find,member,parse,regex,regexcomp andreplacesettheoptionnumberaccordingly(2048).Notethatoffsetandlengthsinregexresultsarealwaysinsinglebyte counts.Seetheregexdocumentationfordetails. UseexplodetoobtainanarrayofUTF8charactersandtomanipulatecharactersratherthanbyteswhenaUTF8enabledfunction isunavailable:


( j o i n( r e v e r s e( e x p l o d es t r ) ) ) ;r e v e r s eU T F 8c h a r a c t e r s

Theabovestringfunctions(oftenusedtomanipulatenontextualbinarydata)nowworkoncharacter,ratherthanbyte,boundaries, socaremustbeexercisedwhenusingtheUTF8enabledversion.Thesizeofthefirst127ASCIIcharactersalongwiththe charactersinpopularcodepagessuchasISO8859isonebytelong.Whenworkingexclusivelywithinthesecodepages,UTF 8enablednewLISPisnotrequired.Thesetlocalefunctionaloneissufficientforlocalizedbehavior.

FunctionsonlyavailableonUTF8enabledversions
function unicode utf8 utf8len description convertsUTF8orASCIIstringsintoUSC4Unicode convertsUCS4UnicodestringstoUTF8 returnsthenumberofUTF8charactersinastring

Thefirsttwofunctionsarerarelyusedinpractice,asmostUnicodetextfilesarealreadyUTF8encoded(ratherthanUCS4,which usesfourbyteintegercharacters).Unicodecanbedisplayeddirectlywhenusingthe" % l s " formatspecifier. ForfurtherdetailsonUTF8andUnicode,consultUTF8andUnicodeFAQforUnix/LinuxbyMarkusKuhn. ()

22.Commasinparameterlists
Someoftheexampleprogramscontainfunctionsthatuseacommatoseparatetheparametersintotwogroups.Thisisnotaspecial syntaxofnewLISP,butratheravisualtrick.Thecommaisasymboljustlikeanyothersymbol.Theparametersafterthecommaare notrequiredwhencallingthefunctiontheysimplydeclarelocalvariablesinaconvenientway.ThisispossibleinnewLISP becauseparametervariablesinlambdaexpressionsarelocalandargumentsareoptional:
( d e f i n e( m y f u n cabc,xyz ) ( s e t' x ) ( ) )

Whencallingthisfunction,onlya ,b ,andc areusedasparameters.Theothers(thecommasymbol,x ,y ,andz )areinitializedto n i l andarelocaltothefunction.Afterexecution,thefunction'scontentsareforgottenandtheenvironment'ssymbolsarerestoredto theirpreviousvalues. Forotherwaysofdeclaringandinitializinglocalvariables,seelet,letexandletn. ()

()

newLISPFunctionReference

1.Syntaxofsymbolvariablesandnumbers
SourcecodeinnewLISPisparsedaccordingtotherulesoutlinedhere.Whenindoubt,verifythebehaviorofnewLISP'sinternal parserbycallingparsewithoutoptionalarguments.

Symbolsforvariablenames
Thefollowingrulesapplytothenamingofsymbolsusedasvariablesorfunctions: 1. Variablesymbolsshouldnotstartwithanyofthefollowingcharacters:
#;"'(){}.,0123456789

2. Variablesymbolsstartingwitha+ orcannothaveanumberasthesecondcharacter. 3. Anycharacterisallowedinsideavariablename,exceptfor: "'():, andthespacecharacter.Thesemarktheendofavariablesymbol. 4. Asymbolnamestartingwith[ (leftsquarebracket)andendingwith] (rightsquarebracket)maycontainanycharacter excepttherightsquarebracket. 5. Asymbolnamestartingwith$ (dollarsign)isglobal.ThereareseveralofthesesymbolsalreadybuiltintonewLISPandset andchangedinternally.Thistypeofglobalsymbolcanalsobecreatedbytheuser. AllofthefollowingsymbolsarelegalvariablenamesinnewLISP:
m y v a r A n a m e X 3 4 z z [ *75( ) } ; ] * 1 1 1 *

SometimesitisusefultocreatehashlikelookupdictionarieswithkeyscontainingcharactersthatareillegalinnewLISPvariables. Thefunctionssymandcontextcanbeusedtocreatesymbolscontainingthesecharacters:
( s e t( s y m" ( # : L * " )4 5 6 ) 4 5 6;t h es y m b o l' ( # : L * ' ( e v a l( s y m" ( # : L * " ) ) 4 5 6 ( s e t( s y m1 )1 2 3 ) 1 2 3 ( e v a l( s y m1 ) ) 1 2 3 1 1 ( +12 ) 3

Thelastexamplecreatesthesymbol1 containingthevalue1 2 3 .AlsonotethatcreatingsuchasymboldoesnotalternewLISP's normaloperations,since1 isstillparsedasthenumberone.

Numbers
newLISPrecognizesthefollowingnumberformats: Integersareoneormoredigitslong,optionallyprecededbya+ orsign.Anyothercharactermarkstheendoftheintegerormay bepartofthesequenceifparsedasafloat(seefloatsyntaxbelow).
1 2 3 + 4 5 6 7 9 9 9

Bigintegerscanbeofunlimitedprecisionandareprocesseddifferentlyfromnormal64biintegersinternally.
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0;w i l la u t o m a t i c a l l yb ec o n v e r t e dt ob i gi n t 1 2 3 L ;a p p e n d e dLf o r c e sc o n v e r s i o n 0 L

whenparsingthecommandlineorprogrammingsource,newLISPwillrecognise,integersbiggerthan64bitandconvertthetobig integers.SmallernumberscanbeforcedtobigintegerformatbyappendingtheletterL. Hexadecimalsstartwitha0 x (or0 X ),followedbyanycombinationofthehexadecimaldigits:0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F .Any othercharacterendsthehexadecimalnumber.


0 x F F 2 5 5 0 x 1 0 a b 4 2 6 7 0 X 1 0 C C 4 3 0 0

Binariesstartwitha0 b (or0 B ),followedbyupto641'sor0s.Anyothercharacterendsthebinarynumber.


0 b 1 0 1 0 1 0 4 2

Octalsstartwithanoptional+ (plus)or(minus)signanda0 (zero),followedbyanycombinationoftheoctaldigits:0 1 2 3 4 5 6 7 . Anyothercharacterendstheoctalnumber.


0 1 2 0 1 0 0 7 7 0 7 7 1 0 8 6 3 6 3

Floatingpointnumberscanstartwithanoptional+ (plus)or(minus)sign,buttheycannotbefollowedbya0 (zero)thiswould makethemoctalnumbersinsteadoffloatingpoints.Asingle. (decimalpoint)canappearanywherewithinafloatingpointnumber, includingatthebeginning.


1 . 2 3 1 . 2 3 + 2 . 3 4 5 6 . 5 0 6 1 . 2 3 1 . 2 3 2 . 3 4 5 6 0 . 5 0 6

Asdescribedbelow,scientificnotationstartswithafloatingpointnumbercalledthesignificand(ormantissa),followedbythe lettere orE andanintegerexponent.


1 . 2 3 e 3 1 . 2 3 E 3 + 2 . 3 4 e 2 . 5 0 6 E 3 1 2 3 0 1 2 3 0 0 . 0 2 3 4 5 0 6

()

2.Datatypesandnamesinthereference

Todescribethetypesandnamesofafunction'sparameters,thefollowingnamingconventionisusedthroughoutthereference section: syntax:(formatstrformatexpdata1[expdatai...]) Argumentsarerepresentedbysymbolsformedbytheargument'stypeandname,separatedbya(hyphen).Here,strformat(a string)andexpdata1(anexpression)arenamed"format"and"data1",respectively. Argumentsenclosedinbrackets[ and] areoptional.Whenargumentsareseparatedbyavertical| thenoneofthemmustbe chosen.

array
Anarray(constructedwiththearrayfunction).

body
Oneormoreexpressionsforevaluation.Theexpressionsareevaluatedsequentiallyifthereismorethanone.
17 . 8 n i l ( +34 ) " H i "( +ab ) ( p r i n tr e s u l t ) ( d o t h i s ) ( d o t h a t )1 2 3

bool
t r u e ,n i l ,oranexpressionevaluatingtooneofthesetwo. t r u e ,n i l ,( < =X1 0 )

context
Anexpressionevaluatingtoacontext(namespace)oravariablesymbolholdingacontext.
M y C o n t e x t ,a C t x ,T h e C T X

exp
Anydatatypedescribedinthischapter.

func
Asymboloranexpressionevaluatingtoanoperatorsymbolorlambdaexpression.
+ ,a d d ,( f i r s t' ( a d ds u b ) ) ,( l a m b d a( x )( +xx ) )

int
Anintegeroranexpressionevaluatingtoaninteger.Generally,ifafloatingpointnumberisusedwhenanintisexpected,thevalue istruncatedtoaninteger.
1 2 3 ,5 ,( *X5 )

list
Alistofelements(anytype)oranexpressionevaluatingtoalist.
( abc" h e l l o "( +34 ) )

num
Aninteger,afloatingpointnumber,oranexpressionevaluatingtooneofthesetwo.Ifanintegerispassed,itisconvertedtoa floatingpointnumber.
1 . 2 3 4 ,( d i v1 03 ) ,( s i n1 )

matrix
Alistinwhicheachrowelementisitselfalistoranarrayinwhicheachrowelementisitselfanarray.Allelementlistsorarrays (rows)areofthesamelength.Anydatatypecanbeelementofamatrix,butwhenusingspecificmatrixoperationslikedet, multiply,orinvert,allnumbersmustbefloatsorintegers. Thedimensionsofamatrixaredefinedbyindicatingthenumberofrowsandthenumberofcolumnelementsperrow.Functions workingonmatricesignoresuperfluouscolumnsinarow.Formissingrowelements,0 . 0 isassumedbythefunctionsdet,multiply, andinvert,whiletransposeassumesn i l .Specialrulesapplyfortransposewhenawholerowisnotalistoranarray,butsomeother datatype.
( ( 1 2 3 4 ) ( 5 6 7 8 ) ( 91 01 11 2 ) )

;3r o w s4c o l u m n s

( ( 12 )( 34 )( 56 ) ) ;3r o w s2c o l u m n s

place
Aplacereferencedbyasymboloraplacedefinedinalist,arrayorstringbyindexingwithnthorimplicitindexingoraplace referencedbyfunctionslikefirst,last,assocorlookup.

str
Astringoranexpressionthatevaluatestoastring.
" H e l l o " ,( a p p e n df i r s t n a m e "M i l l e r " )

Specialcharacterscanbeincludedinquotedstringsbyplacinga\ (backslash)beforethecharacterordigitstoescapethem: character description \ " foradoublequoteinsideaquotedstring \ n thelinefeedcharacter(ASCII10) \ r thecarriagereturncharacter(ASCII13)


\ b \ t \ f \ n n n \ x n n \ u n n n n \ \

forabackspaceBScharacter(ASCII8) foraTABcharacter(ASCII9) foraformfeedFFcharacter(ASCII12) adecimalASCIIcodewherennnisbetween000and255 ahexadecimalcodewherennisbetween00andFF aunicodecharacterencodedinthefourn n n n hexadecimaldigits.Whenreadingaquotedstring,newLISPwill translatethistoaUTF8characterintheUTF8enabledversionsofnewLISP. thebackslashcharacteritself

Decimalsstartwithadigit.Hexadecimalsstartwithx :
" \ 0 6 5 \ 0 6 6 \ 0 6 7 "" A B C " " \ x 4 1 \ x 4 2 \ x 4 3 "" A B C "

Insteadofa" (doublequote),a{ (leftcurlybracket)and} (rightcurlybracket)canbeusedtodelimitstrings.Thisisusefulwhen

quotationmarksneedtooccurinsidestrings.Quotingwiththecurlybracketssuppressesthebackslashescapeeffectforspecial characters.Balancednestedcurlybracketsmaybeusedwithinastring.Thisaidsinwritingregularexpressionsorshortsectionsof HTML.


( p r i n t" < Ah r e f = \ " h t t p : / / m y s i t e . c o m \ " > ");t h ec r y p t i cw a y ( p r i n t{ < Ah r e f = " h t t p : / / m y s i t e . c o m " > }) ;p a t hn a m e so nM SW i n d o w s ( s e t' p a t h" C : \ \ M y D i r \ \ e x a m p l e . l s p " ) ;n oe s c a p i n gw h e nu s i n gb r a c e s ( s e t' p a t h{ C : \ M y D i r \ e x a m p l e . l s p } ) ;o nM SW i n d o w st h ef o r w a r ds l a s hc a nb eu s e di np a t hn a m e s ( s e t' p a t h" C : / M y D i r / e x a m p l e . l s p " ) ;i n n e rb r a c e sa r eb a l a n c e d ( r e g e x{ a b c { 1 , 2 } }l i n e ) ( p r i n t[ t e x t ] t h i sc o u l db e av e r yl o n g( >2 0 4 8c h a r a c t e r s )t e x t , i . e .H T M L . [ / t e x t ] ) ;t h er e a d a b l ew a y

Thetags[ t e x t ] and[ / t e x t ] canbeusedtodelimitlongstringsandsuppressescapecharactertranslation.Thisisusefulfor delimitinglongHTMLpassagesinCGIfileswritteninnewLISPorforsituationswherecharactertranslationshouldbecompletely suppressed.Alwaysusethe[ t e x t ] tagsforstringslongerthan2048characters.

sym
Asymbolorexpressionevaluatingtoasymbol.
' x y z ,( f i r s t' ( +-/ ) ) ,' * ,' -,s o m e S y m b o l ,

Mostofthecontextsymbolsinthismanualstartwithanuppercaselettertodistinguishthemfromothersymbols.

symcontext
Asymbol,anexistingcontext,oranexpressionevaluatingtoasymbolfromwhichacontextwillbecreated.Ifacontextdoesnot alreadyexist,manyfunctionsimplicitlycreatethem(e.g.,bayestrain,context,evalstring,load,sym,andxmlparse).Thecontext mustbespecifiedwhenthesefunctionsareusedonanexistingcontext.Evenifacontextalreadyexists,somefunctionsmay continuetotakequotedsymbols(e.g.,context).Forotherfunctions,suchascontext?,thedistinctioniscritical.

()

3.Functionsingroups
Somefunctionsappearinmorethanonegroup.

Listprocessing,flowcontrol,andintegerarithmetic
+,,*,/,% ++ integerarithmetic incrementintegernumbers

<,>,= <=,>=,!= : and append apply args assoc begin bigint bind case catch chop clean cond cons constant count curry define definemacro defnew difference doargs dolist dostring dotimes dotree dountil dowhile dup endswith eval exists expand explode extend first filter find flat fn for forall

decrementintegernumbers comparesanydatatype:less,greater,equal comparesanydatatype:lessequal,greaterequal,notequal constructsacontextsymbolandappliesittoanobject logicala n d appendslists,arraysorstringstoformanewlist,arrayorstring appliesafunctionorprimitivetoalistofarguments retrievestheargumentlistofafunctionormacroexpression searchesforkeywordassociationsinalist beginsablockoffunctions convertanumbertobigintegerformat bindsvariableassociationsinalist branchesdependingoncontentsofcontrolvariable evaluatesanexpression,possiblycatchingerrors chopselementsfromtheendofalist cleanselementsfromalist branchesconditionallytoexpressions prependsanelementtoalist,makinganewlist definesaconstantsymbol countselementsofonelistthatoccurinanotherlist transformsafunctionf(x,y)intoafunctionfx(y) definesanewfunctionorlambdaexpression definesamacroorlambdamacroexpression copiesasymboltoadifferentcontext(namespace) returnsthedifferencebetweentwolists iteratesthroughtheargumentsofafunction evaluatesonceforeachelementinalist evaluatesonceforeachcharacterinastring evaluatesonceforeachnumberinarange iteratesthroughthesymbolsofacontext repeatsevaluationofanexpressionuntiltheconditionismet repeatsevaluationofanexpressionwhiletheconditionistrue duplicatesalistorstringaspecifiednumberoftimes checkstheendofastringorlistagainstakeyofthesametype evaluatesanexpression checksfortheexistenceofaconditioninalist replacesasymbolinanestedlist explodesalistorstring extendsalistorstring getsthefirstelementofalistorstring filtersalist searchesforanelementinalistorstring returnstheflattenedlist definesanewfunctionorlambdaexpression evaluatesonceforeachnumberinarange checksifallelementsinalistmeetacondition

if index intersect lambda last length let letex letn list local lookup map match member not nth or pop popassoc push quote ref refall rest replace reverse rotate select self set setfsetq setref setrefall silent slice sort startswith swap unify unique union unless until when while

evaluatesanexpressionconditionally filterselementsfromalistandreturnstheirindices returnstheintersectionoftwolists definesanewfunctionorlambdaexpression returnsthelastelementofalistorstring calculatesthelengthofalistorstring declaresandinitializeslocalvariables expandslocalvariablesintoanexpression,thenevaluates initializeslocalvariablesincrementally,likenestedlets makesalist declareslocalvariables looksupmembersinanassociationlist mapsafunctionovermembersofalist,collectingtheresults matchespatternsagainstlistsformatchingagainststrings,seefindandregex findsamemberofalistorstring logicaln o t getsthenthelementofalistorstring logicalo r deletesandreturnsanelementfromalistorstring removesanassociationfromanassociationlist insertsanewelementintoalistorstring quotesanexpression returnsthepositionofanelementinsideanestedlist returnsalistofindexvectorsofelementsinsideanestedlist returnsallbutthefirstelementofalistorstring replaceselementsinsidealistorstring reversesalistorstring rotatesalistorstring selectsandpermuteselementsfromalistorstring AccessesthetargetobjectinsideaFOOPmethod setsthebindingorcontentsofasymbol setscontentsofasymbolorlist,arrayorstringreference searchesforanelementinanestedlistandreplacesit searchesforanelementinanestedlistandreplacesallinstances workslikebeginbutsuppressesconsoleoutputofthereturnvalue extractsasublistorsubstring sortsthemembersofalist checksthebeginningofastringorlistagainstakeyofthesametype swapstwoelementsinsidealistorstring unifiestwoexpressions returnsalistwithoutduplicates returnsauniquelistofelementsfoundintwoormorelists. evaluatesanexpressionconditionally repeatsevaluationofanexpressionuntiltheconditionismet evaluatesablockofstatementsconditionally repeatsevaluationofanexpressionwhiletheconditionistrue

Stringandconversionfunctions
address bigint bits char chop dostring dup endswith encrypt evalstring explode extend find findall first float format getchar getfloat getint getlong getstring int join last lowercase member name nth pack parse pop push regex regexcomp replace rest reverse rotate select setfsetq slice source getsthememoryaddressofanumberorstring convertanumbertobigintegerformat translatesanumberintobinaryrepresentation translatesbetweencharactersandASCIIcodes chopsoffcharactersfromtheendofastring evaluatesonceforeachcharacterinastring duplicatesalistorstringaspecifiednumberoftimes checkstheendofastringorlistagainstakeyofthesametype doesaonetimepadencryptionanddecryptionofastring compiles,thenevaluatesastring transformsastringintoalistofcharacters extendsalistorstring searchesforanelementinalistorstring returnsalistofallpatternmatchesfoundinstring getsthefirstelementinalistorstring translatesastringorintegerintoafloatingpointnumber formatsnumbersandstringsasintheClanguage getsacharacterfromamemoryaddress getsadoublefloatfromamemoryaddress getsa32bitintegerfromamemoryaddress getsalong64bitintegerfromamemoryaddress getsastringfromamemoryaddress translatesastringorfloatintoaninteger joinsalistofstrings returnsthelastelementofalistorstring convertsastringtolowercasecharacters findsalistorstringmember returnsthenameofasymboloritscontextasastring getsthenthelementinalistorstring packsnewLISPexpressionsintoabinarystructure breaksastringintotokens popsfromastring pushesontoastring performsaPerlcompatibleregularexpressionsearch precompilesaregularexpressionpattern replaceselementsinalistorstring getsallbutthefirstelementofalistorstring reversesalistorstring rotatesalistorstring selectsandpermuteselementsfromalistorstring setscontentsofastringreference extractsasubstringorsublist returnsthesourcerequiredtobindasymbolasastring

startswith string sym titlecase trim unicode utf8 utf8len unpack uppercase

checksthestartofthestringorlistagainstakeystringorlist transformsanythingintoastring translatesastringintoasymbol convertsthefirstcharacterofastringtouppercase trimsastringononeorbothsides convertsASCIIorUTF8toUCS4Unicode convertsUCS4UnicodetoUTF8 returnslengthofanUTF8stringinUTF8characters unpacksabinarystructureintonewLISPexpressions convertsastringtouppercasecharacters

Floatingpointmathandspecialfunctions
abs acos acosh add array arraylist asin asinh atan atanh atan2 beta betai binomial ceil cos cosh crc32 dec div erf exp factor fft floor flt gammai gammaln gcd ifft inc inf? log returnstheabsolutevalueofanumber calculatesthearccosineofanumber calculatestheinversehyperboliccosineofanumber addsfloatingpointorintegernumbersandreturnsafloatingpointnumber createsanarray returnsalistconversionfromanarray calculatesthearcsineofanumber calculatestheinversehyperbolicsineofanumber calculatesthearctangentofanumber calculatestheinversehyperbolictangentofanumber computestheprincipalvalueofthearctangentofY/Xinradians calculatesthebetafunction calculatestheincompletebetafunction calculatesthebinomialfunction roundsuptothenextinteger calculatesthecosineofanumber calculatesthehyperboliccosineofanumber calculatesa32bitCRCforadatabuffer decrementsanumberinavariable,listorarray dividesfloatingpointorintegernumbers calculatestheerrorfunctionofanumber calculatestheexponentialeofanumber factorsanumberintoprimes performsafastFouriertransform(FFT) roundsdowntothenextinteger convertsanumbertoa32bitintegerrepresentingafloat calculatestheincompleteGammafunction calculatesthelogGammafunction calculatesthegreatestcommondivisorofagroupofintegers performsaninversefastFouriertransform(IFFT) incrementsanumberinavariable,listorarray checksifafloatingpointvalueisinfinite calculatesthenaturalorotherlogarithmofanumber

min max mod mul NaN? round pow sequence series sgn sin sinh sqrt sub tan tanh uuid

findsthesmallestvalueinaseriesofvalues findsthelargestvalueinaseriesofvalues calculatesthemodulooftwonumbers multipliesfloatingpointorintegernumbers checksifafloatisNaN(notanumber) roundsanumber calculatesxtothepowerofy generatesalistsequenceofnumbers createsageometricsequenceofnumbers calculatesthesignumfunctionofanumber calculatesthesineofanumber calculatesthehyperbolicsineofanumber calculatesthesquarerootofanumber subtractsfloatingpointorintegernumbers calculatesthetangentofanumber calculatesthehyperbolictangentofanumber returnsaUUID(UniversalUniqueIDentifier)

Matrixfunctions
det invert mat multiply transpose returnsthedeterminantofamatrix returnstheinversionofamatrix performsscalaroperationsonmatrices multipliestwomatrices returnsthetranspositionofamatrix

Arrayfunctions
append array arraylist array? det first invert last mat multiply nth rest setf slice transpose appendsarrays createsandinitializesanarraywithupto16dimensions convertsanarrayintoalist checksifexpressionisanarray returnsthedeterminantofamatrix returnsthefirstrowofanarray returnstheinversionofamatrix returnsthelastrowofanarray performsscalaroperationsonmatrices multipliestwomatrices returnsanelementofanarray returnsallbutthefirstrowofanarray setscontentsofanarrayreference returnsasliceofanarray transposesamatrix

Bitoperators

<<,>> & | ^ ~

bitshiftleft,bitshiftright bitwiseand bitwiseinclusiveor bitwiseexclusiveor bitwisenot

Predicates
atom? array? bigint? context? directory? empty? even? file? float? global? inf? integer? lambda? legal? list? macro? NaN? nil? null? number? odd? protected? primitive? quote? string? symbol? true? zero? checksifanexpressionisanatom checksifanexpressionisanarray checksifanumberisabiginteger checksifanexpressionisacontext checksifadisknodeisadirectory checksifalistorstringisempty checkstheparityofanintegernumber checksifafileexists checksifanexpressionisafloat checksifasymbolisglobal checksifafloatingpointvalueisinfinite checksifanexpressionisaninteger checksifanexpressionisalambdaexpression checksifastringcontainsalegalsymbol checksifanexpressionisalist checksifanexpressionisalambdamacroexpression checksifafloatisNaN(notanumber) checksifanexpressionisn i l checksifanexpressionisn i l ," " ,( ) ,0 or0 . 0 checksifanexpressionisafloatoraninteger checkstheparityofanintegernumber checksifasymbolisprotected checksifanexpressionisaprimitive checksifanexpressionisquoted checksifanexpressionisastring checksifanexpressionisasymbol checksifanexpressionisnotn i l checksifanexpressionis0 or0 . 0

Dateandtimefunctions
date datelist dateparse datevalue now time convertsadatetimevaluetoastring returnsalistofyear,month,day,hours,minutes,secondsfromatimevalueinseconds parsesadatestringandreturnsthenumberofsecondspassedsinceJanuary1,1970,(formerlyp a r s e d a t e ) calculatesthetimeinsecondssinceJanuary1,1970foradateandtime returnsalistofcurrentdatetimeinformation calculatesthetimeittakestoevaluateanexpressioninmilliseconds

timeofday

calculatesthenumberofmillisecondselapsedsincethedaystarted

Statistics,simulationandmodelingfunctions
amb bayesquery bayestrain corr critchi2 critf critt critz kmeansquery kmeanstrain normal probchi2 probf probt probz rand random randomize seed stats ttest randomlyselectsanargumentandevaluatesit calculatesBayesianprobabilitiesforadataset countsitemsinlistsforBayesianorfrequencyanalysis calculatestheproductmomentcorrelationcoefficient calculatestheChistatisticforagivenprobability calculatestheFstatisticforagivenprobability calculatestheStudent'ststatisticforagivenprobability calculatesthenormaldistributedZforagivenprobability calculatesdistancestoclustercentroidsorotherdatapoints partitionsadatasetintoclusters makesalistofnormaldistributedfloatingpointnumbers calculatesthetailprobabilityofaChidistributionvalue calculatesthetailprobabilityofaFdistributionvalue calculatesthetailprobabilityofaStudent'stdistributionvalue calculatesthecumulatedprobabilityofaZdistributionvalue generatesrandomnumbersinarange generatesalistofevenlydistributedfloats shufflesalloftheelementsinalist seedstheinternalrandomnumbergenerator calculatessomebasicstatisticsforadatavector comparesmeansofdatasamplesusingtheStudent'ststatistic

Patternmatching
endswith find findall match parse ref refall regex replace search startswith unify testsifalistorstringendswithapattern searchesforapatterninalistorstring findsalloccurrencesofapatterninastring matcheslistpatterns breaksastringalongaroundpatterns returnsthepositionofanelementinsideanestedlist returnsalistofindexvectorsofelementsinsideanestedlist findspatternsinastring replacespatternsinastring searchesforapatterninafile testsifalistorstringstartswithapattern performsalogicalunificationofpatterns

Financialmathfunctions
fv irr returnsthefuturevalueofaninvestment calculatestheinternalrateofreturn

nper npv pv pmt

calculatesthenumberofperiodsforaninvestment calculatesthenetpresentvalueofaninvestment calculatesthepresentvalueofaninvestment calculatesthepaymentforaloan

Input/outputandfileoperations
appendfile close currentline device exec load open peek print println read readchar readfile readkey readline readutf8 save search seek write writechar writefile writeline appendsdatatoafile closesafile retrievescontentsoflastreadlinebuffer setsorinquiresaboutcurrentprintdevice launchesanotherprogram,thenreadsfromorwritestoit loadsandevaluatesafileofnewLISPcode opensafileforreadingorwriting checksfiledescriptorfornumberofbytesreadyforreading printstotheconsoleoradevice printstotheconsoleoradevicewithalinefeed readsbinarydatafromafile readsan8bitcharacterfromafile readsawholefileinoneoperation readsakeyboardkey readsalinefromtheconsoleorfile readsUTF8characterfromafile savesaworkspace,context,orsymboltoafile searchesafileforastring setsorreadsafileposition writesbinarydatatoafile writesacharactertoafile writesafileinoneoperation writesalinetotheconsoleorafile

ProcessesandtheCilkAPI
! abort destroy exec fork pipe process receive semaphore send share spawn sync shellsouttotheoperatingsystem abortsachildprocessstartedwiths p a w n destroysaprocesscreatedwithf o r k orp r o c e s s runsaprocess,thenreadsfromorwritestoit launchesanewLISPchildprocess createsapipeforinterprocesscommunication launchesachildprocess,remappingstandardI/Oandstandarderror receiveamessagefromanotherprocess createsandcontrolssemaphores sendamessagetoanotherprocess sharesmemorywithotherprocesses launchesachildprocessforCilkprocessmanagement waitsforchildprocesseslaunchedwiths p a w n andcollectsresults

waitpid

waitsforachildprocesstoend

Fileanddirectorymanagement
changedir copyfile deletefile directory fileinfo makedir realpath removedir renamefile changestoadifferentdriveanddirectory copiesafile deletesafile returnsalistofdirectoryentries getsfilesize,date,time,andattributes makesanewdirectory returnsthefullpathoftherelativefilepath removesanemptydirectory renamesafileordirectory

HTTPnetworkingAPI
base64enc base64dec deleteurl geturl jsonerror jsonparse posturl puturl xferevent xmlerror xmlparse xmltypetags encodesastringintoBASE64format decodesastringfromBASE64format deletesafileorpagefromtheweb readsafileorpagefromtheweb returnserrorinformationfromafailedJSONtranslation. parsesJSONformatteddata postsinfotoaURLaddress uploadsapagetoaURLaddress registersaneventhandlerforHTTPbytetransfers returnslastXMLparseerror parsesanXMLdocument showsormodifiesXMLtypetags

SocketTCP/IP,UDPandICMPnetworkAPI
netaccept netclose netconnect neterror neteval netinterface netipv netlisten netlocal netlookup netpacket netpeek netpeer acceptsanewincomingconnection closesasocketconnection connectstoaremotehost returnsthelasterror evaluatesexpressionsonmultipleremotenewLISPservers SetsthedefaultinterfaceIPaddressonmultihomedcomputers. SwitchesbetweenIPv4andIPv6internetprotocolversions. listensforconnectionstoalocalsocket returnsthelocalIPandportnumberforaconnection returnsthenameforanIPnumber sendacustomconfiguredIPpacketoverrawsockets returnsthenumberofcharactersreadytobereadfromanetworksocket returnstheremoteIPandportforanetconnect

netping netreceive netreceivefrom netreceiveudp netselect netsend netsendto netsendudp netservice netsessions

sendsapingpacket(ICMPechorequest)tooneormoreaddresses readsdataonasocketconnection readsaUDPonanopenconnection readsaUDPandclosestheconnection checksasocketorlistofsocketsforstatus sendsdataonasocketconnection sendsaUDPonanopenconnection sendsaUDPandclosestheconnection translatesaservicenameintoaportnumber returnsalistofcurrentlyopenconnections

Reflectionandcustomization
commandevent errorevent lasterror ostype prefix promptevent readexpr readerevent setlocale source syserror sysinfo term preprocessesthecommandlineandHTTPrequests definesanerrorhandler reportthelasterrornumberandtext containsastringdescribingtheOSplatform Returnsthecontextprefixofasymbol customizestheinteractivenewLISPshellprompt readsandtranslatessexpressionsfromsource preprocessexpressionsbeforeevaluationeventdriven switchestoadifferentlocale returnsthesourcerequiredtobindasymboltoastring reportsOSsystemerrornumbers givesinformationaboutsystemresources returnsthetermpartofasymboloritscontextasastring

Systemfunctions
$ callback catch context copy debug delete default env exit global import mainargs new prettyprint readexpr reset accessessystemvariables$0>$15 registersacallbackfunctionforanimportedlibrary evaluatesanexpression,catchingerrorsandearlyreturns createsorswitchestoadifferentnamespace copiestheresultofanevaluation debugsauserdefinedfunction deletessymbolsfromthesymboltable returnsthecontentsofadefaultfunctorfromacontext getsorsetstheoperatingsystem'senvironment exitsnewLISP,settingtheexitvalue makesasymbolaccessibleoutsideMAIN importsafunctionfromasharedlibrary getscommandlinearguments createsacopyofacontext changestheprettyprintingcharacteristics translatesastringtoansexpressionwithoutevaluatingit goestothetoplevel

signal sleep sym symbols throw throwerror timer trace tracehighlight

setsasignalhandler suspendsprocessingforspecifiedmilliseconds createsasymbolfromastring returnsalistofallsymbolsinthesystem causesapreviouscatchtoreturn throwsauserdefinederror startsaoneshottimer,firinganevent setsorinquiresabouttracemode setshighlightingstringsintracemode

Importinglibraries
address callback flt float getchar getfloat getint getlong getstring import int pack struct unpack returnsthememoryaddressofanumberorstring registersacallbackfunctionforanimportedlibrary convertsanumbertoa32bitintegerrepresentingafloat translatesastringorintegerintoafloatingpointnumber getsacharacterfromamemoryaddress getsadoublefloatfromamemoryaddress getsa32bitintegerfromamemoryaddress getsalong64bitintegerfromamemoryaddress getsastringfromamemoryaddress importsafunctionfromasharedlibrary translatesastringorfloatintoaninteger packsnewLISPexpressionsintoabinarystructure DefinesadatastructurewithCtypes unpacksabinarystructureintonewLISPexpressions

newLISPinternalsAPI
commandevent cpymem dump promptevent readexpr readerevent preprocessesthecommandlineandHTTPrequests copiesmemorybetweenaddresses showsmemoryaddressandcontentsofnewLISPcells customizestheinteractivenewLISPshellprompt readsandtranslatessexpressionsfromsource preprocessexpressionsbeforeevaluationeventdriven

()

4.Functionsinalphabeticalorder

!
syntax:(!strshellcommand[intflags])

Executesthecommandinstrcommandbyshellingouttotheoperatingsystemandexecuting.Thisfunctionreturnsadifferent valuedependingonthehostoperatingsystem.
( !" v i " ) ( !" l sl t r " )

Usetheexecfunctiontoexecuteashellcommandandcapturethestandardoutputortofeedstandardinput.Theprocessfunction maybeusedtolaunchanonblockingchildprocessandredirectstdI/Oandstderrortopipes. OnMsWindowstheoptionalintflagsparametertakesprocesscreationflagsasdefinedfortheWindowsC r e a t e P r o c e s s A functiontocontrolvariousparametersofprocesscreation.Theinclusionofthisparameterwhichalsocanbe0 forcesadifferent creationoftheprocesswithoutacommandshellwindow.ThisparameterisignoredonUnix.


;o nM SW i n d o w s ;c l o s et h ec o n s o l eo ft h ec u r r e n t l yr u n n i n gn e w L I S Pp r o c e s s ( a p p l y( i m p o r t" k e r n e l 3 2 "" F r e e C o n s o l e " ) ) ;s t a r ta n o t h e rp r o c e s sa n dw a i tf o ri tt of i n i s h ( !" n o t e p a d . e x e "0 ) ( e x i t )

Withouttheadditionalparameter,the! callwouldcreateanewcommandwindowreplacingtheclosedone. Notethat! (exclamationmark)canbealsobeusedasacommandlineshelloperatorbyomittingtheparenthesisandspaceafterthe ! :


>! l sl t r ;e x e c u t e di nt h en e w L I S Ps h e l lw i n d o w

Usedinthisway,the! operatorisnotanewLISPfunctionatall,butratheraspecialfeatureofthenewLISPcommandshell.The! mustbeenteredasthefirstcharacteronthecommandline.

$
syntax:($intidx) Thefunctionsthatuseregularexpressions(directory,endswith,find,parse,regex,search,startswithandreplace)allbindtheir resultstothepredefinedsystemvariables$ 0 ,$ 1 ,$ 2 $ 1 5 afterorduringthefunction'sexecution.Systemvariablescanbetreatedthe sameasanyothersymbol.Asanalternative,thecontentsofthesevariablesmayalsobeaccessedbyusing( $0 ) ,( $1 ) ,( $2 ) , etc.Thismethodallowsindexedaccess(i.e.,( $i ) ,wherei isaninteger).
( s e t' s t r " h t t p : / / n e w l i s p . o r g : 8 0 " ) ( f i n d" h t t p : / / ( . * ) : ( . * ) "s t r0 ) 0 $ 0 " h t t p : / / n e w l i s p . o r g : 8 0 " $ 1 " n e w l i s p . o r g " $ 2 " 8 0 " ( $0 ) " h t t p : / / n e w l i s p . o r g : 8 0 " ( $1 ) " n e w l i s p . o r g " ( $2 ) " 8 0 "

+,,*,/,%
syntax:(+int1[int2...])

Returnsthesumofallnumbersinint1. syntax:(int1[int2...]) Subtractsint2fromint1,thenthenextintifromthepreviousresult.Ifonlyoneargumentisgiven,itssignisreversed. syntax:(*int1[int2...]) Theproductiscalculatedforint1tointi. syntax:(/int1[int2...]) Eachresultisdividedsuccessivelyuntiltheendofthelistisreached.Divisionbyzerocausesanerror. syntax:(%int1[int2...]) Eachresultisdividedsuccessivelybythenextint,thentherest(modulooperation)isreturned.Divisionbyzerocausesanerror.For floatingpointnumbers,usethemodfunction.
( +12345 ) ( +12( -52 )8 ) ( -1 0321 ) ( -( *34 )612 ) ( -1 2 3 ) ( m a p-' ( 1 02 03 0 ) ) ( *123 ) ( *1 0( -82 ) ) ( /1 23 ) ( /1 2 032 02 ) ( %1 03 ) ( %1 03 ) ( +1 . 23 . 9 ) 1 5 1 4 4 3 1 2 3 ( 1 02 03 0 ) 6 6 0 4 1 1 1 4

Floatingpointvaluesinargumentsto+ ,,* ,/ ,and% aretruncatedtotheintegervalueclosestto0 (zero). Floatingpointvalueslargerorsmallerthanthemaximum(9 , 2 2 3 , 3 7 2 , 0 3 6 , 8 5 4 , 7 7 5 , 8 0 7 )orminimum (9 , 2 2 3 , 3 7 2 , 0 3 6 , 8 5 4 , 7 7 5 , 8 0 8 )integervaluesaretruncatedtothosevalues.Thisincludesthevaluesfor+ I n f andI n f . Calculationsresultinginvalueslargerthan9 , 2 2 3 , 3 7 2 , 0 3 6 , 8 5 4 , 7 7 5 , 8 0 7 orsmallerthan9 , 2 2 3 , 3 7 2 , 0 3 6 , 8 5 4 , 7 7 5 , 8 0 8 wrap aroundfrompositivetonegativeornegativetopositive. FloatingpointvaluesthatevaluatetoN a N (NotaNumber),artreatedas0 (zero).

++!
syntax:(++place[num...]) The+ + operatorworkslikeinc,butperformsintegerarithmetic.Withouttheoptionalargumentinnum,+ + incrementsthenumberin placeby1 . Iffloatingpointnumbersarepassedasarguments,theirfractionalpartgetstruncatedfirst. Calculationsresultinginnumbersgreaterthan9,223,372,036,854,775,807wraparoundtonegativenumbers.Resultssmallerthan 9,223,372,036,854,775,808wraparoundtopositivenumbers. placeiseitherasymboloraplaceinaliststructureholdinganumber,oranumberreturnedbyanexpression.

( s e t' x1 ) ( + +x ) 2 ( s e t' x3 . 8 ) ( + +x ) 4 ( + +x1 . 3 ) 5 ( s e t' l s t' ( 123 ) ) ( + +( l s t1 )2 ) ) 4 l s t ( 143 )

Ifthesymbolforplacecontainsn i l ,itistreatedasifcontaining0 . Seefordecrementingnumbersinintegermode.Seeincforincrementingnumbersinfloatingpointmode.

!
syntax:(place[num...]) Theoperatorworkslikedec,butperformsintegerarithmetic.Withouttheoptionalargumentinnum2,decrementsthe numberinplaceby1 . Iffloatingpointnumbersarepassedasarguments,theirfractionalpartgetstruncatedfirst. Calculationsresultinginnumbersgreaterthan9,223,372,036,854,775,807wraparoundtonegativenumbers.Resultssmallerthan 9,223,372,036,854,775,808wraparoundtopositivenumbers. placeiseitherasymboloraplaceinaliststructureholdinganumber,oranumberreturnedbyanexpression.
( s e t' x1 ) ( -x ) 0 ( s e t' x3 . 8 ) ( -x ) 2 ( -x1 . 3 ) 1 ( s e t' l s t' ( 123 ) ) ( -( l s t1 )2 ) ) 0 l s t ( 103 )

Ifthesymbolforplacecontainsn i l ,itistreatedasifcontaining0 . See++forincrementingnumbersinintegermode.Seedecfordecrementingnumbersinfloatingpointmode.

<,>,=,<=,>=,!=
syntax:(<exp1[exp2...]) syntax:(>exp1[exp2...]) syntax:(=exp1[exp2...]) syntax:(<=exp1[exp2...]) syntax:(>=exp1[exp2...]) syntax:(!=exp1[exp2...]) Expressionsareevaluatedandtheresultsarecomparedsuccessively.Aslongasthecomparisonsconformtothecomparison operators,evaluationandcomparisonwillcontinueuntilallargumentsaretestedandtheresultist r u e .Assoonasonecomparison fails,n i l isreturned. Ifonlyoneargumentissupplied,allcomparisonoperatorsassume0 (zero)asasecondargument.Thiscanbeusedtocheckifa

numberisnegative,positive,zeroornotzero. Alltypesofexpressionscanbecompared:atoms,numbers,symbols,andstrings.Listexpressionscanalsobecompared(list elementsarecomparedrecursively). Whencomparinglists,elementsatthebeginningofthelistareconsideredmoresignificantthantheelementsfollowing(similarto charactersinastring).Whencomparinglistsofdifferentlengthsbutequalelements,thelongerlistisconsideredgreater(see examples). Inmixedtypeexpressions,thetypesarecomparedfromlowesttohighest.Floatsandintegersarecomparedbyfirstconvertingthem totheneededtype,thencomparingthemasnumbers. Atoms:nil,true,integerorfloat,string,symbol,primitive Lists:quotedlist/expression,list/expression,lambda,lambdamacro
( <3589 ) t r u e ( >4236 ) n i l ( <" a "" c "" d " ) t r u e ( > =d u b aa b a ) t r u e ( <' ( 34 )' ( 15 ) ) n i l ( >' ( 123 )' ( 12 ) ) t r u e ( =' ( 578 )' ( 578 ) ) t r u e ( ! =14373 ) t r u e ( <1 . 26" H e l l o "' a n y' ( 123 ) ) ( <n i lt r u e ) ( <' ( ( ( ab ) ) )' ( ( ( bc ) ) ) ) ( <' ( ( a( bc ) )' ( a( bd ) )' ( a( b( d ) ) ) ) ) ;w i t hs i n g l ea r g u m e n tc o m p a r e sa g a i n s t0 ( >1 ) t r u e;c h e c k sf o rp o s i t i v e ( >1 ) n i l;c h e c k sf o rn e g a t i v e ( =1 2 3 ) n i l;c h e c k sf o rz e r o ( m a p>' ( 134312 ) ) ( t r u et r u en i ln i lt r u et r u e )

t r u e t r u e t r u e t r u e

<<,>>
syntax:(<<int1int2[int3...]) syntax:(>>int1int2[int3...]) syntax:(<<int1) syntax:(>>int1) Thenumberint1isarithmeticallyshiftedtotheleftorrightbythenumberofbitsgivenasint2,thenshiftedbyint3andsoon.For example,64bitintegersmaybeshiftedupto63positions.Whenshiftingright,themostsignificantbitisduplicated(arithmetic shift):
( > >0 x 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 01 ) 0 x C 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ;n o t0 x 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 !

( < <13 ) ( < <121 ) ( > >1 0 2 41 0 ) ( > >1 6 022 ) ( < <3 ) ( > >8 )

8 8 1 1 0 6 4

Whenint1istheonlyargument< < and> > shiftbyonebit.

&
syntax:(&int1int2[int3...]) Abitwisea n d operationisperformedonthenumberinint1withthenumberinint2,thensuccessivelywithint3,etc.
( &0 x A A B B0 x 0 0 0 F ) 1 1 ;w h i c hi s0 x B

|
syntax:(|int1int2[int3...]) Abitwiseo r operationisperformedonthenumberinint1withthenumberinint2,thensuccessivelywithint3,etc.
( |0 x 1 00 x 8 021 ) 1 4 7

^
syntax:(^int1int2[int3...]) Abitwisex o r operationisperformedonthenumberinint1withthenumberinint2,thensuccessivelywithint3,etc.
( ^0 x A A0 x 5 5 ) 2 5 5

~
syntax:(~int) Abitwisen o t operationisperformedonthenumberinint,reversingallofthebits.
( f o r m a t" % X "( ~0 x F F F F F F A A ) ) " 5 5 " ( ~0 x F F F F F F F F ) 0

:
syntax:(:symfunctionlistobject[...]) Thecolonisusednotonlyasasyntacticseparatorbetweennamespaceprefixandtheterminsidebutalsoasanoperator.When usedasanoperator,thecolon: constructsacontextsymbolfromthecontextnameintheobjectlistandthesymbolfollowingthe colon.Theobjectlistinlistobjectcanbefollowedbyotherparameters. The: operatorimplementspolymorphismofobjectmethods,whicharepartofdifferentobjectclassesrepresentedbycontexts (namespaces).InnewLISP,anobjectisrepresentedbyalist,thefirstelementofwhichisthesymbol(name)ofitsclasscontext.

Theclasscontextimplementsthefunctionsapplicabletotheobject.Nospaceisrequiredbetweenthecolonandthesymbol followingit.
( d e f i n e( R e c t a n g l e : a r e a ) ( m u l( s e l f3 )( s e l f4 ) ) ) ( d e f i n e( C i r c l e : a r e a ) ( m u l( p o w( s e l f3 )2 )( a c o s0 )2 ) ) ( d e f i n e( R e c t a n g l e : m o v ed xd y ) ( i n c( s e l f1 )d x ) ( i n c( s e l f2 )d y ) ) ( d e f i n e( C i r c l e : m o v epd xd y ) ( i n c( s e l f1 )d x )( i n c( s e l f2 )d y ) ) ( s e t' m y r e c t' ( R e c t a n g l e551 02 0 ) );xyw i d t hh e i g h t ( s e t' m y c i r c l e' ( C i r c l e121 0 ) );xyr a d i u s ; ;u s i n gt h e:( c o l o n )o p e r a t o rt or e s o l v et oas p e c i f i cc o n t e x t ( : a r e am y r e c t ) ( : a r e am y c i r c l e ) 2 0 0 3 1 4 . 1 5 9 2 6 5 4

; ;m a pc l a s sm e t h o d su s e sc u r r yt oe n c l o s et h ec o l o no p e r a t o ra n dc l a s sf u n c t i o n ( m a p( c u r r y: a r e a )( l i s tm y r e c tm y c i r c l e ) )( 2 0 03 1 4 . 1 5 9 2 6 5 4 ) ( m a p( c u r r y: a r e a )' ( ( R e c t a n g l e551 02 0 )( C i r c l e121 0 ) ) )( 2 0 03 1 4 . 1 5 9 2 6 5 4 ) ; ;c h a n g eo b j e c ta t t r i b u t e su s i n gaf u n c t i o na n dr e a s s i g n i n g ; ;t ot h eo b j e c t sn a m e ( : m o v em y r e c t23 ) m y r e c t ( R e c t a n g l e781 02 0 ) ( : m o v em y c i r c l e45 ) m y c i r c l e( C i r c l e571 0 )

InsidetheFOOPmethodstheselffunctionisusedtoaccessthetargetobjectofthemethod.

abort
syntax:(abortintpid) syntax:(abort) Inthefirstform,a b o r t abortsaspecificchildprocessofthecurrentparentprocessgivingtheprocessidinintpid.Theprocessmust havebeenstartedusingspawn.Forprocessesstartedusingfork,usedestroyinstead. Thefunctiona b o r t isnotavailableonWin32.
( a b o r t2 2 4 5 ) t r u e

Toabortallchildprocessesspawnedfromthecurrentprocessusea b o r t withoutanyparameters:
( a b o r t ) t r u e;a b o r ta l l

Thefunctiona b o r t ispartoftheCilkAPIforsynchronizingchildprocessesandprocessparallelization.Seethereferenceforthe functionspawnforafulldiscussionoftheCilkAPI.

abs
syntax:(absnum) Returnstheabsolutevalueofthenumberinnum.
( a b s3 . 5 ) 3 . 5

acos
syntax:(acosnumradians) Thearccosinefunctioniscalculatedfromthenumberinnumradians.
( a c o s1 ) 0 ( c o s( a c o s1 ) )1

acosh
syntax:(acoshnumradians) Calculatestheinversehyperboliccosineofnumradians,thevaluewhosehyperboliccosineisnumradians.Ifnumradiansisless than1,a c o s h returnsN a N .
( a c o s h2 ) 1 . 3 1 6 9 5 7 8 9 7 ( c o s h( a c o s h2 ) )2 ( a c o s h0 . 5 )N a N

add
syntax:(addnum1[num2...]) Allofthenumbersinnum1,num2,andonaresummed.a d d acceptsfloatorintegeroperands,butitalwaysreturnsafloatingpoint number.AnyfloatingpointcalculationwithN a N alsoreturnsN a N .
( a d d23 . 2 59 ) 1 4 . 2 5 ( a d d12345 ) 1 5

address
syntax:(addressint) syntax:(addressfloat) syntax:(addressstr) Returnsthememoryaddressoftheintegerinint,thedoublefloatingpointnumberinfloat,orthestringinstr.Thisfunctionisused

forpassingparameterstolibraryfunctionsthathavebeenimportedusingtheimportfunction.
( s e t' s" \ 0 0 1 \ 0 0 2 \ 0 0 3 \ 0 0 4 " ) ( g e t c h a r( +( a d d r e s ss )3 ) ) 4

( s e t' x1 2 3 4 5 );xi sa6 4 b i tl o n gi n t ;o nab i g e n d i a nC P U ,i . e .P P Co rS P A R C ( g e t l o n g( a d d r e s sx ) ) 1 2 3 4 5 ;t h e3 2 b i ti n ti si nh i g h3 2 b i tp a r to ft h el o n gi n t ( g e t i n t( +( a d d r e s sx )4 ) ) 1 2 3 4 5 ;o nal i t t l e e n d i a nC P U ,i . e .I n t e li 3 8 6 ;t h e3 2 b i ti n ti si nt h el o w3 2 b i tp a r to ft h el o n gi n t ( g e t i n t( a d d r e s sx ) ) 1 2 3 4 5 ;o nb o t ha r c h i t e c t u r e s( i n t e g e r sa r e6 4b i ti nn e w L I S P ) ( s e t' x1 2 3 4 5 6 7 8 9 0 ) ( g e t l o n g( a d d r e s sx ) ) 1 2 3 4 5 6 7 8 9 0

WhenastringispassedtoClibraryfunctiontheaddressofthestringisusedautomatically,anditisnotnecessarytousethe a d d r e s s functioninthatcase.Astheexampleshows,a d d r e s s canbeusedtodopointerarithmeticonthestring'saddress.


a d d r e s s shouldonlybeusedonpersistentaddressesfromdataobjectsreferredtobyavariablesymbol,notfromvolatile

intermediateexpressionobjects. Seealsothegetchar,getint,getlongandgetfloatfunctions.

amb
syntax:(ambexp1[exp2...]) Oneoftheexpressionsexp1...nisselectedatrandom,andtheevaluationresultisreturned.
( a m b' a' b' c' d' e ) o n eo f :a ,b ,c ,d ,o rea tr a n d o m ( d o t i m e s( x1 0 )( p r i n t( a m b357 ) ) ) 3 5 7 7 7 5 3 5 7 5 5

Internally,newLISPusesthesamefunctionasrandtopickarandomnumber.Togeneraterandomfloatingpointnumbers,use random,randomize,ornormal.Toinitializethepseudorandomnumbergeneratingprocessataspecificstartingpoint,usetheseed function.

and
syntax:(andexp1[exp2...]) Theexpressionsexp1,exp2,etc.areevaluatedinorder,returningtheresultofthelastexpression.Ifanyoftheexpressionsyield n i l ortheemptylist( ) ,evaluationisterminatedandn i l ortheemptylist( ) isreturned.
( s e t' x1 0 ) ( a n d( <x1 0 0 )( >x2 ) ) ( a n d( <x1 0 0 )( >x2 )" p a s s e d " ) ( a n d' ( ) ) ( a n dt r u e ) ( a n d ) 1 0 t r u e " p a s s e d " ( ) t r u e t r u e

append
syntax:(appendlist1[list2...]) syntax:(appendarray1[array2...]) syntax:(appendstr1[str2...]) Inthefirstform,a p p e n d workswithlists,appendinglist1throughlistntoformanewlist.Theoriginallistsareleftunchanged.
( a p p e n d' ( 123 )' ( 456 )' ( ab ) ) ( 123456ab ) ( s e t' a L i s t' ( " h e l l o "" w o r l d " ) ) ( a p p e n da L i s t' ( " h e r e "" Ia m " ) ) ( " h e l l o "" w o r l d " ) ( " h e l l o "" w o r l d "" h e r e "" Ia m " )

Inthesecondforma p p e n d worksonarrays:
( s e t' A( a r r a y32( s e q u e n c e16 ) ) ) ( ( 12 )( 34 )( 56 ) ) ( s e t' B( a r r a y22( s e q u e n c e71 0 ) ) ) ( ( 78 )( 91 0 ) ) ( a p p e n dAB ) ( ( 12 )( 34 )( 56 )( 78 )( 91 0 ) ) ( a p p e n dBBB ) ( ( 78 )( 91 0 )( 78 )( 91 0 )( 78 )( 91 0 ) )

Inthethirdform,a p p e n d worksonstrings.Thestringsinstrnareconcatenatedintoanewstringandreturned.
( s e t' m o r e"h o wa r ey o u " ) "h o wa r ey o u "

( a p p e n d" H e l l o"" w o r l d , "m o r e ) " H e l l ow o r l d ,h o wa r ey o u " a p p e n d isalsosuitableforprocessingbinarystringscontainingzeroes.Thestringfunctionwouldcutoffstringsatzerobytes.

Linkagecharactersorstringscanbespecifiedusingthejoinfunction.Usethestringfunctiontoconvertargumentstostringsand appendinonestep. Usethefunctionsextendandpushtoappendtoanexistinglistorstringmodifyingthetarget.

appendfile
syntax:(appendfilestrfilenamestrbuffer) Workssimilarlytowritefile,butthecontentinstrbufferisappendedifthefileinstrfilenameexists.Ifthefiledoesnotexist,itis created(inthiscase,a p p e n d f i l e worksidenticallytowritefile).Thisfunctionreturnsthenumberofbyteswritten. Onfailurethefunctionreturnsn i l .Forerrorinformation,usesyserrorwhenusedonfiles.WhenusedonURLsneterrorgives moreerrorinformation.
( w r i t e f i l e" m y f i l e . t x t "" A B C " ) ( a p p e n d f i l e" m y f i l e . t x t "" D E F " ) ( r e a d f i l e" m y f i l e . t x t " ) " A B C D E F " a p p e n d f i l e cantakeah t t p : / / orf i l e : / / URLinstrfilename.Incaseoftheh t t p : / / prefix,a p p e n d f i l e worksexactly

likeputurlwith" P r a g m a :a p p e n d \ r \ n " intheheaderoptionandcantakethesameadditionalparameters.The" P r a g m a : a p p e n d \ r \ n " optionissuppliedautomatically.


( a p p e n d f i l e" h t t p : / / a s i t e . c o m / m e s s a g e . t x t "" M o r em e s s a g et e x t . " )

Thefilem e s s a g e . t x t isappendedataremotelocationh t t p : / / a s i t e . c o m withthecontentsofstrbuffer.Ifthefiledoesnotyet exist,itwillbecreated.Inthismode,a p p e n d f i l e canalsobeusedtotransferfilestoremotenewLISPservernodes. Seealsoreadfileandwritefile.

apply
syntax:(applyfunclist[intreduce]) Appliesthecontentsoffunc(primitive,userdefinedfunction,orlambdaexpression)totheargumentsinlist.
( a p p l y+' ( 1234 ) ) ( s e t' a L i s t' ( 345 ) ) ( a p p l y*a L i s t ) ( a p p l ys q r t' ( 2 5 ) ) ( a p p l y( l a m b d a( xy )( *xy ) )' ( 34 ) ) 1 0 ( 345 ) 6 0 5 1 2

Theintreduceparametercanoptionallycontainthenumberofargumentstakenbythefunctioninfunc.Inthiscase,funcwillbe repeatedlyappliedusingthepreviousresultasthefirstargumentandtakingtheotherargumentsrequiredsuccessivelyfromlist(in leftassociativeorder).Forexample,ifo p takestwoarguments,then:


( a p p l yo p' ( 12345 )2 ) ; ;i se q u i v a l e n tt o ( o p( o p( o p( o p12 )3 )4 )5 ) ; ;f i n dt h eg r e a t e s tc o m m o nd i v i s o r ; ;o ft w oo rm o r ei n t e g e r s ; ;n o t et h a tn e w L I S Pa l r e a d yh a sag c df u n c t i o n ( d e f i n e( g c d _ab ) ( l e t( r( %ba ) ) ( i f( =r0 )a( g c d _ra ) ) ) ) ( d e f i n e m a c r o( m y g c d ) ( a p p l yg c d _( a r g s )2 ) ) ( m y g c d1 21 86 ) 6 ( m y g c d1 21 864 ) 2

Thelastexampleshowshowa p p l y 'sreducefunctionalitycanbeusedtoconvertatwoargumentfunctionintoonethattakes multiplearguments.Note,thatabuiltingcdisavailable.


a p p l y shouldonlybeusedonfunctionsandoperatorsthatevaluatealloftheirarguments,notonspecialformslikedotimesorcase,

whichevaluateonlysomeoftheirarguments.Doingsowillcausethefunctiontofail.

args
syntax:(args) syntax:(argsintidx1[intidx2...])

Accessesalistofallunboundargumentspassedtothecurrentlyevaluatingdefine,definemacrolambda,orlambdamacro expression.Onlytheargumentsofthecurrentfunctionormacrothatremainafterlocalvariablebindinghasoccurredareavailable. Thea r g s functionisusefulfordefiningfunctionsormacroswithavariablenumberofparameters.


a r g s canbeusedtodefinehygienicmacrosthatavoidthedangerofvariablecapture.Seedefinemacro. ( d e f i n e m a c r o( p r i n t l i n e ) ( d o l i s t( x( a r g s ) ) ( p r i n tx" \ n " ) ) ) ( p r i n t l i n e" h e l l o "" W o r l d " )

Thisexampleprintsalinefeedaftereachargument.Themacromimicstheeffectofthebuiltinfunctionprintln. Inthesecondsyntax,a r g s cantakeoneormoreindices(intidxn).


( d e f i n e m a c r o( f o o ) ( p r i n t( a r g s2 )( a r g s1 )( a r g s0 ) ) ) ( f o oxyz ) z y x ( d e f i n e( b a r ) ( a r g s021 ) ) ( b a r' ( 12( 34 ) ) ) 4

Thefunctionf o o printsouttheargumentsinreverseorder.Theb a r functionshowsa r g s beingusedwithmultipleindicestoaccess nestedlists. Rememberthat( a r g s ) onlycontainstheargumentsnotalreadyboundtolocalvariablesofthecurrentfunctionormacro:


( d e f i n e( f o oab )( a r g s ) ) ( f o o12 ) ( )

( f o o12345 ) ( 345 )

Inthefirstexample,anemptylistisreturnedbecausetheargumentsareboundtothetwolocalsymbols,a andb .Thesecond exampledemonstratesthat,afterthefirsttwoargumentsarebound(asinthefirstexample),threeargumentsremainandarethen returnedbya r g s .


( a r g s ) canbeusedasanargumenttoabuiltinoruserdefinedfunctioncall,butitshouldnotbeusedasanargumenttoanother

macro,inwhichcase( a r g s ) wouldnotbeevaluatedandwouldthereforehavethewrongcontentsinthenewmacroenvironment.

array
syntax:(arrayintn1[intn2...][listinit]) Createsanarraywithintn1elements,optionallyinitializingitwiththecontentsoflistinit.Uptosixteendimensionsmaybe specifiedformultidimensionalarrays. Internally,newLISPbuildsmultidimensionalarraysbyusingarraysastheelementsofanarray.newLISParraysshouldbeused wheneverrandomindexingintoalargelistbecomestooslow.Notalllistfunctionsmaybeusedonarrays.Foramoredetailed discussion,seethechapteronarrays.
( a r r a y5 ) ( n i ln i ln i ln i ln i l )

( a r r a y5( s e q u e n c e1 5 ) ) ( 12345 ) ( a r r a y1 0' ( 12 ) ) ( 1212121212 )

Arrayscanbeinitializedwithobjectsofanytype.Iffewerinitializersthanelementsareprovided,thelistisrepeateduntilall elementsofthearrayareinitialized.
( s e t' m y a r r a y( a r r a y34( s e q u e n c e11 2 ) ) ) ( ( 1234 )( 5678 )( 91 01 11 2 ) )

Arraysaremodifiedandaccessedusingmostofthesamefunctionsusedformodifyinglists:
( s e t f( m y a r r a y23 )9 9 )9 9 ) m y a r r a y( ( 1234 )( 5678 )( 91 01 19 9 ) ) ( s e t f( m y a r r a y11 )" h e l l o " ) " h e l l o " m y a r r a y( ( 1234 )( 5" h e l l o "78 )( 91 01 19 9 ) ) ( s e t f( m y a r r a y1 )' ( abcd ) )( abcd ) m y a r r a y( ( 1234 )( abcd )( 91 01 19 9 ) ) ( n t h1m y a r r a y ) ( abcd ) ;a c c e s saw h o l er o w

; ;u s ei m p l i c i ti n d e x i n ga n ds l i c i n go na r r a y s ( m y a r r a y1 ) ( abcd )

( m y a r r a y01 ) 4 ( 2m y a r r a y ) ( ( 91 01 19 9 ) )

( 32m y a r r a y ) ( ( 1234 )( abcd ) )

Caremustbetakentouseanarraywhenreplacingawholerow. arraylistcanbeusedtoconvertarraysbackintolists:
( a r r a y l i s tm y a r r a y ) ( ( 1234 )( abcd )( 1239 9 ) )

Toconvertalistbackintoanarray,applyflattothelist:
( s e t' a L i s t' ( ( 12 )( 34 ) ) ) ( ( 12 )( 34 ) )

( s e t' a A r r a y( a r r a y22( f l a ta L i s t ) ) ) ( ( 12 )( 34 ) )

Thearray?functioncanbeusedtocheckifanexpressionisanarray:
( a r r a y ?m y a r r a y ) t r u e

( a r r a y ?( a r r a y l i s tm y a r r a y ) ) n i l

Whenserializingarraysusingthefunctionsourceorsave,thegeneratedcodeincludesthea r r a y statementnecessarytocreatethem. Thisway,variablescontainingarraysarecorrectlyserializedwhensavingwithsaveorcreatingsourcestringsusingsource.


( s e t' m y a r r a y( a r r a y34( s e q u e n c e11 2 ) ) ) ( s a v e" a r r a y . l s p "' m y a r r a y ) ; ;c o n t e n t so ff i l ea r r a y l s p; ; ( s e t' m y a r r a y( a r r a y34( f l a t' ( ( 1234 ) ( 5678 ) ( 91 01 11 2 ) ) ) ) )

arraylist

syntax:(arraylistarray) Returnsalistconversionfromarray,leavingtheoriginalarrayunchanged:
( s e t' m y a r r a y( a r r a y34( s e q u e n c e11 2 ) ) ) ( ( 1234 )( 5678 )( 91 01 11 2 ) ) ( s e t' m y l i s t( a r r a y l i s tm y a r r a y ) ) ( ( 1234 )( 5678 )( 91 01 11 2 ) ) ( l i s t( a r r a y ?m y a r r a y )( l i s t ?m y l i s t ) ) ( t r u et r u e )

array?
syntax:(array?exp) Checksifexpisanarray:
( s e t' M( a r r a y34( s e q u e n c e14 ) ) ) ( ( 1234 )( 1234 )( 1234 ) ) ) ( a r r a y ?M ) t r u e

( a r r a y ?( a r r a y l i s tM ) ) n i l

asin
syntax:(asinnumradians) Calculatesthearcsinefunctionfromthenumberinnumradiansandreturnstheresult.
( a s i n1 ) 1 . 5 7 0 7 9 6 3 2 7 ( s i n( a s i n1 ) )1

asinh
syntax:(asinhnumradians) Calculatestheinversehyperbolicsineofnumradians,thevaluewhosehyperbolicsineisnumradians.
( a s i n h2 ) 1 . 4 4 3 6 3 5 4 7 5 ( s i n h( a s i n h2 ) ) 2

assoc
syntax:(assocexpkeylistalist) syntax:(assoclistexpkeylistalist)

Inthefirstsyntaxthevalueofexpkeyisusedtosearchlistalistforamemberlistwhosefirstelementmatchesthekeyvalue.If found,thememberlistisreturnedotherwise,theresultwillben i l .
( a s s o c1' ( ( 34 )( 12 ) ) ) ( 12 ) ( s e t' d a t a' ( ( a p p l e s1 2 3 )( b a n a n a s1 2 34 5 )( p e a r s7 ) ) ) ( a s s o c' b a n a n a sd a t a ) ( b a n a n a s1 2 34 5 ) ( a s s o c' o r a n g e sd a t a ) n i l

Togetherwithsetfa s s o c canbeusedtochangeanassociation.
( s e t f( a s s o c' p e a r sd a t a )' ( p e a r s8 ) ) d a t a ( ( a p p l e s1 2 3 )( b a n a n a s1 2 34 5 )( p e a r s8 ) )

Inthesecondsyntaxmorethenonekeyexpressionscanbespecifiedtosearchinnested,multilevelassociationlists:
( s e t' p e r s o n s' ( ( i d 0 0 1( n a m e" A n n e " )( a d d r e s s( c o u n t r y" U S A " )( c i t y" N e wY o r k " ) ) ) ( i d 0 0 2( n a m e" J e a n " )( a d d r e s s( c o u n t r y" F r a n c e " )( c i t y" P a r i s " ) ) ) ) ) ( a s s o c' ( i d 0 0 1a d d r e s s )p e r s o n s )( a d d r e s s( c o u n t r y" U S A " )( c i t y" N e wY o r k " ) ) ( a s s o c' ( i d 0 0 1a d d r e s sc i t y )p e r s o n s )( c i t y" N e wY o r k " )

ThelistinlistaListcanbeacontextwhichwillbeinterpretedasitsdefaultfunctor.Thiswayverybiglistscanbepassedby referenceforspeedieraccessandlessmemoryusage:
( s e t' p e r s o n s : p e r s o n s' ( ( i d 0 0 1( n a m e" A n n e " )( a d d r e s s( c o u n t r y" U S A " )( c i t y" N e wY o r k " ) ) ) ( i d 0 0 2( n a m e" J e a n " )( a d d r e s s( c o u n t r y" F r a n c e " )( c i t y" P a r i s " ) ) ) ) ) ( d e f i n e( g e t c i t yd bi d ) ( l a s t( a s s o c( l i s ti d' a d d r e s s' c i t y )d b) ) ) ( g e t c i t yp e r s o n s' i d 0 0 1 )" N e wY o r k "

Formakingreplacementsinassociationlists,usethesetftogetherwiththea s s o c function.Thelookupfunctionisusedtoperform associationlookupandelementextractioninonestep.

atan
syntax:(atannumradians) Thearctangentofnumradiansiscalculatedandreturned.
( a t a n1 ) 0 . 7 8 5 3 9 8 1 6 3 4 ( t a n( a t a n1 ) ) 1

atan2
syntax:(atan2numYradiansnumXradians) Thea t a n 2 functioncomputestheprincipalvalueofthearctangentofY/Xinradians.Itusesthesignsofbothargumentsto determinethequadrantofthereturnvalue.a t a n 2 isusefulforconvertingCartesiancoordinatesintopolarcoordinates.

( a t a n 211 ) ( d i v( a c o s0 )( a t a n 211 ) ) ( a t a n 201 ) ( =( a t a n 212 )( a t a n( d i v12 ) ) )

0 . 7 8 5 3 9 8 1 6 3 4 2 3 . 1 4 1 5 9 2 6 5 4 t r u e

atanh
syntax:(atanhnumradians) Calculatestheinversehyperbolictangentofnumradians,thevaluewhosehyperbolictangentisnumradians.Iftheabsolutevalue ofnumradiansisgreaterthan1,a t a n h returnsN a N ifitisequalto1,a t a n h returnsinfinity.
( a t a n h0 . 5 )0 . 5 4 9 3 0 6 1 4 4 3 ( t a n h( a t a n h0 . 5 ) )0 . 5 ( a t a n h1 . 1 )N a N ( a t a n h1 )i n f

atom?
syntax:(atom?exp) Returnst r u e ifthevalueofexpisanatom,otherwisen i l .Anexpressionisanatomifitevaluatestonil,true,aninteger,afloat,a string,asymboloraprimitive.Lists,lambdaorlambdamacroexpressions,andquotedexpressionsarenotatoms.
( a t o m ?' ( 123 ) ) n i l ( a n d( a t o m ?1 2 3 ) ( a t o m ?" h e l l o " ) ( a t o m ?' f o o ) ) t r u e ( a t o m ?' ' f o o ) n i l

base64dec
syntax:(base64decstr) TheBASE64stringinstrisdecoded.NotethatstrisnotverifiedtobeavalidBASE64string.Thedecodedstringisreturned.
( b a s e 6 4 d e c" S G V s b G 8 g V 2 9 y b G Q = " ) " H e l l oW o r l d "

Forencoding,usethebase64encfunction. newLISP'sBASE64handlingisderivedfromroutinesfoundintheUnixcurlutilityandconformstotheRFC4648standard.

base64enc
syntax:(base64encstr[boolflag]) ThestringinstrisencodedintoBASE64format.Thisformatencodesgroupsof3*8=24inputbitsinto4*8=32outputbits, whereeach8bitoutputgrouprepresents6bitsfromtheinputstring.The6bitsareencodedinto64possibilitiesfromthelettersA

Zandazthenumbers09andthecharacters+(plussign)and/(slash).The=(equalssign)isusedasafillerinunused3to4 bytetranslations.Thisfunctionishelpfulforconvertingbinarycontentintoprintablecharacters. Withouttheoptionalboolflagparametertheemptystring" " isencodedinto" = = = = " .Ifboolflagevaluatestot r u e ,theempty string" " istranslatedinto" " .Bothtranslationsresultin" " whenusingbase64dec. Theencodedstringisreturned. BASE64encodingisusedwithmanyInternetprotocolstoencodebinarydataforinclusionintextbasedmessages(e.g.,XML RPC).
( b a s e 6 4 e n c" H e l l oW o r l d " ) " S G V s b G 8 g V 2 9 y b G Q = " ( b a s e 6 4 e n c" " ) ( b a s e 6 4 e n c" "t r u e ) " = = = = " " "

Notethatb a s e 6 4 e n c doesnotinsertcarriagereturn/linefeedpairsinlongerBASE64sequencesbutinsteadreturnsapure BASE64encodedstring. Fordecoding,usethebase64decfunction. newLISP'sBASE64handlingisderivedfromroutinesfoundintheUnixcurlutilityandconformstotheRFC4648standard.

bayesquery
syntax:(bayesquerylistLcontextD[boolchain[boolprobs]]) Takesalistoftokens(listL)andatraineddictionary(contextD)andreturnsalistofthecombinedprobabilitiesofthetokensinone category(AorMc)versusacategory(B)againstallothercategories(Mi).AlltokensinlistLshouldoccurincontextD.When usingthedefaultR.A.FisherChimode,nonexistenttokenswillskewresultstowardequalprobabilityinallcategories. NonexistingtokenswillnothaveanyinfluenceontheresultwhenusingthetrueChainBayesianmodewithboolchainsetto t r u e .Theoptionallastflag,boolprobs,indicateswhetherfrequenciesorprobabilityvaluesareusedinthedataset.Thebayestrain functionistypicallyusedtogenerateadataset'sfrequencies. Tokenscanbestringsorsymbols.Ifstringsareused,theyareprependedwithanunderscorebeforebeinglookedupincontextD.If bayestrainwasusedtogeneratecontextD'sfrequencies,theunderscorewasautomaticallyprependedduringthelearningprocess. Dependingontheflagspecifiedinboolprobs,bayesqueryemployseithertheR.A.FisherChimethodofcompounding probabilitiesortheChainBayesianmethod.Bydefault,whennoflagorn i l isspecifiedinboolprobs,theChimethodof compoundingprobabilitiesisused.Whenspecifyingt r u e inboolprobs,theChainBayesianmethodisused. IftheR.A.FisherChimethodisused,thetotalnumberoftokensinthedifferenttrainingset'scategoriesshouldbeequalorsimilar. Unevenfrequenciesincategorieswillskewtheresults. FortwocategoriesAandB,b a y e s q u e r y usesthefollowingformula: p(A|tkn)=p(tkn|A)*p(A)/(p(tkn|A)*p(A)+p(tkn|B)*p(B)) ForNcategories,theformulacanbegeneralizedto: p(Mc|tkn)=p(tkn|Mc)*p(Mc)/sumiN(p(tkn|Mi)*p(Mi)) Theprobabilities(p(Mi)orp(A),alongwithp(B))representtheBayesianpriorprobabilities.p(Mc|tkn)andp(A|tkn)arethe posteriorBayesianprobabilitiesofacategoryormodel.ThisnaiveBayesformuladoesnortakeintoaccountdependenciesbetween differentcategories.

Priorsarehandleddifferently,dependingonwhethertheR.A.FisherChiortheChainBayesianmethodisused.InChainBayesian mode,posteriorsfromonetokencalculationgetthepriorsinthenextcalculation.InthedefaultR.A.Fishermethod,priorsarenot passedonviachaining,butprobabilitiesarecompoundedusingtheChimethod. InChainBayesmode,tokenswithzerofrequencyinonecategorywilleffectivelyputtheprobabilityofthatcategoryto0(zero). Thisalsocausesallposteriorpriorstobesetto0andthecategorytobecompletelysuppressedintheresult.Queriesresultinginzero probabilitiesforallcategoriesyieldNaNvalues. ThedefaultR.A.FisherChimethodislesssensitiveaboutzerofrequenciesandstillmaintainsalowprobabilityforthattoken.This maybeanimportantfeatureinnaturallanguageprocessingwhenusingBayesianstatistics.Imaginethatfivedifferentlanguage corpuscategorieshavebeentrained,butsomewordsoccurringinonecategoryarenotpresentinanother.WhenthepureChain Bayesianmethodisused,asentencecouldneverbeclassifiedintoitscorrectcategorybecausethezerocountofjustoneword tokencouldeffectivelyexcludeitfromthecategorytowhichitbelongs. Ontheotherhand,theChainBayesianmethodoffersexactresultsforspecificproportionsinthedata.WhenusingChainBayesian modefornaturallanguagedata,allzerofrequenciesshouldberemovedfromthetraineddictionaryfirst. Thereturnvalueofb a y e s q u e r y isalistofprobabilityvalues,oneforeachcategory.Followingaretwoexamples:thefirstforthe defaultR.A.Fishermode,thesecondforadatasetprocessedwiththeChainBayesianmethod. Previoustoversion10.3.0thelistofprobabilityvaluesreturnedinFisherChimodewasnormalizedbydividingeachvaluebythe sumofthewholelist.Thisnormalizationhasbeendroppedinversion10.3.0.

R.A.FisherChimethod
Inthefollowingexample,thetwodatasetsarebooksfromProjectGutenberg.Weassumethatdifferentauthorsusecertainwords withdifferentfrequenciesandwanttodetermineifasentenceismorelikelytooccurinoneortheotherauthor'swriting.Asimilar methodisfrequentlyusedtodifferentiatebetweenspamandlegitimateemail.
; ;f r o mP r o j e c tG u t e n b e r g :h t t p : / / w w w . g u t e n b e r g . o r g / c a t a l o g / ; ;T h eA d v e n t u r e so fS h e r l o c kH o l m e s-S i rA r t h u rC o n a nD o y l e ( b a y e s t r a i n( p a r s e( l o w e r c a s e( r e a d f i l e" D o y l e . t x t " ) ) " [ ^ a z ] + "0 )' ( )' D o y l e D o w s o n ) ; ;AC o m e d yo fM a s k s-E r n e s tD o w s o na n dA r t h u rM o o r e ( b a y e s t r a i n' ( )( p a r s e( l o w e r c a s e( r e a d f i l e" D o w s o n . t x t " ) ) " [ ^ a z ] + "0 )' D o y l e D o w s o n ) ( s a v e" D o y l e D o w s o n . l s p "' D o y l e D o w s o n )

Thetwotrainingsetsareloaded,splitintotokens,andprocessedbythebayestrainfunction.Intheend,theD o y l e D o w s o n dictionaryissavedtoafile,whichwillbeusedlaterwiththeb a y e s q u e r y function. Thefollowingcodeillustrateshowb a y e s q u e r y isusedtoclassifyasentenceasDoyleorDowson:


( l o a d" D o y l e D o w s o n . l s p " ) ( b a y e s q u e r y( p a r s e" h ew a sp u t t i n gt h el a s tt o u c h e st oap i c t u r e " ) ' D o y l e D o w s o n ) ( 0 . 9 6 2 4 9 6 3 4 6 90 . 0 3 7 5 0 3 6 5 3 1 ) ( b a y e s q u e r y( p a r s e" i m m e n s ef a c u l t i e sa n de x t r a o r d i n a r yp o w e r so fo b s e r v a t i o n " ) ' D o y l e D o w s o n ) ( 0 . 0 1 4 7 7 4 1 8 1 7 80 . 9 8 5 2 2 5 8 1 8 2 )

ThequeriescorrectlyidentifythefirstsentenceasaDoylesentence,andthesecondoneasaDowsonsentence.

ChainBayesianmethod

ThesecondexampleisfrequentlyfoundinintroductoryliteratureonBayesianstatistics.ItshowstheChainBayesianmethodof usingb a y e s q u e r y onthedataofapreviouslyprocesseddataset:


( s e t' D a t a : t e s t p o s i t i v e' ( 81 8 ) ) ( s e t' D a t a : t e s t n e g a t i v e' ( 27 2 ) ) ( s e t' D a t a : t o t a l' ( 1 09 0 ) )

Adiseaseoccursin10percentofthepopulation.Abloodtestdevelopedtodetectthisdiseaseproducesafalsepositiverateof20 percentinthehealthypopulationandafalsenegativerateof20percentinthesick.Whatistheprobabilityofapersoncarryingthe diseaseaftertestingpositive?


( b a y e s q u e r y' ( t e s t p o s i t i v e )D a t at r u e ) ( 0 . 3 0 7 6 9 2 3 0 7 70 . 6 9 2 3 0 7 6 9 2 3 ) ( b a y e s q u e r y' ( t e s t p o s i t i v et e s t p o s i t i v e )D a t at r u e ) ( 0 . 6 40 . 3 6 ) ( b a y e s q u e r y' ( t e s t p o s i t i v et e s t p o s i t i v et e s t p o s i t i v e )D a t at r u e ) ( 0 . 8 7 6 7 1 2 3 2 8 80 . 1 2 3 2 8 7 6 7 1 2 )

NotethattheBayesianformulasusedassumestatisticalindependenceofeventsfortheb a y e s q u e r y toworkcorrectly. Theexampleshowsthatapersonmusttestpositiveseveraltimesbeforetheycanbeconfidentlyclassifiedassick. CalculatingthesameexampleusingtheR.A.FisherChimethodwillgivelessdistinguishedresults.

Specifyingprobabilitiesinsteadofcounts
Often,dataisalreadyavailableasprobabilityvaluesandwouldrequireadditionalworktoreversethemintofrequencies.Inthelast example,thedatawereoriginallydefinedaspercentages.Theadditionaloptionalboolprobsflagallowsprobabilitiestobeentered directlyandshouldbeusedtogetherwiththeChainBayesianmodeformaximumperformance:
( s e t' D a t a : t e s t p o s i t i v e' ( 0 . 80 . 2 ) ) ( s e t' D a t a : t e s t n e g a t i v e' ( 0 . 20 . 8 ) ) ( s e t' D a t a : t o t a l' ( 0 . 10 . 9 ) ) ( b a y e s q u e r y' ( t e s t p o s i t i v e )D a t at r u et r u e ) ( 0 . 3 0 7 6 9 2 3 0 7 70 . 6 9 2 3 0 7 6 9 2 3 ) ( b a y e s q u e r y' ( t e s t p o s i t i v et e s t p o s i t i v e )D a t at r u et r u e ) ( 0 . 6 40 . 3 6 ) ( b a y e s q u e r y' ( t e s t p o s i t i v et e s t p o s i t i v et e s t p o s i t i v e )D a t at r u et r u e ) ( 0 . 8 7 6 7 1 2 3 2 8 80 . 1 2 3 2 8 7 6 7 1 2 )

Asexpected,theresultsarethesameforprobabilitiesastheyareforfrequencies.

bayestrain
syntax:(bayestrainlistM1[listM2...]symcontextD) Takesoneormorelistsoftokens(M1,M2)fromajointsetoftokens.InnewLISP,tokenscanbesymbolsorstrings(otherdata typesareignored).TokensareplacedinacommondictionaryinsymcontextD,andthefrequencyiscountedforeachtokenin eachcategoryMi.Ifthecontextdoesnotyetexist,itmustbequoted. TheMcategoriesrepresentdatamodelsforwhichsequencesoftokenscanbeclassified(seebayesquery).EachtokeninDisa contentaddressablesymbolcontainingalistofthefrequenciesforthistokenwithineachcategory.Stringtokensareprependedwith an_ (underscore)beforebeingconvertedintosymbols.Asymbolnamedt o t a l iscreatedcontainingthetotalofeachcategory.The

t o t a l symbolcannotbepartofthesymbolspassedasanMicategory.

Thefunctionreturnsalistoftokenfrequenciesfoundinthedifferentcategoriesormodels.
( b a y e s t r a i n' ( AABCC )' ( ABBCCC )' L ) ( 56 ) L : A L : B L : C L : t o t a l ( 21 ) ( 12 ) ( 23 ) ( 56 )

( b a y e s t r a i n' ( " o n e "" t w o "" t w o "" t h r e e " ) ' ( " t h r e e "" o n e "" t h r e e " ) ' ( " o n e "" t w o "" t h r e e " )' S ) ( 433 ) S : _ o n e S : _ t w o S : _ t h r e e S : t o t a l ( 111 ) ( 201 ) ( 121 ) ( 433 )

Thefirstexampleshowstrainingwithtwolistsofsymbols.Thesecondexampleillustrateshowan_ isprependedwhentraining withstrings.


b a y e s t r a i n createssymbolsfromstringsprependinganunderscorecharacter.Thisisthesamewayhashesarecreatedand

contextspopulateswithsymbolsbyb a y e s t r a i n canbeusedlikehashes:
;u s eab a y e s t r a i n e dc o n t e x tn a m e s p a c el i k eah a s hd i c t i o n a r y ( S" t w o " ) ( 201 ) ( S" t h r e e " )( 121 ) ( S )( ( " o n e "( 111 ) )( " t h r e e "( 121 ) )( " t w o "( 201 ) ) )

Notethattheseexamplesarejustfordemonstrationpurposes.Inreality,trainingsetsmaycontainthousandsormillionsofwords, especiallywhentrainingnaturallanguagemodels.Butsmalldatasetsmaybeusedwhenthefrequencyofsymbolsjustdescribe alreadyknownproportions.Inthiscase,itmaybebettertodescribethemodeldatasetexplicitly,withouttheb a y e s t r a i n function:


( s e t' D a t a : t e s t e d p o s i t i v e' ( 81 8 ) ) ( s e t' D a t a : t e s t e d n e g a t i v e' ( 27 2 ) ) ( s e t' D a t a : t o t a l' ( 1 09 0 ) )

Thelastdataarefromapopularexampleusedtodescribethebayesqueryfunctioninintroductorypapersandbooksaboutbayesian networks. Trainingcanbedoneindifferentstagesbyusingb a y e s t r a i n onanexistingtrainedcontextwiththesamenumberofcategories. Thenewsymbolswillbeadded,thencountsandtotalswillbecorrectlyupdated. Traininginmultiplebatchesmaybenecessaryonbigtextcorporaordocumentsthatmustbetokenizedfirst.Thesecorporacanbe tokenizedinsmallportions,thenfedintob a y e s t r a i n inmultiplestages.Categoriescanalsobesingularlytrainedbyspecifyingan emptylistfortheabsentcorpus:


( b a y e s t r a i ns h a k e s p e a r e 1' ( )' d a t a ) ( b a y e s t r a i ns h a k e s p e a r e 2' ( )' d a t a ) ( b a y e s t r a i n' ( )h e m i n g w a y 1' d a t a ) ( b a y e s t r a i n' ( )h e m i n g w a y 2' d a t a ) ( b a y e s t r a i ns h a k e p e a r e r e s th e m i n g w a y r e s t' d a t a ) b a y e s t r a i n willcorrectlyupdatewordcountsandtotals.

Usingb a y e s t r a i n insideacontextotherthanM A I N requiresthetrainingcontextstohavebeencreatedpreviouslywithintheM A I N contextviathecontextfunction.


b a y e s t r a i n isnotonlyusefulwiththebayesqueryfunction,butalsoasafunctionforcountingingeneral.Forinstance,the

resultingfrequenciescouldbeanalyzedusingprobchi2againstanullhypothesisofproportionaldistributionofitemsacross

categories.

begin
syntax:(beginbody) Theb e g i n functionisusedtogroupablockofexpressions.Theexpressionsinbodyareevaluatedinsequence,andthevalueofthe lastexpressioninbodyisreturned.
( b e g i n ( p r i n t" T h i si sab l o c ko f2e x p r e s s i o n s \ n " ) ( p r i n t" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " ) )

Somebuiltinfunctionslikecond,define,doargs,dolist,dostring,dotimes,whenandwhilealreadyallowmultipleexpressionsin theirbodies,butb e g i n isoftenusedinanifexpression. Thesilentfunctionworkslikeb e g i n ,butsuppressesconsoleoutputonreturn.

beta
syntax:(betacumanumb) TheBetafunction,b e t a ,isderivedfromthelogGammag a m m a l n functionasfollows: beta=exp(gammaln(a)+gammaln(b)gammaln(a+b))
( b e t a12 ) 0 . 5

betai
syntax:(betainumxnumanumb) TheIncompleteBetafunction,b e t a i ,equalsthecumulativeprobabilityoftheBetadistribution,b e t a i ,atxinnumx.The cumulativebinomialdistributionisdefinedastheprobabilityofanevent,pev,withprobabilityptooccurkormoretimesinNtrials: pev=Betai(p,k,Nk+1)
( b e t a i0 . 538 ) 0 . 9 4 5 3 1 2 5

Theexamplecalculatestheprobabilityforaneventwithaprobabilityof0.5tooccur3ormoretimesin10trials(8=103+1). TheincompleteBetadistributioncanbeusedtoderiveavarietyofotherfunctionsinmathematicsandstatistics.Seealsothe binomialfunction.

bigint
syntax:(bigintnumber)

syntax:(bigintstring) Afloatingpointorintegernumbergetsconvertedtobigintegerformat.Whenconvertingfromfloatingpoint,roundingerrorsoccur goingbackandforthbetweendecimalandbinaryarithmetic. Astringargumentgetsparsedtoanumberandconvertedtoabiginteger.


( b i g i n t1 2 3 4 5 ) 1 2 3 4 5 L

( b i g i n t1 . 2 3 4 5 6 7 8 9 0 e 3 0 )1 2 3 4 5 6 7 8 8 9 9 9 9 9 9 9 9 5 7 3 6 1 0 0 0 0 0 0 0 0 0 L ( s e t' n u m5 6 7 8 9 0 ) ( b i g i n tn u m ) ( b i g i n t" 5 4 3 2 1 " ) ( b i g i n t" 1 2 3 . 4 5 " ) ( b i g i n t" 1 2 3 h e l l o " ) 5 6 7 8 9 0 L 5 4 3 2 1 L 1 2 3 L 1 2 3 L

SeealsothemanualchapterBiginteger,unlimitedprecisionarithmetic

bigint?
syntax:(bigint?number) Checkifanumberisformattedasabiginteger.
( s e t' x1 2 3 4 5 ) ( s e t' y1 2 3 4 5 L ) ( s e t' z1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 ) ( s e t' p1 . 2 3 4 5 e 2 0 ) ( s e t' q( b i g i n tp ) ) ( b i g i n t ?x ) ( b i g i n t ?y ) ( b i g i n t ?z ) ( b i g i n t ?p ) ( b i g i n t ?q ) n i l t r u e t r u e n i l t r u e

SeealsothemanualchapterBiginteger,unlimitedprecisionarithmetic

bind!
syntax:(bindlistvariableassociations[booleval]) listvariableassociationscontainsanassociationlistofsymbolsandtheirvalues.b i n d setsallsymbolstotheirassociatedvalues. Theassociatedvaluesareevaluatediftheboolevalflagist r u e :
( s e t' l s t' ( ( a( +34 ) )( b" h e l l o " ) ) ) ( b i n dl s t ) a b ( +34 ) " h e l l o " " h e l l o " " h e l l o "

( b i n dl s tt r u e ) a 7

Thereturnvalueofbindisthevalueofthelastassociation.
b i n d isoftenusedtobindassociationlistsreturnedbyunify. ( b i n d( u n i f y' ( pXYa )' ( pYXX ) ) ) X Y a a a

Thiscanbeusedfordestructuring:
( s e t' s t r u c t u r e' ( ( o n e" t w o " )3( f o u r( xyz ) ) ) ) ( s e t' p a t t e r n' ( ( AB )C( DE ) ) ) ( b i n d( u n i f yp a t t e r ns t r u c t u r e ) ) Ao n e B" t w o " C3 Df o u r E( xyz )

unifyreturnsanassociationlistandb i n d bindstheassociations.

binomial
syntax:(binomialintnintkfloatp) Thebinomialdistributionfunctionisdefinedastheprobabilityforaneventtooccurintktimesinintntrialsifthateventhasa probabilityoffloatpandalltrialsareindependentofoneanother: binomial=pow(p,k)*pow(1.0p,nk)*n!/(k!*(nk)!) wherex!isthefactorialofxandpow(x,y)isxraisedtothepowerofy.

( b i n o m i a l1 030 . 5 ) 0 . 1 1 7 1 8 7 5

Theexamplecalculatestheprobabilityforaneventwithaprobabilityof0.5tooccur3timesin10trials.Foracumulated distribution,seethebetaifunction.

bits
syntax:(bitsint[bool]) Transformsanumberininttoastringof1'sand0'soralist,ifboolevaluatestoanythingnotn i l . Instringrepresentationbitsareinhightoloworder.Inlistpresentation1'sand0'sarerepresentedast r u e andn i l andinorder fromthelowesttothehighestbit.Thisallowsdirectindexingandprogramcontrolswitchingontheresult.
( b i t s1 2 3 4 ) " 1 0 0 1 1 0 1 0 0 1 0 "

( i n t( b i t s1 2 3 4 )02 )1 2 3 4 ( b i t s1 2 3 4t r u e ) ( n i lt r u en i ln i lt r u en i lt r u et r u en i ln i lt r u e )

( ( b i t s1 2 3 4t r u e )0 )n i l;i n d e x i n go ft h er e s u l t

intwithabaseof2istheinversefunctiontob i t s .

callback
syntax:(callbackintindexsymfunction) syntax:(callbacksymfunctionstrreturntype[str_param_type...]) syntax:(callbacksymfunction) Inthefirstsimplec a l l b a c k syntaxuptosixteen(0to15)callbackfunctionsforuptoeightparameterscanberegisteredwith importedlibraries.Thec a l l b a c k functionreturnsaprocedureaddressthatinvokesauserdefinedfunctioninsymfunction.The followingexampleshowstheusageofcallbackfunctionswhenimportingtheOpenGLgraphicslibrary: Ifmorethansixteencallbackfunctionsarerequired,slotsmustbereassignedtoadifferentcallbackfunction.
. . . ( d e f i n e( d r a w ) ( g l C l e a rG L _ C O L O R _ B U F F E R _ B I T) ( g l R o t a t e dr o t x0 . 01 . 00 . 0 ) ( g l R o t a t e dr o t y1 . 00 . 00 . 0 ) ( g l u t W i r e T e a p o t0 . 5 ) ( g l u t S w a p B u f f e r s ) ) ( d e f i n e( k e y b o a r dk e yxy ) ( i f( =( &k e y0 x F F )2 7 )( e x i t ) );e x i tp r o g r a mw i t hE S C ( p r i n t l n" k e y : "( &k e y0 x F F )"x : "x "y : "y ) ) ( d e f i n e( m o u s eb u t t o ns t a t exy ) ( i f( =s t a t e0 ) ( g l u t I d l e F u n c0 );s t o pr o t a t i o no nb u t t o np r e s s ( g l u t I d l e F u n c( c a l l b a c k4' r o t a t i o n ) ) ) ( p r i n t l n" b u t t o n :"b u t t o n"s t a t e : "s t a t e"x : "x"y : "y ) ) ( g l u t D i s p l a y F u n c( c a l l b a c k0' d r a w ) ) ( g l u t K e y b o a r d F u n c( c a l l b a c k1' k e y b o a r d ) ) ( g l u t M o u s e F u n c( c a l l b a c k2' m o u s e ) ) . . .

Theaddressreturnedbyc a l l b a c k isregisteredwiththeGlutlibrary.Theabovecodeisasnippetfromthefileo p e n g l d e m o . l s p , inthee x a m p l e s / directoryofthesourcedistributionofnewLISPandcanalsobedownloadedfrom newlisp.org/downloads/OpenGL. Inthesecondextendedc a l l b a c k syntaxtypespecifiersareusedtodescribethefunctionsreturnandparametervaluetypeswhen thefunctioniscalled.Anunlimitednumberofcallbackfunctionscanberegisteredwiththesecondsyntax,andreturnvaluesare passedbacktothecallingfunction.ThesymbolinsymfunctioncontainsanewLISPdefinedfunctionusedasacallbackfunction callablefromaCprogram. Inthethirdsyntaxc a l l b a c k returnsapreviouslyreturnedCcallableaddressforthatsymbol. Whilethefirstsimplec a l l b a c k syntaxonlyhandlesintegersandpointervalues,c a l l b a c k intheexpandedsyntaxcanalsohandle simpleanddoubleprecisionfloatingpointnumberspassedinanoutofthec a l l b a c k function. Boththesimpleandextendedsyntaxcanbemixedinsidethesameprogram. Thefollowingexampleshowstheimportoftheq s o r t Clibraryfunction,whichtakesasoneofit'sargumentstheaddressofa comparisonfunction.ThecomparisonfunctioninthiscaseiswritteninnewLISPandcalledintobytheimportedq s o r t function:
;Cv o i dq s o r t ( . . . )t a k e sa ni n t e g e ra r r a yw i t hn u m b e ra n dw i d t h ;o fa r r a ye l e m e n t sa n dap o i n t e rt ot h ec o m p a r i s o nf u n c t i o n ( i m p o r t" l i b c . d y l i b "" q s o r t "" v o i d "" v o i d * "" i n t "" i n t "" v o i d * " ) ( s e t' r l i s t' ( 2312443303 ) )

;p a c kt h el i s ti n t oa nCr e a d a b l e3 2 b i ti n t e g e ra r r a y ( s e t' c a r r a y( p a c k( d u p" l d"1 0 )r l i s t ) ) ;t h ec o m p a r i s o nc a l l b a c kf u n c t i o nr e c e i v e sp o i n t e r st oi n t e g e r s ( d e f i n e( c m pab ) ( -( g e t i n ta )( g e t i n tb ) ) ) ;g e n e r a t eaCc a l l a b l ea d d r e s sf o rc m p ( s e t' f u n c( c a l l b a c k' c m p" i n t "" v o i d * "" v o i d * " ) ) ;s o r tt h ec a r r a y ( q s o r tc a r r a y1 04f u n c ) ;u n p a c kt h es o r t e da r r a yi n t oaL I S Pl i s t ( u n p a c k( d u p" l d "1 0 )c a r r a y ) ( 0122333344 )

Astypespecifiersthesamestringtagscanbeusedasintheimportfunction.Allpointertypesarepassedasnumbersinandoutof thec a l l b a c k function.Thefunctionsgetchar,getint,getlongandgetstringcanbeusedtoextractnumbersofdifferentprecision fromparameters.Usepackandunpacktoextractdatafrombinarybuffersandstructures. NotethatnewLISPasalreadyafastbuiltinsortfunction.

case
syntax:(caseexpswitch(exp1body1)[(exp2body2)...]) Theresultofevaluatingexpswitchiscomparedtoeachoftheunevaluatedexpressionsexp1,exp2,.Ifamatchisfound,the correspondingexpressionsinbodyareevaluated.Theresultofthelastbodyexpressionisreturnedastheresultfortheentirec a s e expression.
( d e f i n e( t r a n s l a t en ) ( c a s en ( 1" o n e " ) ( 2" t w o " ) ( 3" t h r e e " ) ( 4" f o u r " ) ( t r u e" C a n ' tt r a n s l a t et h i s " ) ) ) ( t r a n s l a t e3 ) " t h r e e " ( t r a n s l a t e1 0 ) " C a n ' tt r a n s l a t et h i s "

Theexampleshowshow,ifnomatchisfound,thelastexpressioninthebodyofac a s e functioncanbeevaluated.

catch
syntax:(catchexp) syntax:(catchexpsymbol) Inthefirstsyntax,c a t c h willreturntheresultoftheevaluationofexportheevaluatedargumentofathrowexecutedduringthe evaluationofexp:
( c a t c h( d o t i m e s( x1 0 0 0 ) ( i f( =x5 0 0 )( t h r o wx ) ) ) ) 5 0 0

Thisformisusefulforbreakingoutofiterationloopsandforforcinganearlyreturnfromafunctionorexpressionblock:
( d e f i n e( f o ox )

( i fc o n d i t i o n( t h r o w1 2 3 ) ) 4 5 6 ) ; ;i fc o n d i t i o ni st r u e ( c a t c h( f o op ) ) 1 2 3 ; ;i fc o n d i t i o ni sn o tt r u e ( c a t c h( f o op ) ) 4 5 6

Inthesecondsyntax,c a t c h evaluatestheexpressionexp,storestheresultinsymbol,andreturnst r u e .Ifanerroroccursduring evaluation,c a t c h returnsn i l andstorestheerrormessageinsymbol.Thisformcanbeusefulwhenerrorsareexpectedasanormal potentialoutcomeofafunctionandaredealtwithduringprogramexecution.


( c a t c h( f u n c34 )' r e s u l t ) n i l r e s u l t " E R R :i n v a l i df u n c t i o ni nf u n c t i o nc a t c h:( f u n c34 ) " ( c o n s t a n t' f u n c+ ) +< 4 0 6 8 A 6 > ( c a t c h( f u n c34 )' r e s u l t ) t r u e r e s u l t 7

Whenathrowisexecutedduringtheevaluationofexp,c a t c h willreturnt r u e ,andthet h r o w argumentwillbestoredinsymbol:


( c a t c h( d o t i m e s( x1 0 0 ) ( i f( =x5 0 )( t h r o w" f i n " ) )' r e s u l t ) t r u e r e s u l t " f i n "

Aswellasbeingusedforearlyreturnsfromfunctionsandforbreakingoutofiterationloops(asinthefirstsyntax),thesecond syntaxofc a t c h canalsobeusedtocatcherrors.Thethrowerrorfunctionmaybeusedtothrowuserdefinederrors.

ceil
syntax:(ceilnumber) Returnsthenexthighestintegerabovenumberasafloatingpoint.
( c e i l1 . 5 ) 1 ( c e i l3 . 4 ) 4

Seealsothefloorfunction.

changedir
syntax:(changedirstrpath) Changesthecurrentdirectorytobetheonegiveninstrpath.Ifsuccessful,t r u e isreturnedotherwisen i l isreturned.
( c h a n g e d i r" / e t c " )

Makes/ e t c thecurrentdirectory.

charutf8
syntax:(charstr[intindex[true]]) syntax:(charint) Givenastringargument,extractsthecharacteratintindexfromstr,returningeithertheASCIIvalueofthatcharacterorthe UnicodevalueonUTF8enabledversionsofnewLISP. Ifintindexisomitted,0(zero)isassumed.Ifintidxisfollowedbyabooleant r u e value,thantheindextreatsstrasan8bitbyte arrayinsteadofanarrayofmultibyteUTF8characters. Theemptystringreturnsn i l .Both( c h a r0 ) and( c h a rn i l ) willreturn" \ 0 0 0 " . SeeIndexingelementsofstringsandlists. Givenanintegerargument,c h a r returnsastringcontainingtheASCIIcharacterwithvalueint. OnUTF8enabledversionsofnewLISP,thevalueinintistakenasUnicodeandaUTF8characterisreturned.
( c h a r" A B C " ) ( c h a r" A B C "1 ) ( c h a r" A B C "1 ) ( c h a r" B " ) ( c h a r" " ) ( c h a r" "1t r u e ) ( c h a r6 5 ) " A " ( c h a r6 6 ) " B " ( c h a r( c h a r6 5 ) ) 6 5 ;t w oi n v e r s ea p p l i c a t i o n s 6 5 ;A S C I Ic o d ef o r" A " 6 6 ;A S C I Ic o d ef o r" B " 6 7 ;A S C I Ic o d ef o r" C " 6 6 ;A S C I Ic o d ef o r" B " 9 3 7;U T F 8c o d ef o r" " 1 6 9;b y t ev a l u ea to f f s e t1

( m a pc h a r( s e q u e n c e12 5 5 ) ) ;r e t u r n sc u r r e n tc h a r a c t e rs e t ;T h eZ e no fU T F 8 ( c h a r( &( c h a r" " )( c h a r" " ) ) ) ;b y@ k o s h _ b o t

choputf8
syntax:(chopstr[intchars]) syntax:(choplist[intelements]) Ifthefirstargumentevaluatestoastring,c h o p returnsacopyofstrwiththelastintcharcharactersomitted.Iftheintcharargument isabsent,onecharacterisomitted.c h o p doesnotalterstr. Ifthefirstargumentevaluatestoalist,acopyoflistisreturnedwithintelementsomitted(sameasforstrings).
( s e t' s t r" n e w L I S P " ) " n e w L I S P " ( c h o ps t r ) " n e w L I S " ( c h o ps t r2 ) " n e w L I " s t r " n e w L I S P " ( s e t' l s t' ( ab( cd )e ) ) ( c h o pl s t ) ( ab( cd ) ) ( c h o pl s t2 ) ( ab ) l s t ( ab( cd )e )

clean
syntax:(cleanexppredicatelist) Thepredicateexppredicateisappliedtoeachelementoflist.Inthereturnedlist,allelementsforwhichexppredicateist r u e are eliminated.
c l e a n workslikefilterwithanegatedpredicate. ( c l e a ns y m b o l ?' ( 12d4fg5h ) ) ( 1245 )

( f i l t e rs y m b o l ?' ( 12d4fg5h ) ) ( dfgh ) ( d e f i n e( b i g ?x )( >x5 ) ) ( l a m b d a( x )( >x5 ) )

( c l e a nb i g ?' ( 11 036451 1 ) ) ( 1345 ) ( c l e a n< =' ( 3460230 ) ) ( 342 ) ( c l e a n( c u r r ym a t c h' ( a* ) )' ( ( a1 0 )( b5 )( a3 )( c8 )( a9 ) ) ) ( ( b5 )( c8 ) )

Thepredicatemaybeabuiltinpredicateorauserdefinedfunctionorlambdaexpression. Forcleaningnumbersfromonelistusingnumbersfromanother,usedifferenceorintersect(withthelistmodeoption). Seealsotherelatedfunctionindex,whichreturnstheindicesoftheremainingelements,andfilter,whichreturnsallelementsfor whichapredicatereturnstrue.

close
syntax:(closeintfile) Closesthefilespecifiedbythefilehandleinintfile.Thehandlewouldhavebeenobtainedfromapreviousopenoperation.If successful,c l o s e returnst r u e otherwisen i l isreturned.
( c l o s e( d e v i c e ) ) t r u e ( c l o s e7 ) t r u e ( c l o s ea H a n d l e ) t r u e

Notethatusingc l o s e ondeviceautomaticallyresetsitto0(zero,thescreendevice).

commandevent
syntax:(commandeventsymeventhandler|funceventhandler) SpecifiesauserdefinedfunctionforpreprocessingthenewLISPcommandlinebeforeitgetsevaluated.Thiscanbeusedtowrite customizedinteractivenewLISPshellsandtotransformHTTPrequestswhenrunninginservermode.
c o m m a n d e v e n t takeseitherasymbolofauserdefinedfunctionoralambdafunction.Theeventhandlerfunctionmustreturna

stringorthecommandlinewillbepasseduntranslatedtonewLISP.

Toonlyforceaprompt,thefunctionshouldreturntheemptystring" " . ThefollowingexamplemakesthenewLISPshellworklikeanormalUnixshellwhenthecommandstartswithaletter.Butstarting thelinewithanopenparenthesisoraspaceinitiatesanewLISPevaluation.


( c o m m a n d e v e n t( f n( s ) ( i f( s t a r t s w i t hs" [ a z A Z ] "0 )( a p p e n d" ! "s )s ) ) )

SeealsotherelatedprompteventwhichcanbeusedforfurthercustomizinginteractivemodebymodifyingthenewLISPprompt. ThefollowingprogramcanbeusedeitherstandaloneorincludedinnewLISP'si n i t . l s p startupfile:


# ! / u s r / b i n / n e w l i s p ;s e tt h ep r o m p tt ot h ec u r r e n td i r e c t o r yn a m e ( p r o m p t e v e n t( f n( c t x )( a p p e n d( r e a l p a t h )" >" ) ) ) ;p r e p r o c e s st h ec o m m a n d l i n e ( c o m m a n d e v e n t( f n( s ) ( i f ( s t a r t s w i t hs" c d " ) ( s t r i n g""( t r u e ?( c h a n g e d i r( l a s t( p a r s es"" ) ) ) ) ) ( s t a r t s w i t hs" [ a z A Z ] "0 ) ( a p p e n d" ! "s ) t r u es ) ) )

InthedefinitionofthecommandlinetranslationfunctiontheUnixcommandc d getsaspecialtreatment,tomakesurethatthe directoryischangedfornewLISPprocesstoo.Thiswaywhenshellingoutwith! andcomingback,newLISPwillmaintainthe changeddirectory. CommandlinesfornewLISPmuststarteitherwithaspaceoranopeningparenthesis.Unixcommandsmuststartatthebeginning oftheline. WhennewLISPisrunninginservermodeeitherusingthec orh t t p option,itreceivesHTTPrequestssimilartothefollowing:
G E T/ i n d e x . h t m l

Orifaqueryisinvolved:
G E T/ i n d e x . c g i ? u s e r i d = j o e & p a s s w o r d = s e c r e t

Afunctionspecifiedbyc o m m a n d e v e n t couldfilterandtransformtheserequestlines,e.g.:discoveringallqueriestryingtoperform CGIusingafileendingin. e x e .Sucharequestwouldbetranslatedintoarequestforanerrorpage:


; ;h t t p d c o n f . l s p ; ; ; ;f i l t e ra n dt r a n s l a t eH T T Pr e q u e s t sf o rn e w L I S P ; ;co rh t t ps e r v e rm o d e s ; ;r e j e c tq u e r yc o m m a n d su s i n gC G Iw i t h. e x ef i l e s ( c o m m a n d e v e n t( f n( s ) ( l e t( r e q u e s ts ) ( w h e n( f i n d" ? "s );i st h i saq u e r y ( s e t' r e q u e s t( f i r s t( p a r s es" ? " ) ) ) ;d i s c o v e ri l l e g a le x t e n s i o ni nq u e r i e s ( w h e n( e n d s w i t hr e q u e s t" . e x e " ) ( s e t' r e q u e s t" G E T/ e r r o r p a g e . h t m l " ) )) r e q u e s t ) ) )

Whenstartingtheservermodewithn e w l i s ph t t p d c o n f . l s pcd 8 0w. / h t t p d o c newLISPwillloadthedefinitionfor c o m m a n d e v e n t forfilteringincomingrequests,andthequery:


G E T/ c m d . e x e ? d i r

Wouldbetranslatedinto:

G E T/ e r r o r p a g e . h t m l

TheexampleshowsatechniquefrequentlyusedinthepastbyspammersonWin32based,badconfiguredwebserverstogain controloverservers.
h t t p d c o n f . l s p filescaneasilybedebuggedloadingthefileintoaninteractivenewLISPsessionandenteringtheHTTPrequests

manually.newLISPwilltranslatethecommandlineanddispatchittothebuiltinwebserver.Theserveroutputwillappearinthe shellwindow. Note,thatthecommandlinelengthaswellasthelinelengthinHTTPheadersislimitedto512charactersfornewLISP.

cond
syntax:(cond(expcondition1body1)[(expcondition2body2)...]) Likei f ,c o n d conditionallyevaluatestheexpressionswithinitsbody.Theexpconditionsareevaluatedinturn,untilsomeexp conditioniisfoundthatevaluatestoanythingotherthann i l oranemptylist( ) .Theresultofevaluatingbodyiisthenreturnedas theresultoftheentirecondexpression.Ifallconditionsevaluateton i l oranemptylist,condreturnsthevalueofthelastcond expression.
( d e f i n e( c l a s s i f yx ) ( c o n d ( ( <x0 )" n e g a t i v e " ) ( ( <x1 0 )" s m a l l " ) ( ( <x2 0 )" m e d i u m " ) ( ( > =x3 0 )" b i g " ) ) ) ( c l a s s i f y1 5 ) ( c l a s s i f y2 2 ) ( c l a s s i f y1 0 0 ) ( c l a s s i f y1 0 ) " m e d i u m " " n i l " " b i g " " n e g a t i v e "

Whenabodynismissing,thevalueofthelastcondexpressionevaluatedisreturned.Ifnoconditionevaluatestot r u e ,thevalueof thelastconditionalexpressionisreturned(i.e.,n i l oranemptylist).


( c o n d( ( +34 ) ) ) 7

Whenusedwithmultiplearguments,thefunctionifbehaveslikec o n d ,exceptitdoesnotneedextraparenthesestoenclosethe conditionbodypairofexpressions.

cons
syntax:(consexp1exp2) Ifexp2evaluatestoalist,thenalistisreturnedwiththeresultofevaluatingexp1insertedasthefirstelement.Ifexp2evaluatesto anythingotherthanalist,theresultsofevaluatingexp1andexp2arereturnedinalist.Notethatthereisnodottedpairin newLISP:consingtwoatomsconstructsalist,notadottedpair.
( c o n s' a' b ) ( c o n s' a' ( bc ) ) ( c o n s( +34 )( *55 ) ) ( c o n s' ( 12 )' ( 34 ) ) ( c o n sn i l1 ) ( c o n s1n i l ) ( c o n s1 ) ( c o n s ) ( ab ) ( abc ) ( 72 5 ) ( ( 12 )34 ) ( n i l1 ) ( 1n i l ) ( 1 ) ( )

UnlikeotherLispsthatreturn( s ) astheresultoftheexpression( c o n s' sn i l ) ,newLISP'sc o n s returns( sn i l ) .InnewLISP, n i l isaBooleanvalueandisnotequivalenttoanemptylist,andanewLISPcellholdsonlyonevalue.


c o n s behavesliketheinverseoperationoffirstandrest(orfirstandlastifthelistisapair): ( c o n s( f i r s t' ( abc ) )( r e s t' ( abc ) ) ) ( abc ) ( c o n s( f i r s t' ( xy ) )( l a s t' ( xy ) ) ) ( xy )

constant!
syntax:(constantsym1exp1[sym2exp2]...) Identicaltosetinfunctionality,c o n s t a n t furtherprotectsthesymbolsfromsubsequentmodification.Asymbolsetwithc o n s t a n t canonlybemodifiedusingthec o n s t a n t functionagain.Whenanattemptismadetomodifythecontentsofasymbolprotected withc o n s t a n t ,newLISPgeneratesanerrormessage.Onlysymbolsfromthecurrentcontextcanbeusedwithc o n s t a n t .This preventstheoverwritingofsymbolsthathavebeenprotectedintheirhomecontext.Thelastexpninitializerisalwaysoptional. Symbolsinitializedwithset,define,ordefinemacrocanstillbeprotectedbyusingthec o n s t a n t function:
( c o n s t a n t' a V a r1 2 3 ) 1 2 3 ( s e t' a V a r9 9 9 ) E R R :s y m b o li sp r o t e c t e di nf u n c t i o ns e t :a V a r ( d e f i n e( d o u b l ex )( +xx ) ) ( c o n s t a n t' d o u b l e ) ; ;e q u i v a l e n tt o ( c o n s t a n t' d o u b l e( f n( x )( +xx ) ) )

Thefirstexampledefinesaconstant,a V a r ,whichcanonlybechangedbyusinganotherc o n s t a n t statement.Thesecondexample protectsd o u b l e frombeingchanged(exceptbyc o n s t a n t ).BecauseafunctiondefinitioninnewLISPisequivalenttoan assignmentofalambdafunction,bothstepscanbecollapsedintoone,asshowninthelaststatementline.Thiscouldbean importanttechniqueforavoidingprotectionerrorswhenafileisloadedmultipletimes. Thelastvaluetobeassignedcanbeomitted.c o n s t a n t returnsthecontentsofthelastsymbolsetandprotected. Builtinfunctionscanbeassignedtosymbolsortothenamesofotherbuiltinfunctions,effectivelyredefiningthemasdifferent functions.Thereisnoperformancelosswhenrenamingfunctions.
( c o n s t a n t' s q u a r e r o o ts q r t ) s q r t< 4 0 6 C 2 E > ( c o n s t a n t' +a d d ) a d d< 4 0 6 8 A 6 > s q u a r e r o o t willbehavelikes q r t .The+ (plussign)isredefinedtousethemixedtypefloatingpointmodeofa d d .The

hexadecimalnumberdisplayedintheresultisthebinaryaddressofthebuiltinfunctionandvariesondifferentplatformsandOSes.

context
syntax:(context[symcontext]) syntax:(contextsymcontextstr|sym[expvalue]) Inthefirstsyntax,c o n t e x t isusedtoswitchtoadifferentcontextnamespace.SubsequentloadsofnewLISPsourceorfunctions likeevalstringandsymwillputnewlycreatedsymbolsandfunctiondefinitionsinthenewcontext.

Ifthecontextstillneedstobecreated,thesymbolforthenewcontextshouldbespecified.Whennoargumentispassedtoc o n t e x t , thenthesymbolforthecurrentcontextisreturned. Becausecontextsevaluatetothemselves,aquoteisnotnecessarytoswitchtoadifferentcontextifthatcontextalreadyexists.


( c o n t e x t' G R A P H ) ;c r e a t e/s w i t c hc o n t e x tG R A P H

( d e f i n e( f o o d r a wxyz ) ;f u n c t i o nr e s i d e si nG R A P H ( ) ) ( s e t' v a r1 2 3 4 5 ) ( s y m b o l s ) ( f o o d r a wv a r ) ;G R A P Hh a sn o wt w os y m b o l s ( c o n t e x tM A I N ) ( p r i n tG R A P H : v a r )1 2 3 4 5 ( G R A P H : f o o d r a w1 02 03 0 ) ( s e t' G R A P H : v a r6 7 8 9 ) ;s w i t c hb a c kt oM A I N( q u o t en o tr e q u i r e d ) ;c o n t e n t so fs y m b o li nG R A P H ;e x e c u t ef u n c t i o ni nG R A P H ;a s s i g nt oas y m b o li nG R A P H

Ifacontextsymbolisreferredtobeforethecontextexists,thecontextwillbecreatedimplicitly.
( s e t' p e r s o n : a g e0 ) ;n on e e dt oc r e a t ec o n t e x tf i r s t ( s e t' p e r s o n : a d d r e s s" " ) ;u s e f u lf o rq u i c k l yd e f i n i n gd a t as t r u c t u r e s

Contextscanbecopied:
( n e wp e r s o n' J o h n D o e ) J o h n D o e ( s e t' J o h n D o e : a g e9 9 )

Contextscanbereferredtobyavariable:
( s e t' h u m a nJ o h n D o e ) h u m a n : a g e 9 9 ( s e t' h u m a n : a d d r e s s" 1M a i nS t r e e t " ) J o h n D o e : a d d r e s s " 1M a i nS t r e e t "

Anevaluatedcontext(noquote)canbegivenasanargument:
>( c o n t e x t' F O O ) F O O F O O >( c o n t e x tM A I N ) M A I N >( s e t' o l dF O O ) F O O >( c o n t e x t' B A R ) B A R B A R >( c o n t e x tM A I N : o l d ) F O O F O O >

Ifanidentifierwiththesamesymbolalreadyexists,itisredefinedtobeacontext. Symbolswithinthecurrentcontextarereferredtosimplybytheirnames,asarebuiltinfunctionsandspecialsymbolsliken i l and t r u e .Symbolsoutsidethecurrentcontextarereferencedbyprefixingthesymbolnamewiththecontextnameanda: (colon).To quoteasymbolinadifferentcontext,prefixthecontextnamewitha' (singlequote). Withinagivencontext,symbolsmaybecreatedwiththesamenameasbuiltinfunctionsorcontextsymbolsinMAIN.This overwritesthesymbolsinMAINwhentheyareprefixedwithacontext:


( c o n t e x t' C T X ) ( d e f i n e( C T X : n e wv a r ) ( ) ) ( c o n t e x t' M A I N )

C T X : n e w willoverwritenewinMAIN.

Inthesecondsyntax,c o n t e x t canbeusedtocreatesymbolsinanamespace.Notethatthisshouldnotbeusedforcreatinghashes ordictionaries.Forashorter,moreconvenientmethodtousenamespacesashashlikedictionaries,seethechapterHashfunctions anddictionaries.


; ;c r e a t eas y m b o la n ds t o r ed a t ai ni t ( c o n t e x t' C t x" a b c "1 2 3 ) 1 2 3 ( c o n t e x t' C t x' x y z9 9 9 ) 9 9 9 ; ;r e t r i e v ec o n t e n t sf r o m ( c o n t e x t' C t x" a b c " ) ( c o n t e x t' C t x' x y z ) C t x : a b c C t x : x y z s y m b o l 1 2 3 9 9 9 1 2 3 9 9 9

Thefirstthreestatementscreateasymbolandstoreavalueofanydatatypeinside.Thefirststatementalsocreatesthecontext namedC t x .Whenasymbolisspecifiedforthename,thenameistakenfromthesymbolandcreatesasymbolwiththesamename inthecontextC t x . SymbolscancontainspacesoranyotherspecialcharactersnottypicallyallowedinnewLISPsymbolsbeingusedasvariable names.Thissecondsyntaxofc o n t e x t onlycreatesthenewsymbolandreturnsthevaluecontainedinit.Itdoesnotswitchtothe newnamespace.

context?
syntax:(context?exp) syntax:(context?expstrsym) Inthefirstsyntax,context?isapredicatethatreturnst r u e onlyifexpevaluatestoacontextotherwise,itreturnsn i l .
( c o n t e x t ?M A I N ) t r u e ( s e t' x1 2 3 ) ( c o n t e x t ?x ) n i l ( s e t' F O O : q" h o l a " ) " h o l a " ( s e t' c t xF O O ) ( c o n t e x t ?c t x ) t r u e ;c t xc o n t a i n sc o n t e x tf o o

Thesecondsyntaxchecksfortheexistenceofasymbolinacontext.Thesymbolisspecifiedbyitsnamestringinstrsym.
( c o n t e x t ?F O O" q " ) t r u e ( c o n t e x t ?F O O" p " ) n i l

Usecontexttochangeandcreatenamespacesandtocreatehashsymbolsincontexts.

copy
syntax:(copyexp) Makeacopyfromevaluatingexpressioninexp.Somebuiltinfunctionsaredestructive,changingtheoriginalcontentsofalist, arrayorstringtheyareworkingon.Withc o p y theirbehaviorcanbemadenondestructive.
( s e t' a L i s t' ( abcdef ) ) ( r e p l a c e' c( c o p ya L i s t ) )( abdef )

a L i s t( abcdef ) ( s e t' s t r" n e w L I S P " )" n e w L I S P " ( r o t a t e( c o p ys t r ) )" P n e w L I S " s t r" n e w L I S P "

Usingc o p y thefunctionsreplaceandrotatearepreventedfromchangingthedata.Amodifiedversionofthedataisreturned.

copyfile
syntax:(copyfilestrfromnamestrtoname) Copiesafilefromapathfilenamegiveninstrfromnametoapathfilenamegiveninstrtoname.Returnst r u e ifthecopywas successfulorn i l ,ifthecopywasunsuccessful.
( c o p y f i l e" / h o m e / m e / n e w l i s p / d a t a . l s p "" / t m p / d a t a . l s p " )

corr
syntax:(corrlistvectorXlistvectorY) CalculatesthePearsonproductmomentcorrelationcoefficientasameasureofthelinearrelationshipbetweenthetwovariablesin listvectorXandlistvectorY.Bothlistsmustbeofsamelength.
c o r r returnsalistcontainingthefollowingvalues:

name description r Correlationcoefficient b0 Regressioncoefficientoffset b1 Regressioncoefficientslope t df p tstatisticforsignificancetesting Degreesoffreedomfort Twotailedprobabilityoftunderthenullhypothesis

( s e t' s t u d y t i m e' ( 9 01 0 01 3 01 5 01 8 02 0 02 2 03 0 03 5 04 0 0 ) ) ( s e t' t e s t e r r o r s' ( 2 52 82 02 01 51 21 31 086 ) ) ( c o r rs t u d y t i m et e s t e r r o r s )( 0 . 9 2 62 9 . 2 4 10 . 0 6 46 . 9 4 480 . 0 0 0 1 1 9 0 )

Thenegativecorrelationof0 . 9 2 6 betweenstudytimeandtesterrorsishighlysignificantwithatwotailedp ofabout0 . 0 0 0 1 underthenullhypothesis. Theregressioncoefficientsb 0=2 9 . 2 4 1 andb 1=0 . 0 6 4 canbeusedtoestimatevaluesoftheYvariable(testerrors)from valuesinX(studytime)usingtheequationY = b 0+b 1*X .

cos
syntax:(cosnumradians) Calculatesthecosineofnumradiansandreturnstheresult.
( c o s1 ) 0 . 5 4 0 3 0 2 3 0 5 9 ( s e t' p i( m u l2( a c o s0 ) ) ) 3 . 1 4 1 5 9 2 6 5 4 ( c o sp i ) 1

cosh
syntax:(coshnumradians) Calculatesthehyperboliccosineofnumradians.Thehyperboliccosineisdefinedmathematicallyas:(exp(x)+exp(x))/2.An overflowtoi n f mayoccurifnumradiansistoolarge.
( c o s h1 ) 1 . 5 4 3 0 8 0 6 3 5 ( c o s h1 0 ) 1 1 0 1 3 . 2 3 2 9 2 ( c o s h1 0 0 0 ) i n f ( =( c o s h1 )( d i v( a d d( e x p1 )( e x p1 ) )2 ) ) t r u e

count
syntax:(countlist1list2) Countselementsoflist1inlist2andreturnsalistofthosecounts.
( c o u n t' ( 123 )' ( 3214231122 ) ) ( 342 ) ( c o u n t' ( za )' ( zdzbazya ) ) ( 32 ) ( s e t' l s t( e x p l o d e( r e a d f i l e" m y F i l e . t x t " ) ) ) ( s e t' l e t t e r c o u n t s( c o u n t( u n i q u el s t )l s t ) )

Thesecondexamplecountsalloccurrencesofdifferentlettersinm y F i l e . t x t . Thefirstlistinc o u n t ,whichspecifiestheitemstobecountedinthesecondlist,shouldbeunique.Foritemsthatarenotunique, onlythefirstinstancewillcarryacountallotherinstanceswilldisplay0 (zero).

cpymem
syntax:(cpymemintfromaddressinttoaddressintbytes) Copiesintbytesofmemoryfromintfromaddresstointtoaddress.Thisfunctioncanbeusedfordirectmemorywriting/readingor forhackingnewLISPinternals(e.g.,typebitsinnewLISPcells,orbuildingfunctionswithbinaryexecutablecodeonthefly). NotethatthisfunctionshouldonlybeusedwhenfamiliarwithnewLISPinternals.c p y m e m cancrashthesystemormakeitunstable ifusedincorrectly.
( s e t' s" 0 1 2 3 4 5 6 7 8 9 " )

( c p y m e m" x x x "( +( a d d r e s ss )5 )3 ) s " 0 1 2 3 4 x x x 8 9 " )

Theexamplecopiesastringdirectlyintoastringvariable. Thefollowingexamplecreatesanewfunctionfromscratch,runsapieceofbinarycode,andaddsuptwonumbers.Thisassembly languagesnippetshowsthex86(IntelCPU)codetoadduptwonumbersandreturntheresult:


5 5 p u s he b p 8 BE C m o v e b p ,e s p 8 B4 50 8m o v e a x ,[ e b p + 0 8 ] 0 34 50 Ca d d e a x ,[ e b p + 0 c ] 5 D p o p e b p C 3 r e t ;f o rW i n 3 2 / s t d c a l lc h a n g el a s tl i n e C 20 80 0r e t

ThebinaryrepresentationisattachedtoanewfunctioncreatedinnewLISP:
( s e t' f o o c o d e( a p p e n d ( p a c k" b b b b b b b b b b "0 x 5 50 x 8 B0 x E C0 x 8 B0 x 4 50 x 0 80 x 0 30 x 4 50 x 0 C0 x 5 D ) ( i f( =o s t y p e" W i n 3 2 " )( p a c k" b b b "0 x C 20 x 0 80 x 0 0 )( p a c k" b "0 x C 3 ) ) ) ) ( s e t' f o op r i n t ) ( c p y m e m( p a c k" l d "( i f( =o s t y p e" W i n 3 2 " )8 4 5 64 3 6 0 ) )( f i r s t( d u m pf o o ) )4 ) ( c p y m e m( p a c k" l d "( a d d r e s sf o o c o d e ) )( +( f i r s t( d u m pf o o ) )1 2 )4 ) ( s e t' f o o n a m e" f o o " ) ( c p y m e m( p a c k" l d "f o o n a m e )( +( f i r s t( d u m pf o o ) )8 )4 ) ( f o o34 ) 7

ThelastexamplewillnotworkonallhardwareplatformsandOSs. UsethedumpfunctiontoretrievebinaryaddressesandthecontentsfromnewLISPcells.

crc32
syntax:(crc32strdata) Calculatesarunning32bitCRC(CircularRedundancyCheck)sumfromthebufferinstrdata,startingwithaCRCof 0 x f f f f f f f f forthefirstbyte.c r c 3 2 usesanalgorithmpublishedbywww.w3.org.
( c r c 3 2" a b c d e f g h i j k l m n o p q r s t u v w x y z " ) 1 2 7 7 6 4 4 9 8 9 c r c 3 2 isoftenusedtoverifydataintegrityinunsafedatatransmissions.

critchi2
syntax:(critchi2numprobabilityintdf) CalculatesthecriticalminimumChiforagivenconfidenceprobabilitynumprobabilityunderthenullhypothesisandthedegrees offreedominintdffortestingthesignificanceofastatisticalnullhypothesis. Notethatversionspriorto10.2.0took(1.0p)fortheprobabilityinsteadofp.
( c r i t c h i 20 . 0 14 ) 1 3 . 2 7 6 7 0 4 4 3

Seealsotheinversefunctionprobchi2.

critf
syntax:(critfnumprobabilityintdf1intdf2) CalculatesthecriticalminimumFforagivenconfidenceprobabilitynumprobabilityunderthenullhypothesisandthedegreesof freedomgiveninintdf1andintdf2fortestingthesignificanceofastatisticalnullhypothesisusingtheFtest.
( c r i t f0 . 0 51 01 2 ) 2 . 7 5 3 3 8 6 7 2 7

Seealsotheinversefunctionprobf.

critt
syntax:(crittnumprobabilityintdf) CalculatesthecriticalminimumStudent'stforagivenconfidenceprobabilitynumprobabilityunderthenullhypothesisandthe degreesoffreedominintdffortestingthesignificanceofastatisticalnullhypothesis.
( c r i t t0 . 0 51 4 ) 1 . 7 6 1 3 1 0 1 4 2

Seealsotheinversefunctionprobt.

critz
syntax:(critznumprobability) CalculatesthecriticalnormaldistributedZvalueofagivencumulatedprobabilitynumprobabilityfortestingofstatistical significanceandconfidenceintervals.
( c r i t z0 . 9 9 9 ) 3 . 0 9 0 2 3 2 3 7 2

Seealsotheinversefunctionprobz.

currentline
syntax:(currentline) Retrievesthecontentsofthelastreadlineoperation.c u r r e n t l i n e 'scontentsarealsoimplicitlyusedwhenwritelineiscalled withoutastringparameter. ThefollowingsourceshowsthetypicalcodepatternforcreatingaUnixcommandlinefilter:
# ! / u s r / b i n / n e w l i s p

( s e t' i n F i l e( o p e n( m a i n a r g s2 )" r e a d " ) ) ( w h i l e( r e a d l i n ei n F i l e ) ( i f( s t a r t s w i t h( c u r r e n t l i n e )" ; ; " ) ( w r i t e l i n e ) ) ) ( e x i t )

Theprogramisinvoked:
. / f i l t e rm y f i l e . l s p

Thisdisplaysallcommentlinesstartingwith; ; fromafilegivenasacommandlineargumentwheninvokingthescriptf i l t e r .

curry
syntax:(curryfuncexp) Transformsfuncfromafunctionf(x,y)thattakestwoargumentsintoafunctionfx(y)thattakesasingleargument.c u r r y workslike amacrointhatitdoesnotevaluateitsarguments.Instead,theyareevaluatedduringtheapplicationoffunc.
( s e t' f( c u r r y+1 0 ) ) ( l a m b d a( $ x )( +1 0$ x ) ) ( f7 ) 1 7 ( f i l t e r( c u r r ym a t c h' ( a* ) )' ( ( a1 0 )( b5 )( a3 )( c8 )( a9 ) ) ) ( ( a1 0 )( a3 )( a9 ) ) ( c l e a n( c u r r ym a t c h' ( a* ) )' ( ( a1 0 )( b5 )( a3 )( c8 )( a9 ) ) ) ( ( b5 )( c8 ) ) ( m a p( c u r r yl i s t' x )( s e q u e n c e15 ) ) ( ( x1 )( x2 )( x3 )( x4 )( x5 ) ) c u r r y canbeusedonallfunctionstakingtwoarguments.

dateutf8
syntax:(date) syntax:(dateintsecs[intoffset]) syntax:(dateintsecsintoffsetstrformat) Thefirstsyntaxreturnsthelocaltimezone'scurrentdateandtimeasastringrepresentation.Ifintsecsisoutofrange,n i l is returned. Inthesecondsyntax,d a t e translatesthenumberofsecondsinintsecsintoitsdate/timestringrepresentationforthelocaltimezone. Thenumberinintsecsisusuallyretrievedfromthesystemusingdatevalue.Optionally,atimezoneoffset(inminutes)canbe specifiedinintoffset,whichisaddedorsubtractedbeforeconversionofintsectoastring.Ifintsecsisoutofrangeoraninvalid strformatisspecified,anemptystring" " isreturned.
( d a t e ) ( d a t e( d a t e v a l u e ) ) ( d a t e( d a t e v a l u e )3 0 0 ) ( d a t e0 ) ( d a t e0( n o w02 ) ) " F r iO c t2 90 9 : 5 6 : 5 82 0 0 4 " " S a tM a y2 01 1 : 3 7 : 1 52 0 0 6 " " S a tM a y2 01 6 : 3 7 : 1 92 0 0 6 " ;5h o u r so f f s e t " W e dD e c3 11 6 : 0 0 : 0 01 9 6 9 " " T h uJ a n 10 0 : 0 0 : 0 01 9 7 0 " ;U n i xe p o c h

Thewaythedateandtimearepresentedinastringdependsontheunderlyingoperatingsystem.

Thesecondexamplewouldshow1119700:0whenintheGreenwichtimezone,butitdisplaysatimelagof8hourswhenin PacificStandardTime(PST).d a t e assumestheintsecsgivenareinCoordinatedUniversalTime(UTCformerlyGreenwichMean Time(GMT))andconvertsitaccordingtothelocaltimezone. Thethirdsyntaxmakesthedatestringfullycustomizablebyusingaformatspecifiedinstrformat.Thisallowsthedayandmonth namestobetranslatedintoresultsappropriateforthecurrentlocale:


( s e t l o c a l e" g e r m a n " )" d e _ D E " ;o nL i n u x-n ol e a d i n g0o nd a yw i t h% d ( d a t e( d a t e v a l u e )0" % A% d .% B% Y " ) " M o n t a g 7 .M r z2 0 0 5 " ( s e t l o c a l e" C " ) ;d e f a u l tP O S I X ( d a t e( d a t e v a l u e )0" % A% B% d% Y " ) " M o n d a yM a r c h0 72 0 0 5 "

;s u p p r e s s i n gl e a d i n g0o nW i n 3 2u s i n g# ( d a t e( d a t e v a l u e )0" % a% # d% b% Y " ) " M o n7M a r2 0 0 5 " ( s e t l o c a l e" g e r m a n " ) ( d a t e( d a t e v a l u e )0" % x " )" 0 7 . 0 3 . 2 0 0 5 " ( s e t l o c a l e" C " ) ( d a t e( d a t e v a l u e )0" % x " )" 0 3 / 0 7 / 0 5 " ;m o n t hd a yy e a r ;d a ym o n t hy e a r

ThefollowingtablesummarizesallformatspecifiersavailableonbothWin32andLinux/Unixplatforms.Moreformatoptionsare availableonLinux/Unix.Fordetails,consultthemanualpagefortheCfunctions t r f t i m e ( ) oftheindividualplatform'sClibrary. format description %a abbreviatedweekdaynameaccordingtothecurrentlocale %A fullweekdaynameaccordingtothecurrentlocale %b abbreviatedmonthnameaccordingtothecurrentlocale %B %c %d %H %I %j %m %M %p %S %U %w %W %x %X %y %Y %z %Z %% fullmonthnameaccordingtothecurrentlocale preferreddateandtimerepresentationforthecurrentlocale dayofthemonthasadecimalnumber(range0131) hourasadecimalnumberusinga24hourclock(range0023) hourasadecimalnumberusinga12hourclock(range0112) dayoftheyearasadecimalnumber(range001366) monthasadecimalnumber(range0112) minuteasadecimalnumber either'am'or'pm'accordingtothegiventimevalueorthecorrespondingstringsforthecurrentlocale secondasadecimalnumber061(60and61toaccountforoccasionalleapseconds) weeknumberofthecurrentyearasadecimalnumber,startingwiththefirstSundayasthefirstdayofthefirstweek dayoftheweekasadecimal,Sundaybeing0 weeknumberofthecurrentyearasadecimalnumber,startingwiththefirstMondayasthefirstdayofthefirstweek preferreddaterepresentationforthecurrentlocalewithoutthetime preferredtimerepresentationforthecurrentlocalewithoutthedate yearasadecimalnumberwithoutacentury(range0099) yearasadecimalnumberincludingthecentury timezoneornameorabbreviation(sameas%ZonWin32,differentonUnix) timezoneornameorabbreviation(sameas%zonWin32,differentonUnix) aliteral'%'character

Leadingzeroesinthedisplayofdecimaldaynumberscanbesuppressedusing" % d " onLinuxandFreeBSDandusing" % e " on OpenBSD,SunOS/SolarisandMacOSX.OnWin32use" % # d " . Seealsodatevalue,datelist,dateparse,timeofday,time,andnow.

datelist
syntax:(datelistintseconds[intindex]) Returnsalistofyear,month,date,hours,minutes,seconds,dayofyearanddayofweekfromatimevaluegiveninsecondsafter January1st,197000:00:00.ThedateandtimevaluesarengivenasUTC,whichmaydifferfromthelocaltimezone. Theweekdayvaluerangesfrom1to7forMondaythruSunday.
( d a t e l i s t1 2 8 2 4 7 9 2 4 4 ) ( d a t e l i s t1 2 8 2 4 7 9 2 4 40 ) ( d a t e l i s t1 2 8 2 4 7 9 2 4 42 ) ( 2 0 1 082 21 21 442 3 41 ) 2 0 1 0;y e a r 2 3 4 ;d a yo fy e a r

( a p p l yd a t e v a l u e( d a t e l i s t1 2 8 2 4 7 9 2 4 4 ) )1 2 8 2 4 7 9 2 4 4 ( d a t e l i s t0 ) ( 1 9 7 01100014 );T h u r s d a y1 s t ,J a n1 9 7 0

Asecondoptionalintindexparametercanbeusedtoreturnaspecificmemberofthelist.
d a t e l i s t istheinverseoperationofdatevalue.

dateparse
syntax:(dateparsestrdatestrformat) Parsesadatefromatextstringinstrdateusingaformatasdefinedinstrformat,whichusesthesameformattingrulesfoundin date.Thefunctiond a t e p a r s e returnsthenumberofUTCsecondspassedsinceJanuary1st,1970UTCstartingwith0andupto 2147472000foradateofJanuary19th,2038. ThisfunctionisnotavailableonWin32platforms.Thefunctionwasnamedp a r s e d a t e inpreviousversions.Theoldformis deprecated.
( d a t e p a r s e" 2 0 0 7 . 1 . 3 "" % Y . % m . % d " ) 1 1 6 7 7 8 2 4 0 0 ( d a t e p a r s e" J a n u a r y1 0 ,0 7 "" % B% d ,% y " ) 1 1 6 8 3 8 7 2 0 0 ;o u t p u to fd a t e p a r s ea si n p u tv a l u et od a t e l i s tp r o d u c e st h es a m ed a t e ( d a t e l i s t( d a t e p a r s e" 2 0 1 0 . 1 0 . 1 87 : 0 0 "" % Y . % m . % d% H : % M " ) ) ( 2 0 1 01 01 87002 9 01 )

Seethedatefunctionforallpossibleformatdescriptors.

datevalue
syntax:(datevalueintyearintmonthintday[inthourintminintsec]) syntax:(datevalue)

Inthefirstsyntax,d a t e v a l u e returnsthetimeinsecondssince19701100:00:00foragivendateandtime.Theparametersfor thehour,minutes,andsecondsareoptional.ThetimeisassumedtobeCoordinatedUniversalTime(UTC),notadjustedforthe currenttimezone. Inthesecondsyntax,d a t e v a l u e returnsthetimevalueinsecondsforthecurrenttime.


( d a t e v a l u e2 0 0 222 8 ) 1 0 1 4 8 5 4 4 0 0 ( d a t e v a l u e1 9 7 011000 ) 0 ( d a t e( a p p l yd a t e v a l u e( n o w ) ) ) " W e dM a y2 41 0 : 0 2 : 4 72 0 0 6 " ( d a t e( d a t e v a l u e ) ) " W e dM a y2 41 0 : 0 2 : 4 72 0 0 6 " ( d a t e ) " W e dM a y2 41 0 : 0 2 : 4 72 0 0 6 "

Thefunctiondatelistcanbeusedtotransformad a t e v a l u e backintoalist:
( d a t e l i s t1 0 1 4 8 5 4 4 0 0 ) ( 2 0 0 222 8000 ) ( a p p l yd a t e v a l u e( d a t e l i s t1 0 1 4 8 5 4 4 0 0 ) )1 0 1 4 8 5 4 4 0 0

Seealsodate,datelist,dateparse,timeofday,time,andnow.

debug
syntax:(debugfunc) Callstraceandbeginsevaluatingtheuserdefinedfunctioninfunc.d e b u g isashortcutforexecuting( t r a c et r u e ) ,thenentering thefunctiontobedebugged.
; ;i n s t e a do fd o i n g ( t r a c et r u e ) ( m y f u n cabc ) ( t r a c en i l ) ; ;u s ed e b u ga sas h o r t c u t ( d e b u g( m y f u n cabc ) )

Whenind e b u g ortracemode,errormessageswillbeprinted.Thefunctioncausingtheexceptionwillreturneither0 orn i l and processingwillcontinue.Thisway,variablesandthecurrentstateoftheprogramcanstillbeinspectedwhiledebugging. Seealsothetracefunction.

dec!
syntax:(decplace[num]) Thenumberinplaceisdecrementedby1 . 0 ortheoptionalnumbernumandreturned.d e c performsfloatarithmeticandconverts integernumberspassedintofloatingpointtype. placeiseitherasymboloraplaceinaliststructureholdinganumber,oranumberreturnedbyanexpression.
( s e tx1 0 ) ( d e cx ) x ( d e cx0 . 2 5 ) x 1 0 9 9 8 . 7 5 8 . 7 5

Ifthesymbolforplacecontainsn i l ,itistreatedasifcontaining0 . 0 :

z ( d e cz )

n i l 1

( s e tzn i l ) ( d e cz0 . 0 1 ) 0 . 0 1

Placesinaliststructureoranumberreturnedbyanotherexpressioncanbeupdatedtoo:
( s e t' l' ( 1234 ) ) ( d e c( l3 )0 . 1 )3 . 9 ( d e c( f i r s tl ) )0 l( 0233 . 9 ) ( d e c( +34 ) )6

Usethefunctiontodecrementinintegermode.Usetheincfunctiontoincrementnumbersfloatingpointmode.

defnew
syntax:(defnewsymsource[symtarget]) Thisfunctionworkssimilarlytonew,butitonlycreatesacopyofonesymbolanditscontentsfromthesymbolinsymsource. Whensymtargetisnotgiven,asymbolwiththesamenameiscreatedinthecurrentcontext.Allsymbolsreferencedinsidesym sourcewillbetranslatedintosymbolreferencesintothecurrentcontext,whichmustnotbeMAIN. Ifanargumentispresentinsymtarget,thecopywillbemadeintoasymbolandcontextasreferencedbythesymbolinsymtarget. Inadditiontoallowingrenamingofthefunctionwhilecopying,thisalsoenablesthecopytobeplacedinadifferentcontext.All symbolreferencesinsymsourcewiththesamecontextassymsourcewillbetranslatedintosymbolreferencesofthetargetcontext.
d e f n e w returnsthesymbolcreated: >( s e t' f o o : v a r' ( f o o : xf o o : y ) ) ( f o o : xf o o : y ) >( d e f n e w' f o o : v a r' c t : m y v a r ) c t : m y v a r >c t : m y v a r ( c t : xc t : y ) >( c o n t e x t' K ) K >( d e f n e w' f o o : v a r ) v a r K >v a r ( xy )

Thefollowingexampleshowshowastaticallyscopedfunctioncanbecreatedbymovingititsownnamespace:
>( s e t' t e m p( l a m b d a( x )( +xx ) ) ) ( l a m b d a( x )( +xx ) ) >( d e f n e w' t e m p' d o u b l e : d o u b l e ) d o u b l e : d o u b l e >( d o u b l e1 0 ) 2 0 >d o u b l e : d o u b l e ( l a m b d a( d o u b l e : x )( +d o u b l e : xd o u b l e : x ) )

Thefollowingdefinitionofd e f s t a t i c canbeusedtocreatefunctionslivingintheirownlexicallyprotectednamespace:

( d e f i n e( d e f s t a t i csb o d y ) ( d e f n e w' b o d y( s y mss ) ) ) ( d e f s t a t i c' a c c( l a m b d a( x ) ( i n cs u mx ) ) ) >( a c c1 ) 1 >( a c c1 ) 2 >( a c c8 ) 1 0 >

Thefunctiond e f n e w canalsobeusedtoconfigurecontextsorcontextobjectsinamoregranularfashionthanispossiblewith new,whichcopiesawholecontext.

default
syntax:(defaultcontext) Returnthecontentsofthedefaultfunctorincontext.
( d e f i n eF o o : F o o1 2 3 ) ( d e f a u l tF o o )1 2 3 ( s e t f( d e f a u l tF o o )4 5 6 ) ( s e t' c t xF o o ) ( d e f a u l tc t x )4 5 6 F o o : F o o 4 5 6

InmanysituationsnewLISPdefaultsautomaticallytothedefaultfunctorwhenseeingacontextname.Incircumstanceswherethis isnotthecase,thed e f a u l t functioncanbeused.

define!
syntax:(define(symname[symparam1...])[body1...]) syntax:(define(symname[(symparam1expdefault)...])[body1...]) syntax:(definesymnameexp) Definesthenewfunctionsymname,withoptionalparameterssymparam1.d e f i n e isequivalenttoassigningalambda expressiontosymname.Whencallingadefinedfunction,allargumentsareevaluatedandassignedtothevariablesinsymparam1 ,thenthebody1expressionsareevaluated.Whenafunctionisdefined,thelambdaexpressionboundtosymnameisreturned. Allparametersdefinedareoptional.Whenauserdefinedfunctioniscalledwithoutarguments,thoseparametersassumethevalue n i l .Ifthoseparametershaveadefaultvaluespecifiedinexpdefault,theyassumethatvalue. Thereturnvalueofd e f i n e istheassignedlambdaexpression.Whencallingauserdefinedfunction,thereturnvalueisthelast expressionevaluatedinthefunctionbody.
( d e f i n e( a r e axy )( *xy ) ) ( l a m b d a( xy )( *xy ) ) ( a r e a23 ) 6

Asanalternative,a r e a couldbedefinedasafunctionwithoutusingd e f i n e .

( s e t' a r e a( l a m b d a( xy )( *xy ) )

lambdaorfnexpressionsmaybeusedbythemselvesasanonymousfunctionswithoutbeingdefinedasasymbol:
( ( l a m b d a(xy )( *xy ) )23 ) 6 ( ( f n(xy )( *xy ) )23 ) 6 f n isjustashorterformofwritingl a m b d a .

Parameterscanhavedefaultvaluesspecified:
( d e f i n e( f o o( a1 )( b2 ) ) ( l i s tab ) ) ( f o o ) ( 12 ) ( f o o3 ) ( 32 ) ( f o o34 ) ( 34 )

Expressionsinexpdefaultareevaluatedinthefunction'scurrentenvironment.
( d e f i n e( f o o( a1 0 )( b( d i va2 ) ) ) ( l i s tab ) ) ( f o o ) ( 1 05 ) ( f o o3 0 ) ( 3 01 5 ) ( f o o34 ) ( 34 )

Thesecondversionofd e f i n e workslikethesetfunction.
( d e f i n ex1 2 3 ) 1 2 3 ; ;i se q u i v a l e n tt o ( s e t' x1 2 3 ) 1 2 3 ( d e f i n ea r e a( l a m b d a(xy )( *xy ) ) ) ; ;i se q u i v a l e n tt o ( s e t' a r e a( l a m b d a(xy )( *xy ) ) ) ; ;i se q u i v a l e n tt o ( d e f i n e( a r e axy )( *xy ) )

Tryingtoredefineaprotectedsymbolwillcauseanerrormessage.

definemacro
syntax:(definemacro(symname[symparam1...])body) syntax:(definemacro(symname[(symparam1expdefault)...])body) Functionsdefinedusingd e f i n e m a c r o arecalledfexprsinotherLISPsastheydon'tdovariableexpansion.InnewLISPtheyare stillcalledmacros,becausetheyarewrittenwiththesamepurposeofcreatingspecialsyntaxformswithnonstandardevaluation patternsofarguments.Functionscreatedusingd e f i n e m a c r o canbecombinedwithtemplateexpansionusingexpandorletex. Definesthenewfexprsymname,withoptionalargumentssymparam1.d e f i n e m a c r o isequivalenttoassigningalambdamacro expressiontoasymbol.Whenad e f i n e m a c r o functioniscalled,unevaluatedargumentsareassignedtothevariablesinsym param1....Thenthebodyexpressionsareevaluated.Whenevaluatingthed e f i n e m a c r o function,thelambdamacroexpression isreturned.
( d e f i n e m a c r o( m y s e t qp 1p 2 )( s e tp 1( e v a lp 2 ) ) ) ( l a m b d a m a c r o( p 1p 2 )( s e tp 1( e v a lp 2 ) ) ) ( m y s e t qx1 2 3 ) 1 2 3 x 1 2 3

Newfunctionscanbecreatedtobehavelikebuiltinfunctionsthatdelaytheevaluationofcertainarguments.Becausefexprscan

accesstheargumentsinsideaparameterlist,theycanbeusedtocreateflowcontrolfunctionslikethosealreadybuiltinto newLISP. Allparametersdefinedareoptional.Whenamacroiscalledwithoutarguments,thoseparametersassumethevaluen i l .Ifthose parametershaveadefaultvaluespecifiedinexpdefault,theyassumethatdefaultvalue.


( d e f i n e m a c r o( f o o( a1 )( b2 ) ) ( l i s tab ) ) ( f o o ) ( 12 ) ( f o o3 ) ( 32 ) ( f o o34 ) ( 34 )

Expressionsinexpdefaultareevaluatedinthefunction'scurrentenvironment.
( d e f i n e m a c r o( f o o( a1 0 )( b( d i va2 ) ) ) ( l i s tab ) ) ( f o o ) ( 1 05 ) ( f o o3 0 ) ( 3 01 5 ) ( f o o34 ) ( 34 )

Notethatinfexprs,thedangerexistsofpassingaparameterwiththesamevariablenameasusedinthed e f i n e m a c r o definition.In thiscase,thefexpr'sinternalvariablewouldendupreceivingn i l insteadoftheintendedvalue:


; ;n o tag o o dd e f i n i t i o n ! ( d e f i n e m a c r o( m y s e t qxy )( s e tx( e v a ly ) ) ) ; ;s y m b o ln a m ec l a s hf o rx ( m y s e t qx1 2 3 ) 1 2 3 x n i l

Thereareseveralmethodsthatcanbeusedtoavoidthisproblem,knownasvariablecapture,bywritinghygienicd e f i n e m a c r o s: Putthedefinitionintoitsownlexicallyclosednamespacecontext.Ifthefunctionhasthesamenameasthecontext,itcanbe calledbyusingthecontextnamealone.Afunctionwiththischaracteristiciscalledadefaultfunction.Thisisthepreferred methodinnewLISPtowrited e f i n e m a c r o s. Useargstoaccessargumentspassedbythefunction.


; ;ad e f i n e m a c r oa sal e x i c a l l yi s o l a t e df u n c t i o n ; ;a v o i d i n gv a r i a b l ec a p t u r ei np a s s e dp a r a m e t e r s ( c o n t e x t' m y s e t q ) ( d e f i n e m a c r o( m y s e t q : m y s e t qxy )( s e tx( e v a ly ) ) ) ( c o n t e x tM A I N ) ( m y s e t qx1 2 3 ) 1 2 3 ;n os y m b o lc l a s h x 1 2 3

Thedefinitionintheexampleislexicallyisolated,andnovariablecapturecanoccur.Insteadofthefunctionbeingcalledusing( m y s e t q : m y s e t q ) ,itcanbecalledwithjust( m y s e t q ) becauseitisadefaultfunction. Thesecondpossibilityistorefertopassedparametersusingargs:


; ;a v o i dv a r i a b l ec a p t u r ei nm a c r o su s i n gt h ea r g sf u n c t i o n ( d e f i n e m a c r o( m y s e t q )( s e t( a r g s0 )( e v a l( a r g s1 ) ) ) )

delete

syntax:(deletesymbol[bool]) syntax:(deletesymcontext[bool]) Deletesasymbolsymbol,oracontextinsymcontextwithallcontainedsymbolsfromnewLISP'ssymboltable.Referencestothe symbolwillbechangedton i l . Whentheexpressioninboolevaluatestot r u e ,symbolsareonlydeletedwhentheyarenotreferenced. Whentheexpressioninboolevaluateston i l ,symbolswillbedeletedwithoutanyreferencechecking.Notethatthismodeshould onlybeused,ifnoreferencestothesymbolexistoutsideit'snamespace.Ifexternalreferencesexist,thismodecanleadtosystem crashes,astheexternalreferenceisnotsetton i l whenusingthismode.Thismodecanbeusedtodeletenamespacehashesandto deletenamespacesinobjectsystems,wherevariablesarestrictlytreatedasprivate. Protectedsymbolsofbuiltinfunctionsandspecialsymbolsliken i l andt r u e cannotbedeleted.
d e l e t e returnst r u e ifthesymbolwasdeletedsuccessfullyorn i l ifthesymbolwasnotdeleted.

Whendeletingacontextsymbol,thefirstd e l e t e removesthecontextnamespacecontentsanddemotesthecontextsymboltoa normalmonovariablesymbol.Asecondd e l e t e willremovethesymbolfromthesymboltable.


( s e t' l s t' ( aba V a rcd ) ) ( d e l e t e' a V a r ) ;a V a rd e l e t e d ,r e f e r e n c e sm a r k e dn i l l s t ( abn i lcd ) ( s e t' l s t' ( aba V a rcd ) ) ( d e l e t e' a V a rt r u e ) n i l;p r o t e c ta V a ri fr e f e r e n c e d l s t ( aba V a rcd ) ; ;d e l e t ea l ls y m b o l si nac o n t e x t ( s e t' f o o : x1 2 3 ) ( s e t' f o o : y" h e l l o " ) ( d e l e t e' f o o ) f o o : x ,f o o : yd e l e t e d

Inthelastexampleonlythesymbolsinsidecontextf o o willbedeletedbutnotthecontextsymbolf o o itself.Itwillbeconvertedto anormalunprotectedsymbolandcontainn i l . Notethatdeletingasymbolthatispartofanexpressionwhichiscurrentlyexecutingcancrashthesystemorhaveotherunforeseen effects.

deletefile
syntax:(deletefilestrfilename) Deletesafilegiveninstrfilename.Returnst r u e ifthefilewasdeletedsuccessfully. Onfailurethefunctionreturnsn i l .Forerrorinformation,usesyserrorwhenusedonfiles.WhenusedonURLsneterrorgives moreerrorinformation. ThefilenamecanbegivenasaURL.
( d e l e t e f i l e" j u n k " ) ( d e l e t e f i l e" h t t p : / / a s i t e . c o m / e x a m p l e . h t m l " )

( d e l e t e f i l e" f i l e : / / a F i l e . t x t " )

Thefirstexampledeletesthefilej u n k inthecurrentdirectory.ThesecondexampleshowshowtouseaURLtospecifythefile.In thisform,additionalparameterscanbegiven.Seedeleteurlfordetails.

deleteurl
syntax:(deletefilestrurl) ThisfunctiondeletesthefileonaremoteHTTPserverspecifiedinstrurl.TheHTTPD E L E T E protocolmustbeenabledonthe targetwebserver,oranerrormessagestringmaybereturned.Thetargetfilemustalsohaveaccesspermissionssetaccordingly. Additionalparameterssuchastimeoutandcustomheadersareavailableexactlyasinthegeturlfunction. Ifstrurlstartswithf i l e : / / afileonthelocalfilesystemisdeleted. ThisfeatureisalsoavailablewhenthedeletefilefunctionisusedandaURLisspecifiedforthefilename.
( d e l e t e u r l" h t t p : / / w w w . a s e r v e r . c o m / s o m e f i l e . t x t " ) ( d e l e t e u r l" h t t p : / / s i t e . o r g : 8 0 8 0 / p a g e . h t m l "5 0 0 0 ) ;d e l e t eo nt h el o c a lf i l es y s t e m ( d e l e t e u r l" f i l e : / / / h o m e / j o e / s o m e f i l e . t x t " )

Thesecondexampleconfiguresatimeoutoptionoffiveseconds.OtheroptionssuchasspecialHTTPprotocolheaderscanbe specified,aswell.Seethegeturlfunctionfordetails.

destroy
syntax:(destroyintpid) syntax:(destroyintpidintsignal) Destroysaprocesswithprocessidinintpidandreturnst r u e onsuccessorn i l onfailure.Theprocessidisnormallyobtained fromapreviouscalltoforkonMacOSXandotherUnixorprocessonallplatforms.OnUnix,d e s t r o y workslikethesystem utilitykillusingtheSIGKILLsignal. CAUTION!Ifintpidis0 thesignalissenttoallprocesseswhosegroupIDisequaltotheprocessgroupIDofthesender.Ifintpid is1 allprocesseswiththecurrentuseridwillbekilled,ifnewLISPisstartedwithsuperuserprivileges,allprocessesexceptsystem processesaredestroyed. Whenspecifyingintsignal,d e s t r o y workslikeaUnixk i l l commandsendingthespecifiedUnixsignaltotheprocessinintpid. ThissecondsyntaxisnotavailableonWin32.
( s e t' p i d( p r o c e s s" / u s r / b i n / b c "b c i nb c o u t ) ) ( d e s t r o yp i d ) ( s e t' p i d( f o r k( d o t i m e s( i1 0 0 0 )( p r i n t l ni )( s l e e p1 0 ) ) ) ) ( s l e e p1 0 0 )( d e s t r o yp i d )

det

syntax:(detmatrix[floatpivot]) Returnsthedeterminantofasquarematrix.Amatrixcaneitherbeanestedlistoranarray. Optionally0 . 0 oraverysmallvaluecanbespecifiedinfloatpivot.ThisvaluesubstitutespivotelementsintheLUdecomposition algorithm,whichresultinzerowhenthealgorithmdealswithasingularmatrix.


( s e t' A' ( ( 111 )( 145 )( 120 ) ) ) ( d e tA ) 1 ;t r e a t m e n to fs i n g u l a rm a t r i c e s ( d e t' ( ( 21 )( 42 ) ) ) n i l ( d e t' ( ( 21 )( 42 ) )0 ) 0 ( d e t' ( ( 21 )( 42 ) )1 e 2 0 ) 4 e 2 0

Ifthematrixissingularandfloatpivotisnotspecified,n i l isreturned. Seealsotheothermatrixoperationsinvert,mat,multiplyandtranspose.

device
syntax:(device[inthandle]) inthandleisanI/Odevicenumber,whichissetto0(zero)forthedefaultSTDI/Opairofhandles,0forstdinand1forstdout.int handlemayalsobeafilehandlepreviouslyobtainedusingopen.Inthiscaseboth,inputandoutputarechanneledthroughthis handle.Whennoargumentissupplied,thecurrentI/Odevicenumberisreturned. TheI/Ochannelspecifiedbyd e v i c e isusedinternallybythefunctionsprintandreadline.WhenthecurrentI/Odeviceis0or1, printsendsoutputtotheconsolewindowandreadlineacceptsinputfromthekeyboard.IfthecurrentI/Odevicehasbeensetby openingafile,thenprintandreadlineworkonthatfile.
( d e v i c e( o p e n" m y f i l e "" w r i t e " ) ) 5 ( p r i n t" T h i sg o e si nm y f i l e " ) " T h i sg o e si nm y f i l e " ( c l o s e( d e v i c e ) ) t r u e

Notethatusingcloseond e v i c e automaticallyresetsd e v i c e to0(zero).

difference
syntax:(differencelistAlistB) syntax:(differencelistAlistBbool) Inthefirstsyntax,d i f f e r e n c e returnsthesetdifferencebetweenlistAandlistB.Theresultinglistonlyhaselementsoccurringin listA,butnotinlistB.Allelementsintheresultinglistareunique,butlistAandlistBneednotbeunique.Elementsinthelistscan beanytypeofLispexpression.
( d i f f e r e n c e' ( 25603502 )' ( 123321 ) ) ( 560 )

Inthesecondsyntax,d i f f e r e n c e worksinlistmode.boolspecifiest r u e oranexpressionnotevaluatington i l .Intheresulting list,allelementsoflistBareeliminatedinlistA,butduplicatesofotherelementsinlistAareleft.


( d i f f e r e n c e' ( 25603502 )' ( 123321 )t r u e ) ( 56050 )

Seealsothesetfunctionsintersect,uniqueandunion.

directory
syntax:(directory[strpath]) syntax:(directorystrpathstrpattern[intregexoption]) Alistofdirectoryentrynamesisreturnedforthedirectorypathgiveninstrpath.Onfailure,n i l isreturned.Whenstrpathis omitted,thelistofentriesinthecurrentdirectoryisreturned.
( d i r e c t o r y" / b i n " ) ( d i r e c t o r y" c : / " )

Thefirstexamplereturnsthedirectoryof/ b i n ,thesecondlinereturnsalistofdirectoryentriesintherootdirectoryofdriveC:. NotethatonWin32systems,aforwardslash(/ )canbeincludedinpathnames.Whenused,abackslash(\ )mustbeprecededbya secondbackslash. Inthesecondsyntax,d i r e c t o r y cantakearegularexpressionpatterninstrpattern.Onlyfilenamesmatchingthepatternwillbe returnedinthelistofdirectoryentries.Inintregexoptions,specialregularexpressionoptionscanbespecifiedseeregexfordetails.


( d i r e c t o r y" . "" \ \ . c " ) ( " f o o . c "" b a r . c " ) ; ;o ru s i n gb r a c e sa ss t r i n gp a t t e r nd e l i m i t e r s ( d i r e c t o r y" . "{ \ . c } ) ( " f o o . c "" b a r . c " ) ;s h o wo n l yh i d d e nf i l e s( s t a r t i n gw i t hd o t ) ( d i r e c t o r y" . "" ^ [ . ] " ) ( " . "" . . "" . p r o f i l e "" . r n d "" . s s h " )

Theregularexpressionforcesd i r e c t o r y toreturnonlyfilenamescontainingthestring" . c " . Otherfunctionsthatuseregularexpressionsarefind,findall,parse,regex,replace,andsearch.

directory?
syntax:(directory?strpath) Checksifstrpathisadirectory.Returnst r u e orn i l dependingontheoutcome.
( d i r e c t o r y ?" / e t c " ) t r u e ( d i r e c t o r y ?" / u s r / b i n / e m a c s / " ) n i l

div
syntax:(divnum1num2[num3...]) syntax:(divnum1) Successivelydividesnum1bythenumberinnum2.d i v canperformmixedtypearithmetic,butitalwaysreturnsfloatingpoint numbers.AnyfloatingpointcalculationwithN a N alsoreturnsN a N .
( d i v1 03 ) 3 . 3 3 3 3 3 3 3 3 3 ( d i v1 2 0( s u b9 . 06 )1 0 0 ) 0 . 4 ( d i v1 0 ) 0 . 1

Whennum1istheonlyargument,d i v calculatestheinverseofnum1.

dountil
syntax:(dountilexpcondition[body]) Theexpressionsinbodyareevaluatedbeforeexpconditionisevaluated.Iftheevaluationofexpconditionisnotn i l ,thenthed o u n t i l expressionisfinishedotherwise,theexpressionsinbodygetevaluatedagain.Notethatd o u n t i l evaluatestheconditional expressionafterevaluatingthebodyexpressions,whereasuntilcheckstheconditionbeforeevaluatingthebody.Thereturnvalueof thed o u n t i l expressionisthelastevaluationofthebodyexpression.Ifbodyisempty,thelastresultofexpconditionisreturned.
d o u n t i l alsoupdatesthesystemiteratorsymbol$ i d x . ( s e t' x1 ) ( d o u n t i l( >x0 )( i n cx ) ) x 2 ( s e t' x1 ) ( u n t i l( >x0 )( i n cx ) ) x 1

Whiled o u n t i l goesthroughtheloopatleastonce,untilneverenterstheloop. Seealsothefunctionswhileanddowhile.

dowhile
syntax:(dowhileexpconditionbody) Theexpressionsinbodyareevaluatedbeforeexpconditionisevaluated.Iftheevaluationofexpconditionisn i l ,thenthed o w h i l e expressionisfinishedotherwisetheexpressionsinbodygetevaluatedagain.Notethatd o w h i l e evaluatestheconditional expressionafterevaluatingthebodyexpressions,whereaswhilecheckstheconditionbeforeevaluatingthebody.Thereturnvalue ofthed o w h i l e expressionisthelastevaluationofthebodyexpression.
d o w h i l e alsoupdatesthesystemiteratorsymbol$ i d x . ( s e t' x1 0 ) ( d o w h i l e( <x1 0 )( i n cx ) ) x 1 1 ( s e t' x1 0 ) ( w h i l e( <x1 0 )( i n cx ) ) x 1 0

Whiled o w h i l e goesthroughtheloopatleastonce,whileneverenterstheloop. Seealsothefunctionsuntilanddountil.

doargs
syntax:(doargs(sym[expbreak])body)

Iteratesthroughallmembersoftheargumentlistinsideauserdefinedfunctionormacro.Thisfunctionormacrocanbedefined usingdefine,definemacro,lambda,orlambdamacro.Thevariableinsymissetsequentiallytoallmembersintheargumentlist untilthelistisexhaustedoranoptionalbreakexpression(definedinexpbreak)evaluatestot r u e oralogicaltruevalue.The d o a r g s expressionalwaysreturnstheresultofthelastevaluation.


d o a r g s alsoupdatesthesystemiteratorsymbol$ i d x . ( d e f i n e( f o o ) ( d o a r g s( i )( p r i n t l ni ) ) ) >( f o o1234 ) 1 2 3 4

Theoptionalbreakexpressioncausesd o a r g s tointerruptprocessingofthearguments:
( d e f i n e m a c r o( f o o ) ( d o a r g s( i( =i' x ) ) ( p r i n t l ni ) ) ) >( f o oabxcde ) a b t r u e

Usetheargsfunctiontoaccesstheentireargumentlistatonce.

dolist
syntax:(dolist(symlist[expbreak])body) Theexpressionsinbodyareevaluatedforeachelementinlist.Thevariableinsymissettoeachoftheelementsbeforeevaluationof thebodyexpressions.Thevariableusedasloopindexislocalandbehavesaccordingtotherulesofdynamicscoping. Optionally,aconditionforearlyloopexitmaybedefinedinexpbreak.Ifthebreakexpressionevaluatestoanynonn i l value,the d o l i s t loopreturnswiththevalueofexpbreak.Thebreakconditionistestedbeforeevaluatingbody.
( s e t' x1 2 3 ) ( d o l i s t( x' ( abcdefg ) ) ;p r i n t s :a b c d e f g ( p r i n tx ) ) g ;r e t u r nv a l u e ( d o l i s t( x' ( abcdefg )( =x' e ) ) ;p r i n t s :a b c d ( p r i n tx ) ) ; ;xi sl o c a li nd o l i s t ; ;xh a ss t i l li t so l dv a l u eo u t s i d et h el o o p x 1 2 3 ;xh a ss t i l li t so l dv a l u e

Thisexampleprintsa b c d e f g intheconsolewindow.Aftertheexecutionofd o l i s t ,thevalueforx remainsunchangedbecausethe x ind o l i s t haslocalscope.Thereturnvalueofd o l i s t istheresultofthelastevaluatedexpression. Theinternalsystemvariable$ i d x keepstrackofthecurrentoffsetintothelistpassedtod o l i s t ,anditcanbeaccessedduringits execution:
( d o l i s t( x' ( abdefg ) ) ( p r i n t l n$ i d x" : "x ) ) g 0 : a 1 : b 2 : d

3 : e 4 : f 5 : g

Theconsoleoutputisshowninboldface.$ i d x isprotectedandcannotbechangedbytheuser.

dostringutf8
syntax:(dostring(symstring[expbreak])body) Theexpressionsinbodyareevaluatedforeachcharacterinstring.ThevariableinsymissettoeachASCIIorUTF8integervalue ofthecharactersbeforeevaluationofthebodyexpressions.Thevariableusedasloopindexislocalandbehavesaccordingtothe rulesofdynamicscoping. Optionally,aconditionforearlyloopexitmaybedefinedinexpbreak.Ifthebreakexpressionevaluatestoanynonn i l value,the d o l i s t loopreturnswiththevalueofexpbreak.Thebreakconditionistestedbeforeevaluatingbody.
;A S C I Ie x a m p l e ( s e t' s t r" a b c d e f g " ) ( d o s t r i n g( cs t r )( p r i n t l nc"-"( c h a rc ) ) ) 9 7-a 9 8-b 9 9-c 1 0 0-d 1 0 1-e 1 0 2-f 1 0 3-g ;U T F 8e x a m p l e ( s e t' u t f 8 s t r" " ) ( d o s t r i n g( cu t f 8 s t r )( p r i n t l nc"-"( c h a rc ) ) ) 2 5 1 0 5- 3 3 0 2 1- 2 1 5 3 4- . . . 2 0 3 0 7- 1 2 2 9 0-

Thisexampleprintsthevalueofeachcharacterintheconsolewindow.InUTF8enabledversionsofnewLISP,individual charactersmaybelongerthanonebyteandthenumberintheloopvariablemayexceed255.Thereturnvalueofd o s t r i n g isthe resultofthelastevaluatedexpression. Theinternalsystemvariable$ i d x keepstrackofthecurrentoffsetintothestringpassedtod o s t r i n g ,anditcanbeaccessedduring itsexecution.

dotimes
syntax:(dotimes(symvarintcount[expbreak])body) Theexpressionsinbodyareevaluatedinttimes.Thevariableinsymissetfrom0(zero)to(int1)eachtimebeforeevaluatingthe bodyexpression(s).Thevariableusedastheloopindexislocaltothed o t i m e s expressionandbehavesaccordingtherulesof dynamicscoping.Theloopindexisofintegertype.d o t i m e s returnstheresultofthelastexpressionevaluatedinbody.After evaluationofthed o t i m e s statementsymassumesitspreviousvalue. Optionally,aconditionforearlyloopexitmaybedefinedinexpbreak.Ifthebreakexpressionevaluatestoanynonn i l value,the

d o t i m e s loopreturnswiththevalueofexpbreak.Thebreakconditionistestedbeforeevaluatingbody. ( d o t i m e s( x1 0 ) ( p r i n tx ) ) 9 ;r e t u r nv a l u e

Thisprints0 1 2 3 4 5 6 7 8 9 totheconsolewindow.

dotree
syntax:(dotree(symsymcontext[bool])body) Theexpressionsinbodyareevaluatedforallsymbolsinsymcontext.Thesymbolsareaccessedinasortedorder.Beforeeach evaluationofthebodyexpression(s),thevariableinsymissettothenextsymbolfromsymcontext.Thevariableusedastheloop indexislocaltothed o t r e e expressionandbehavesaccordingtherulesofdynamicscoping. Whentheoptionalboolexpressionevaluatestonotn i l ,onlysymbolsstartingwithanunderscorecharacter_ areaccessed.Symbol namesstartingwithan_ underscoreareusedforhashkeysandsymbolscreatedbybayestrain.
d o t r e e alsoupdatesthesystemiteratorsymbol$ i d x . ; ;f a s t e ra n dl e s sm e m o r yo v e r h e a d ( d o t r e e( sS o m e C T X )( p r i n ts"" ) ) ; ;s l o w e ra n dh i g h e rm e m o r yu s a g e ( d o l i s t( s( s y m b o l sS o m e C T X ) )( p r i n ts"" ) )

ThisexampleprintsthenamesofallsymbolsinsideSomeCTXtotheconsolewindow.

dump
syntax:(dump[exp]) ShowsthebinarycontentsofanewLISPcell.Withoutanargument,thisfunctionoutputsalistingofallLispcellstotheconsole. Whenexpisgiven,itisevaluatedandthecontentsofaLispcellarereturnedinalist.
( d u m p' a ) ( 9 5 8 6 9 9 659 5 7 8 6 9 29 5 7 8 6 9 29 7 5 9 2 8 0 )

( d u m p9 9 9 ) ( 9 5 8 6 9 9 61 3 09 5 7 8 6 9 29 5 7 8 6 9 29 9 9 )

Thelistcontainsthefollowingmemoryaddressesandinformation: offset description 0 memoryaddressofthenewLISPcell 1 cell>type:major/minortype,seenewlisp.hfordetails 2 cell>next:linkedlistptr cell>aux: stringlength+1or 3 low(littleendian)orhigh(bigendian)wordof64bitintegeror lowwordofIEEE754doublefloat cell>contents: string/symboladdressor 4 high(littleendian)orlow(bigendian)wordof64bitintegeror

highwordofIEEE754doublefloat

ThisfunctionisvaluableforchangingtypebitsincellsorhackingotherpartsofnewLISPinternals.Seethefunctioncpymemfora comprehensiveexample.

dup
syntax:(dupexpintn[bool]) syntax:(dupexp) Iftheexpressioninexpevaluatestoastring,itwillbereplicatedintntimeswithinastringandreturned.Whenspecifyingan expressionevaluatingtoanythingotherthann i l inbool,thestringwillnotbeconcatenatedbutreplicatedinalistlikeanyother datatype. Ifexpcontainsanydatatypeotherthanstring,thereturnedlistwillcontainintnevaluationsofexp. Withouttherepetitionparameter,d u p assumes2.
( d u p" A "6 ) ( d u p" A "6t r u e ) ( d u p" A "0 ) ( d u p" A B "5 ) ( d u p97 ) ( d u p90 ) ( d u p' x8 ) ( d u p' ( 12 )3 ) ( d u p" \ 0 0 0 "4 ) ( d u p" * " ) " A A A A A A " ( " A "" A "" A "" A "" A "" A " ) " " " A B A B A B A B A B " ( 9999999 ) ( ) ( xxxxxxxx ) ( ( 12 )( 12 )( 12 ) ) " \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 " " * * "

Thelastexampleshowshandlingofbinaryinformation,creatingastringfilledwithfourbinaryzeroes. Seealsothefunctionssequenceandseries.

empty?
syntax:(empty?exp) syntax:(empty?str) expistestedforanemptylist(orstrforanemptystring).Dependingonwhethertheargumentcontainselements,t r u e orn i l is returned.
( s e t' v a r' ( ) ) ( e m p t y ?v a r ) ( e m p t y ?' ( 1234 ) ) ( e m p t y ?" h e l l o " ) ( e m p t y ?" " ) t r u e n i l n i l t r u e

Thefirstexamplechecksalist,whilethesecondtwoexamplescheckastring.

encrypt
syntax:(encryptstrsourcestrpad) Performsaonetimepad(OTP)encryptionofstrsourceusingtheencryptionpadinstrpad.Thelongerstrpadisandthemore randomthebytesare,thesafertheencryption.Ifthepadisaslongasthesourcetext,isfullyrandom,andisusedonlyonce,then onetimepadencryptionisvirtuallyimpossibletobreak,sincetheencryptionseemstocontainonlyrandomdata.Toretrievethe original,thesamefunctionandpadareappliedagaintotheencryptedtext:
( s e t' s e c r e t ( e n c r y p t" As e c r e tm e s s a g e "" m ys e c r e tk e y " ) ) " , Y S \ 0 2 2 \ 0 0 6 \ 0 1 7 \ 0 2 3 \ 0 1 7 T M \ 0 1 4 \ 0 2 2 \ n \ 0 1 2 \ 0 3 0 E " ( e n c r y p ts e c r e t" m ys e c r e tk e y " ) " As e c r e tm e s s a g e "

Thesecondexampleencryptsawholefile:
( w r i t e f i l e" m y f i l e . e n c " ( e n c r y p t( r e a d f i l e" m y f i l e " )" 2 9 k H 6 7 * " ) )

endswith
syntax:(endswithstrdatastrkey[numoption]) syntax:(endswithlistexp) Inthefirstsyntax,e n d s w i t h teststhestringinstrdatatoseeifitendswiththestringspecifiedinstrkey.Itreturnst r u e orn i l dependingontheoutcome. Ifaregularexpressionoptionnumberisspecified,strkeycontainsaregularexpressionpattern.Seeregexforvalidnumbersfor option.
( e n d s w i t h" n e w L I S P "" L I S P " ) t r u e ( e n d s w i t h" n e w L I S P "" l i s p " ) n i l ; ;u s er e g u l a re x p r e s s i o n s ( e n d s w i t h" n e w L I S P "" l i s p | y o r k "1 ) t r u e

Inthesecondsyntax,e n d s w i t h checksifalistendswiththelistelementinexp.t r u e orn i l isreturneddependingonoutcome.


( e n d s w i t h' ( 12345 )5 ) t r u e ( e n d s w i t h' ( abcde )' b ) n i l ( e n d s w i t h' ( abc( +34 ) )' ( +34 ) ) t r u e

Thelastexampleshowsthatexpcouldbealistbyitself. Seealsothestartswithfunction.

env
syntax:(env) syntax:(envvarstr) syntax:(envvarstrvaluestr) Inthefirstsyntax(withoutarguments),theoperatingsystem'senvironmentisretrievedasanassociationlistinwhicheachentryisa keyvaluepairofenvironmentvariableandvalue.

( e n v ) ( ( " P A T H "" / b i n : / u s r / b i n : / s b i n " )( " T E R M "" x t e r m c o l o r " ). . .) )

Inthesecondsyntax,thenameofanenvironmentvariableisgiveninvarstr.e n v returnsthevalueofthevariableorn i l ifthe variabledoesnotexistintheenvironment.


( e n v" P A T H " ) " / b i n : / u s r / b i n : / u s r / l o c a l / b i n "

Thethirdsyntax(variablenameinvarstrandvaluepairinvaluestr)setsorcreatesanenvironmentvariable.Ifvaluestristhe emptystring" " ,thenthevariableiscompletelyremovedfromtheenvironmentexceptwhenrunningonSolaris,wherethevariable stayswithanemptystring.


( e n v" N E W L I S P B I N "" / u s r / b i n / " ) ( e n v" N E W L I S P B I N " ) ( e n v" N E W L I S P B I N "" " ) ( e n v" N E W L I S P B I N " ) t r u e " / u s r / b i n / " t r u e n i l

erf
syntax:(erfnum)
e r f calculatestheerrorfunctionofanumberinnum.Theerrorfunctionisdefinedas:

erf(x)=2/sqrt(pi)*integralfrom0toxofexp(t^2)dt
( m a pe r f( s e q u e n c e0 . 06 . 00 . 5 ) ) ( 00 . 5 2 0 4 9 9 8 7 7 80 . 8 4 2 7 0 0 7 9 2 90 . 9 6 6 1 0 5 1 4 6 50 . 9 9 5 3 2 2 2 6 50 . 9 9 9 5 9 3 0 4 8 0 . 9 9 9 9 7 7 9 0 9 50 . 9 9 9 9 9 9 2 5 6 90 . 9 9 9 9 9 9 9 8 4 60 . 9 9 9 9 9 9 9 9 9 8111 )

errorevent
syntax:(erroreventsymeventhandler|funceventhandler) symeventhandlercontainsauserdefinedfunctionforhandlingerrors.Wheneveranerroroccurs,thesystemperformsaresetand executestheuserdefinederrorhandler.Theerrorhandlercanusethebuiltinfunctionlasterrortoretrievethenumberandtextof theerror.Theeventhandlerisspecifiedaseitheraquotedsymboloralambdafunction.
( d e f i n e( m y h a n d l e r ) ( p r i n t" e r r o r#"( f i r s t( l a s t e r r o r ) )"h a so c c u r r e d \ n " )) ( e r r o r e v e n t' m y h a n d l e r ) m y h a n d l e r ; ;s p e c i f yaf u n c t i o nd i r e c t l y ( e r r o r e v e n tm y h a n d l e r ) $ e r r o r e v e n t ( e r r o r e v e n t ( f n( )( p r i n t" e r r o r#"( f i r s t( l a s t e r r o r ) )"h a so c c u r r e d \ n " ) ) ) ( e r r o r e v e n te x i t ) $ e r r o r e v e n t

Foradifferentwayofhandlingerrors,seethecatchfunction.Usethrowerrortothrowuserdefinederrors.

eval
syntax:(evalexp) evalevaluatestheresultofevaluatingexpinthecurrentvariableenvironment.
( s e t' e x p r' ( +34 ) ) ( e v a le x p r ) ( e v a l( l i s t+34 ) ) ( e v a l' ' x ) ( s e t' y1 2 3 ) ( s e t' x' y ) x y ( e v a lx ) 1 2 3 ( +34 ) 7 7 x

Asusual,evaluationofvariableshappensinthecurrentvariableenvironment:
;e v a li ng l o b a l( t o pl e v e l )e n v i r o n m e n t ( s e t' x3' y4 ) ( e v a l' ( +xy ) ) 7 ;e v a li nl o c a le n v i r o n m e n t ( l e t(( x3 3 )( y4 4 )) ( e v a l' ( +xy ) ) ) 7 7 ;o l de n v i r o n m e n ta f t e rl e a v i n gl o c a ll e te n v i r o n m e n t ( e v a l' ( +xy ) ) 7

newLISPpassesallargumentsbyvalue.Usingaquotedsymbol,expressionscanbepassedbyreferencethroughthesymbol.e v a l canbeusedtoaccesstheoriginalcontentsofthesymbol:
( d e f i n e( c h a n g e l i s ta L i s t )( p u s h9 9 9( e v a la L i s t ) ) ) ( s e t' d a t a' ( 12345 ) ) ( c h a n g e l i s t' d a t a ) ( 9 9 912345 )

Intheexample,theparameter' d a t a isquoted,sop u s h canworkontheoriginallist. ThereisasafermethodtopassargumentsbyreferenceinnewLISPbyenclosingthedatainsidecontextobjects.Seethechapter Passingdatabyreference.Passingreferencesintouserdefinedfunctionusingnamespaceidsavoidsvariablecaptureofthepassed symbol,incasethesymbolpassedisthesameusedasaparameterinthefunction.

evalstring
syntax:(evalstringstrsource[symcontext[experror[intoffset]]]) ThestringinstrsourceiscompiledintonewLISP'sinternalformatandthenevaluated.Theevaluationresultisreturned.Ifthestring containsmorethanoneexpression,theresultofthelastevaluationisreturned. Anoptionalsecondargumentcanbeusedtospecifythecontexttowhichthestringshouldbeparsedandtranslated. Ifanerroroccurswhileparsingandevaluatingstrsourcethenexperrorwillbeevaluatedandtheresultreturned. intoffsetspecifiesanoptionaloffsetintostrsource,wheretostartevaluation.
( e v a l s t r i n g" ( +34 ) " ) 7 ( s e t' X1 2 3 ) 1 2 3 ( e v a l s t r i n g" X " ) 1 2 3 ( d e f i n e( r e p l );r e a dp r i n te v a ll o o p

( w h i l et r u e ( p r i n t l n" = >"( e v a l s t r i n g( r e a d l i n e )M A I N( l a s t e r r o r ) ) ) )

( s e t' a1 0 ) ( s e t' b2 0 ) ( s e t' f o o : a1 1 ) ( s e t' f o o : b2 2 ) ( e v a l s t r i n g" ( +ab ) " ) 3 0 ( e v a l s t r i n g" ( +ab ) "' f o o ) 3 3

ThesecondexampleshowsasimplenewLISPinterpreterevalloop. Thelastexampleshowshowtospecifyatargetcontextfortranslation.Thesymbolsa andb nowrefertosymbolsandtheirvalues incontextf o o insteadofM A I N . Seealsothefunctionreadexprwhichtranslatesastringwithoutevaluatingit.

even?
syntax:(even?intnumber) Checksifanintegernumberisevendivisibleby2 ,withoutremainder.Whenafloatingpointnumberispassedforintnumber,it willbeconvertedtoanintegerbycuttingoffitsfractionalpart.
( e v e n ?1 2 3 ) n i l ( e v e n ?8 ) t r u e ( e v e n ?8 . 7 ) t r u e

Useodd?tocheckifanintegerisnotdivisibleby2 .

exec
syntax:(execstrprocess) syntax:(execstrprocess[strstdin]) Inthefirstform,e x e c launchesaprocessdescribedinstrprocessandreturnsallstandardoutputasalistofstrings(oneforeachline instandardout(STDOUT)).e x e c returnsn i l iftheprocesscouldnotbelaunched.Iftheprocesscouldbelaunchedbutonly returnsanderrorandnovalidoutput,theemptylistwillbereturned.
( e x e c" l s* . c " ) ( " n e w l i s p . c "" n l m a t h . c "" n l s t r i n g . c " )

Theexamplestartsaprocessandperformstheshellcommandl s ,capturingtheoutputinanarrayofstrings. Inthesecondform,e x e c createsaprocesspipe,startstheprocessinstrprocess,andreceivesfromstrstdinstandardinputforthis process.Thereturnvalueist r u e iftheprocesswassuccessfullylaunchedotherwiseitisn i l .


( e x e c" c g i P r o c "q u e r y )

Inthisexample,cgiProccouldbeacgiprocessor(e.g.,PerlornewLISP)thatreceivesandprocessesstandardinputsuppliedbya stringcontainedinthevariablequery.

exists
syntax:(existsfuncconditionlist) Successivelyappliesfuncconditiontotheelementsoflistandreturnsthefirstelementthatmeetstheconditioninfunccondition.If noelementmeetsthecondition,n i l isreturned.
( e x i s t ss t r i n g ?' ( 2346" h e l l o "7 ) ) ( e x i s t ss t r i n g ?' ( 342730 ) ) ( e x i s t sz e r o ?' ( 342730 ) ) ( e x i s t s<' ( 342730 ) ) ( e x i s t s( f n( x )( >x3 ) )' ( 342730 ) ) " h e l l o " n i l 0;c h e c kf o r0o r0 . 0 7;c h e c kf o rn e g a t i v e 4

( e x i s t s( f n( x )( =x1 0 ) )' ( 342730 ) ) n i l

Iffuncconditionisn i l ? ,theresultn i l isambiguous.Inthiscaseindexorfindarethebettermethodwhenlookingforn i l . Usetheforallfunctiontocheckifaconditionismetforallelementsinalist.

exit
syntax:(exit[int]) ExitsnewLISP.Anoptionalexitcode,int,maybesupplied.Thiscodecanbetestedbythehostoperatingsystem.WhennewLISP isrunindaemonservermodeusingd asacommandlineoption,onlythenetworkconnectionisclosed,whilenewLISPstays resident,listeningforanewconnection.
( e x i t5 )

exp
syntax:(expnum) Theexpressioninnumisevaluated,andtheexponentialfunctioniscalculatedbasedontheresult.e x p istheinversefunctionoflog.
( e x p1 ) 2 . 7 1 8 2 8 1 8 2 8 ( e x p( l o g1 ) ) 1

expand
syntax:(expandexpsym1[sym2...]) syntax:(expandexplistassoc[bool]) syntax:(expandexp) Inthefirstsyntax,onesymbolinsym(ormoreinsym2throughsymn)islookedupinasimpleornestedexpressionexp.Theyare thenexpandedtothecurrentbindingofthesymbolandtheexpandedexpressionisreturned.Theoriginallistremainsunchanged.

( s e t' x2' a' ( de ) ) ( s e t' f o o' a ) ( e x p a n df o o' a ) ( de ) ( e x p a n d' ( axb )' x ) ( a2b ) ( e x p a n d' ( ax( bcx ) )' x ) ( a2( bc2 ) ) ( e x p a n d' ( ax( bcx ) )' x' a ) ( ( de )2( bc2 ) ) e x p a n d isusefulwhencomposinglambdaexpressionsanddoingvariableexpansionasinrewritemacros. ( d e f i n e( r a i s e t op o w e r ) ( e x p a n d( f n( b a s e )( p o wb a s ep o w e r ) )' p o w e r ) ) ( d e f i n es q u a r e( r a i s e t o2 ) ) ( d e f i n ec u b e( r a i s e t o3 ) ) ( s q u a r e5 ) 2 5 ( c u b e5 ) 1 2 5

Ifmorethanonesymbolispresent,e x p a n d willworkinanincrementalfashion:
( s e t' a' ( bc ) ) ( s e t' b1 ) ( e x p a n d' ( abc )' a' b ) ( ( 1c )1c )

Liketheapplyfunction,e x p a n d reducesitsargumentlist. syntax:(expandlistlistassoc[bool]) Thesecondsyntaxofe x p a n d allowsexpansionbindingstobespecifiedonthefly,withoutperformingasetontheparticipating variables: Iftheboolevaluatestot r u e ,thevaluepartsintheassociationlistareevaluated.


( e x p a n d' ( abc )' ( ( a1 )( b2 ) ) ) ( 12c ) ( e x p a n d' ( abc )' ( ( a1 )( b2 )( c( xyz ) ) ) ) ( 12( xyz ) ) ( e x p a n d' ( ab )' ( ( a( +12 ) )( b( +34 ) ) ) ) ( ( +12 )( +34 ) ) ( e x p a n d' ( ab )' ( ( a( +12 ) )( b( +34 ) ) )t r u e )( 37 )

Notethatthecontentsofthevariablesintheassociationlistwillnotchange.Thisisdifferentfromtheletexfunction,where variablesaresetbyevaluatingandassigningtheirassociationparts. Thisformofe x p a n d isfrequentlyusedinlogicprogramming,togetherwiththeunifyfunction. syntax:(expandlist) Athirdsyntaxisusedtoexpandonlythecontentsofvariablesstartingwithanuppercasecharacter.ThisPROLOGmodemayalso beusedinthecontextoflogicprogramming.Asinthefirstsyntaxofe x p a n d ,symbolsmustbepreset.Onlyuppercasevariables andthoseboundtoanythingotherthann i l willbeexpanded:
( s e t' A1' B v a r2' Cn i l' d5' e6 ) ( e x p a n d' ( A( B v a r )Cdef ) ) ( 1( 2 )Cdef )

OnlythesymbolsA andB v a r areexpandedbecausetheyhavecapitalizednamesandnonn i l contents. Thecurryingfunctionintheexampledemonstratingthefirstsyntaxofe x p a n d cannowbewrittenevenmoresimplyusingan uppercasevariable:


( d e f i n e( r a i s e t oP o w e r ) ( e x p a n d( f n( b a s e )( p o wb a s eP o w e r ) ) ) ) >( d e f i n ec u b e( r a i s e t o3 ) ) ( l a m b d a( b a s e )( p o wb a s e3 ) ) >( c u b e4 ) 6 4

>_

Seetheletexfunction,whichalsoprovidesanexpansionmechanism,andthefunctionunify,whichisfrequentlyusedtogetherwith e x p a n d .

explodeutf8
syntax:(explodestr[intchunk[bool]]) syntax:(explodelist[intchunk[bool]]) Inthefirstsyntax,e x p l o d e transformsthestring(str)intoalistofsinglecharacterstrings.Optionally,achunksizecanbespecified inintchunktobreakthestringintomulticharacterchunks.Whenspecifyingavalueforboolotherthann i l ,thelastchunkwillbe omittedifitdoesnothavethefulllengthspecifiedinintchunk.
( e x p l o d e" n e w L I S P " ) ( " n "" e "" w "" L "" I "" S "" P " ) ( j o i n( e x p l o d e" k e e pi tt o g e t h e r " ) ) " k e e pi tt o g e t h e r " ( e x p l o d e" n e w L I S P "2 ) ( e x p l o d e" n e w L I S P "3 ) ( " n e "" w L "" I S "" P " ) ( " n e w "" L I S "" P " )

;o m i tl a s tc h u n ki ft o os h o r t ( e x p l o d e" n e w L I S P "3t r u e ) ( " n e w "" L I S " )

OnlyonnonUTF8enabledversions,e x p l o d e alsoworksonbinarycontent:
( e x p l o d e" \ 0 0 0 \ 0 0 1 \ 0 0 2 \ 0 0 3 " ) ( " \ 0 0 0 "" \ 0 0 1 "" \ 0 0 2 "" \ 0 0 3 " )

WhencalledinUTF8enabledversionsofnewLISP,e x p l o d e willworkoncharacterboundariesratherthanbyteboundaries.In UTF8encodedstrings,charactersmaycontainmorethanonebyte.Processingwillstopwhenazerobytecharacterisfound. ToexplodebinarycontentsonUTF8enabledversionsofnewLISPuseunpackasshowninthefollowingexample:


( s e t' s t r" \ 0 0 1 \ 0 0 2 \ 0 0 3 \ 0 0 4 " )" \ 0 0 1 \ 0 0 2 \ 0 0 3 \ 0 0 4 " ( u n p a c k( d u p" c "( l e n g t hs t r ) )s t r )( 1234 ) ( u n p a c k( d u p" s "( l e n g t hs t r ) )s t r )( " \ 0 0 1 "" \ 0 0 2 "" \ 0 0 3 "" \ 0 0 4 " )

Inthesecondsyntax,e x p l o d e explodesalist(list)intosublistsofchunksizeintchunk,whichis1(one)bydefault. Thefollowingshowsanexampleofthelastchunkbeingomittedwhenthevalueforboolisotherthann i l ,andthechunkdoesnot havethefulllengthspecifiedinintchunk.


( e x p l o d e' ( abcdefgh ) ) ( ( a )( b )( c )( d )( e )( f )( g )( h ) ) ( e x p l o d e' ( abcdefg )2 ) ( ( ab )( cd )( ef )( g ) ) ;o m i tl a s tc h u n ki ft o os h o r t ( e x p l o d e' ( abcdefg )2t r u e ) ( ( ab )( cd )( ef ) ) ( t r a n s p o s e( e x p l o d e' ( abcdefgh )2 ) ) ( ( aceg )( bdfh ) )

Thejoinandappendfunctionsareinverseoperationsofe x p l o d e .

extend!

syntax:(extendlist1[list2...]) syntax:(extendstring1[string2...]) Thelistinlist1isextendedbyappendinglist2.Morethanonelistmaybeappended. Thestringinstring1isextendedbyappendingstring2.Morethanonestringmaybeappended.Thestringcancontainbinary0 (zero)characters. Thefirstparametercanbeanuninitializedvariable. Theextendedlistorstringisreturned.


;e x t e n d i n gl i s t s ( e x t e n dl s t' ( ab )' ( cd ) )( abcd ) ( e x t e n dl s t' ( efg ) )( abcdef ) l s t( abcdefg ) ;e x t e n d i n gs t r i n g s ( e x t e n ds t r" a b "" c d " )" a b c d " ( e x t e n ds t r" e f g " )" a b c d e f g " s t r" a b c d e f g " ;e x t e n d i n gi np l a c e ( s e t' L' ( ab" C D "( ef ) ) ) ( e x t e n d( L2 )" E " ) L( ab" C D E "( ef ) ) ( e x t e n d( L3 )' ( g ) ) L( ab" C D E "( efg ) )

Foranondestructivelistorstringextensionseeappend.

factor
syntax:(factorint) Factorsthenumberinintintoitsprimecomponents.Whenfloatingpointnumbersarepassed,theyaretruncatedtotheirintegerpart first.
( f a c t o r1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 ) ( 3371 11 31 93 6 0 73 8 0 35 2 5 7 9 ) ; ;c h e c kc o r r e c t n e s so ff a c t o r i n g ( =( a p p l y*( f a c t o r1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 ) )1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 ) t r u e ; ;f a c t o rt h eb i g g e s ti n t e g e r ( f a c t o r9 2 2 3 3 7 2 0 3 6 8 5 4 7 7 5 8 0 7 ) ( 777 31 2 73 3 79 2 7 3 76 4 9 6 5 7 ) ; ;p r i m e s . l s p-r e t u r na l lp r i m e si nal i s t ,u pt on ( d e f i n e( p r i m e sn,p ) ( d o t i m e s( en ) ( i f( =( l e n g t h( f a c t o re ) )1 ) ( p u s hep1 ) ) )p ) ( p r i m e s2 0 ) ( 23571 11 31 71 9 ) f a c t o r returnsn i l fornumberssmallerthan2 .Fornumberslargerthan9,223,372,036,854,775,807(thelargest64bitinteger)

convertedfromfloatingpointnumbers,thelargestintegerisfactored.

fft
syntax:(fftlistnum) CalculatesthediscreteFouriertransformonthelistofcomplexnumbersinlistnumusingtheFFTmethod(FastFourierTransform). Eachcomplexnumberisspecifiedbyitsrealpartfollowedbyitsimaginarypart.Ifonlyrealnumbersareused,theimaginarypartis setto0 . 0 (zero).Whenthenumberofelementsinlistnumisnotapowerof2,f f t increasesthenumberofelementsbypadding thelistwithzeroes.Whentheimaginarypartofacomplexnumberis0 ,simplenumberscanbeusedinstead.
( i f f t( f f t' ( ( 10 )( 20 )( 30 )( 40 ) ) ) ) ( ( 10 )( 20 )( 30 )( 40 ) ) ; ;w h e ni m a g i n a r yp a r ti s0 ,p l a i nn u m b e r sw o r k ,t o o ; ;c o m p l e xn u m b e r sc a nb ei n t e r m i x e d ( f f t' ( 1234 ) ) ( ( 1 00 )( 22 )( 20 )( 22 ) ) ( f f t' ( 12( 30 )4 ) ) ( ( 1 00 )( 22 )( 20 )( 22 ) )

Theinverseoperationoff f t istheifftfunction.

fileinfo
syntax:(fileinfostrname[intindex[boolflag]]) Returnsalistofinformationaboutthefileordirectoryinstr_name.Theoptionalindexspecifiesthelistmembertoreturn.Whenno boolflagisspecifiedorwhenboolflagevaluateston i l informationaboutthelinkisreturnedifthefileisalinktoanoriginalfile. Ifboolflagevaluatestoanythingelsethann i l ,informationabouttheoriginalfilereferencedbythelinkisreturned. offset contents 0 size 1 mode(differswitht r u e flag) 2 devicemode 3 userID 4 groupID 5 accesstime 6 modificationtime 7 statuschangetime

Dependingonboolflagset,thefunctionreportsoneitherthelink(noflagorn i l flag)orontheoriginallinkedfile(t r u e flag).


( f i l e i n f o" . b a s h r c " ) ( 1 2 43 3 1 8 805 0 009 2 0 9 5 1 0 2 29 2 0 9 5 1 0 2 29 2 0 9 5 3 0 7 4 ) ( f i l e i n f o" . b a s h r c "0 ) 1 2 4 ( d a t e( f i l e i n f o" / e t c "1 ) ) " M o nM a r81 8 : 2 3 : 1 72 0 0 5 "

Inthesecondexample,thelaststatuschangedateforthedirectory/etcisretrieved.
f i l e i n f o givesfilestatistics(size)foralinkedfile,notthelink,exceptforthemodefield.

file?
syntax:(file?strpathname[bool]) Checksfortheexistenceofafileinstrname.Returnst r u e ifthefileexistsotherwise,itreturnsn i l .Thisfunctionwillalsoreturn t r u e fordirectories.Iftheoptionalboolvalueist r u e ,thefilemustnotbeadirectoryandstrpathnameisreturnedorn i l ifthe fileisadirectory.Theexistenceofafiledoesnotimplyanythingaboutitsreadorwritepermissionsforthecurrentuser.
( i f( f i l e ?" a f i l e " )( s e t' f i l e N o( o p e n" a f i l e "" r e a d " ) ) ) ( f i l e ?" / u s r / b i n / n e w l i s p "t r u e )" / u s r / b i n / n e w l i s p " ( f i l e ?" / u s r / b i n / f o o "t r u e ) n i l

filter
syntax:(filterexppredicateexplist) Thepredicateexppredicateisappliedtoeachelementofthelistexplist.Alistisreturnedcontainingtheelementsforwhichexp predicateistrue.f i l t e r workslikeclean,butwithanegatedpredicate.
( f i l t e rs y m b o l ?' ( 12d4fg5h ) ) ( dfgh ) ( d e f i n e( b i g ?x )( >x5 ) ) ( l a m b d a( x )( >x5 ) ) ( f i l t e rb i g ?' ( 11 036451 1 ) ) ( 1 061 1 ) ;f i l t e rw i t hc o m p a r i s o nf u n c t o r ( s e t' L' ( ( a1 027 )( b5 )( a83 )( c8 )( a9 ) ) ) ( f i l t e r( c u r r ym a t c h' ( a* ) )L ) ( f i l t e r( c u r r ym a t c h' ( ?? ) )L ) ( ( a1 027 )( a83 )( a9 ) ) ( ( b5 )( c8 )( a9 ) )

( f i l t e r( c u r r ym a t c h' ( *8* ) )L )( ( a83 )( c8 ) )

Thepredicatemaybeabuiltinpredicate,auserdefinedfunction,oralambdaexpression. Forfilteringalistofelementswiththeelementsfromanotherlist,usethedifferencefunctionorintersect(withthelistoption). Seealsotherelatedfunctionindex,whichreturnstheindicesofthefilteredelementsandclean,whichreturnsallelementsofalist forwhichapredicateisfalse.

find
syntax:(findexpkeylist[funccompare|intregexoption]) syntax:(findstrkeystrdata[intregexoption[intoffset]])

Findanexpressioninalist
Ifthesecondargumentevaluatestoalist,thenf i n d returnstheindexposition(offset)oftheelementderivedfromevaluatingexp key.

Optionally,anoperatororuserdefinedfunctioncanbespecifiedinfunccompare.Iftheexpkeyisastring,aregularexpression optioncanbespecifiedwiththeintregexoptionparameter. Whenusingregularexpressionsorcomparisonfunctorsthesystemvariable$ 0 issettothelastelementfound.


;f i n da ne x p r e s s i o ni nal i s t ( f i n d' ( 12 )' ( ( 14 )56( 12 )( 89 ) ) ) 3 ( f i n d" w o r l d "' ( " h e l l o "" w o r l d " ) ) ( f i n d" h i "' ( " h e l l o "" w o r l d " ) ) 1 n i l

( f i n d" n e w l i s p "' ( " P e r l "" P y t h o n "" n e w L I S P " )1 ) 2 ;u s et h ec o m p a r i s o nf u n c t o r ( f i n d3' ( 843 726 )> ) 4 $ 02 ( f i n d" n e w l i s p "' ( " P e r l "" P y t h o n "" n e w L I S P " ) ( f n( xy )( r e g e xxy1 ) ) )2 $ 0" n e w L I S P " ( f i n d5' ( ( l3 )( k5 )( a1 0 )( z2 2 ) ) ( f n( xy )( =x( l a s ty ) ) ) ) 1 $ 0( k5 ) ( f i n d' ( a? )' ( ( l3 )( k5 )( a1 0 )( z2 2 ) )m a t c h ) 2 $ 0( a1 0 ) ( f i n d' ( XX )' ( ( ab )( cd )( ee )( fg ) )u n i f y ) 2 $ 0( ee ) ;d e f i n et h ec o m p a r i s o nf u n c t o rf i r s tf o rb e t t e rr e a d a b i l i t y ( d e f i n e( h a s i t a s l a s txy )( =x( l a s ty ) ) ) ( f i n d2 2' ( ( l3 )( k5 )( a1 0 )( z2 2 ) )h a s i t a s l a s t ) 3 $ 0( z2 2 )

Usingmatchandunify,listsearchescanbeformulatedwhichareaspowerfulasregularexpressionsearchesareforstrings.

Findastringinastring
Ifthesecondargument,strdata,evaluatestoastring,thentheoffsetpositionofthestringstrkey(foundinthefirstargument,str data)isreturned.Inthiscase,f i n d alsoworksonbinarystrdata.Theoffsetpositionreturnedisalwaysbasedoncountingsingle bytecharactersevenwhenrunningtheUTF8enabledversionofnewLISP. Thepresenceofathirdparameterspecifiesasearchusingtheregularexpressionpatternspecifiedinstrpattern,aswellasanoption numberspecifiedinintregexoption(i.e.,1(one)forcaseinsensitivesearchor0 (zero)fornospecialoptions).Ifintregexoptionis specifiedanoptionalintoffsetargumentcanbespecifiedtootostartthesearchnotatthebeginningbutattheoffsetgiven.Inany casethepositionreturnedbyf i n d iscalculatedrelativetothebeginningofthestring. Tospecifyintoffsetinasimplestringsearchwithoutregularexpressions,specifyn i l forintregexoption. InnewLISP,regularexpressionsarestandardPerlCompatibleRegularExpression(PCRE)searches.Foundexpressionsor subexpressionsarereturnedinthesystemvariables$ 0 ,$ 1 ,$ 2 ,etc.,whichcanbeusedlikeanyothersymbol.Asanalternative,the contentsofthesevariablescanalsobeaccessedbyusing( $0 ) ,( $1 ) ,( $2 ) ,etc.Thismethodallowsindexedaccess(i.e.,( $i ) , wherei isaninteger). Seeregexforthemeaningoftheoptionnumbersandmoreinformationonregularexpressionsearching.
;s i m p l es t r i n gs e a r c h ( f i n d" w o r l d "" H e l l ow o r l d " ) 6 ( f i n d" W O R L D "" H e l l ow o R L d " ) n i l ;c a s e i n s e n s i t i v er e g e x ( f i n d" W o r l D "" H e l l ow o R L d "1 ) 6

( f i n d" h i "" h e l l ow o r l d " ) ( f i n d" H e l l o "" H e l l ow o r l d " ) ;r e g e xw i t hd e f a u l to p t i o n s

n i l 0

( f i n d" c a t | d o g "" Ih a v eac a t "0 ) $ 0 ( f i n d" c a t | d o g "" m yd o g "0 ) $ 0 ( f i n d" c a t | d o g "" M YD O G "1 ) $ 0

9 " c a t " 3 " d o g " 3 " D O G "

;u s ea no p t i o n a lo f f s e t ( f i n d" c a t | d o g "" Ih a v eac a ta n dad o g "0 ) 9 ( f i n d" c a t | d o g "" Ih a v eac a ta n dad o g "01 2 )1 9 ; ;f i n dw i t hs u b e x p r e s s i o n si nr e g u l a re x p r e s s i o n ; ;a n da c c e s sw i t hs y s t e mv a r i a b l e s ( s e t' s t r " h t t p : / / n u e v a t e c . c o m : 8 0 " ) ( f i n d" h t t p : / / ( . * ) : ( . * ) "s t r0 ) 0 $ 0 " h t t p : / / n u e v a t e c . c o m : 8 0 " $ 1 " n u e v a t e c . c o m " $ 2 " 8 0 " ; ;s y s t e mv a r i a b l e sa sa ni n d e x e de x p r e s s i o n( s i n c e8 . 0 . 5 ) ( $0 ) " h t t p : / / n u e v a t e c . c o m : 8 0 " ( $1 ) " n u e v a t e c . c o m " ( $2 ) " 8 0 "

Forotherfunctionsusingregularexpressions,seedirectory,findall,parse,regex,replace,andsearch. Tofindexpressionsinnestedormultidimensionallists,usetherefandrefallfunctions.

findall
syntax:(findallstrregexpatternstrtext[exp[intregexoption]]) syntax:(findalllistmatchpatternlist[exp]) syntax:(findallexpkeylist[exp[funccompare]]) Inthefirstsyntax,f i n d a l l findsalloccurrencesofstrregexpatterninthetextstrtext,returningalistcontainingallmatching strings.Theemptylist( ) isreturnedifnomatchesarefound.Inthefirstsyntaxstringsearchesarealwaysdoneusingregular expressionpatterns,evenifnointregexoptionisspecified.Thesystemvariable$ c o u n t isupdatedwiththenumberofmatches found. Optionally,anexpressioncanbespecifiedtoprocessthefoundstringorregularsubexpressionsbeforeplacingthemintothe returnedlist.Anadditionaloption,intoption,specifiesspecialregularexpressionoptions(seeregexforfurtherdetails).
( f i n d a l l{ \ d + }" l k j h k l j h 3 4 g h f d h g f d 6 7 8 g f d h f g d 9 " ) ( " 3 4 "" 6 7 8 "" 9 " ) $ c o u n t3 ( f i n d a l l{ ( n e w ) ( l i s p ) }" n e w L I S P i s N E W L I S P "( a p p e n d$ 2$ 1 )1 ) ( " L I S P n e w "" L I S P N E W " ) ( u n i q u e( s o r t ( f i n d a l l{ [ a z A Z ] + } ( r e p l a c e" < [ ^ > ] + > "( g e t u r l" h t t p : / / n e w l i s p . o r g " )" "0 )) ) ) ( " A "" A C C "" A I "" A P I "" A b o u t "" A l l "" A m a z i n g "" A p p s " . . . " w h e r e "" w h o l e "" w i d t h "" w i k i "" w i l l "" w i t h "" w o r k "" w r i t t e n " )

;u s e$ c o u n ti ne v a l u a t e de x p r ( f i n d a l l" a "" a b a b a b "( s t r i n g$ c o u n t$ i t ) )( " 1 a "" 2 a "" 3 a " )

Thefirstexamplediscoversallnumbersinatext.Thesecondexampleshowshowanoptionalexpressioninexpcanworkon subexpressionsfoundbytheregularexpressionpatterninstrpattern.Thelastexampleretrievesawebpage,cleansoutallHTML tags,andthencollectsallwordsintoauniqueandsortedlist. Notethatf i n d a l l withstringsalwaysperformsaregularexpressionsearch,eveniftheoptioninintoptionisomitted. Inthesecondsyntax,f i n d a l l searchesforalllistmatchpatternslistmatchpatterninlist.Asinf i n d a l l forstrings,an expressioncanbespecifiedinexptoprocessfurtherthematchedsublistfoundinlist.Thesystemvariable$ c o u n t isupdatedwith thenumberofmatchesfound.
( f i n d a l l' ( ?2 )' ( ( a1 )( b2 )( a2 )( c4 ) ) )( ( b2 )( a2 ) ) ( f i n d a l l' ( ?2 )' ( ( a1 )( b2 )( a2 )( c4 ) )( f i r s t$ i t ) )( ba ) $ c o u n t2 f i n d a l l forlistmatchesalwaysusesmatchtocomparewhensearchingforsublistsandalwaysneedsalistforthepattern

expression. Inthethirdsyntax,f i n d a l l canspecifyabuiltinoruserdefinedfunctionusedforcomparinglistelementswiththekey expressioninexpkey:


( f i n d a l l5' ( 27459249748 )$ i t< )( 79978 ) ;p r o c e s st h ef o u n de l e m e n ta v a i l a b l ei n$ i t ( f i n d a l l5' ( 27459249748 )( *3$ i t )< )( 2 12 72 72 12 4 ) ;s a m ea s ( f i n d a l l5' ( 27459249748 )( *3$ i t )( f n( xy )( <xy ) ) )( 2 12 72 72 12 4 ) ( f i n d a l l5' ( 27459249748 )( " a b c d e f g h i j k "$ i t )< )( " h "" j "" j "" h "" i " ) $ c o u n t5 ;u s e$ c o u n t ( f i n d a l l' a' ( ababab )( l i s t$ c o u n t$ i t ) )( ( 1a )( 2a )( 3a ) )

Anytypeofexpressioncanbesearchedfororcanbecontainedinthelist.f i n d a l l inthissyntaxworkssimilartofilterbutwith theaddedbenefitofbeingabletodefineaprocessingexpressionforthefoundelement. Ifnofunccompareisdefinedandexpkeyisalist,thenmatchwillbeusedforcomparison,asinthesecondsyntax.

firstutf8
syntax:(firstlist) syntax:(firstarray) syntax:(firststr) Returnsthefirstelementofalistorthefirstcharacterofastring.Theoperandisnotchanged.Thisfunctionisequivalenttocaror headinotherLispdialects.
( f i r s t' ( 12345 ) ) 1 ( f i r s t' ( ( ab )cd ) ) ( ab ) ( s e t' a L i s t' ( abcde ) ) ( abcde ) ( f i r s ta L i s t ) a a L i s t ( abcde ) ( s e t' A( a r r a y32( s e q u e n c e16 ) ) )

( ( 12 )( 34 )( 56 ) ) ( f i r s tA ) ( f i r s t' ( ) )

( 12 ) E R R :l i s ti se m p t y

Inthethirdsyntax,thefirstcharacterisreturnedfromthestringinstrasastring.
( f i r s t" n e w L I S P " ) " n " ( f i r s t( r e s t" n e w L I S P " ) ) " e "

NotethatfirstworksoncharacterboundariesratherthanbyteboundarieswhentheUTF8enabledversionofnewLISPisused. Seealsothefunctionslastandrest.

flat
syntax:(flatlist[intlevel]) Returnsaflattenedlistfromalist:
( s e t' l s t' ( a( b( cd ) ) ) ) ( f l a tl s t ) ( abcd ) ;e x t r a c tal i s to fi n d e xv e c t o r so fa l le l e m e n t s ( m a p( f n( x )( r e fxl s t ) )( f l a tl s t ) ) ( ( 0 )( 10 )( 110 )( 111 ) )

Theoptionalintlevelparametercanbeusedtolimittherecursionlevelwhenflatteningthelist:
( f l a t' ( ab( cd( ef ) )( gh( ij ) ) )) ( abcdefghij )

( f l a t' ( ab( cd( ef ) )( gh( ij ) ) )1 ) ( abcd( ef )gh( ij ) ) ( f l a t' ( ab( cd( ef ) )( gh( ij ) ) )2 ) ( abcdefghij )

Ifintlevelis0 ,noflatteningwilloccur.
f l a t canbeusedtoiteratethroughnestedlists.

float
syntax:(floatexp[expdefault]) Iftheexpressioninexpevaluatestoanumberorastring,theargumentisconvertedtoafloatandreturned.Ifexpcannotbe convertedtoafloatthenn i l or,ifspecified,theevaluationofexpdefaultwillbereturned.Thisfunctionismostlyusedtoconvert stringsfromuserinputorwhenreadingandparsingtext.Thestringmuststartwithadigitorthe+ (plussign),(minussign),or. (period).Ifexpisinvalid,f l o a t returnsn i l asadefaultvalue. Floatswithexponentslargerthan1e308orsmallerthan1e308areconvertedto+INForINF,respectively.Thedisplayof+INF andINFdiffersondifferentplatformsandcompilers.
( f l o a t" 1 . 2 3 " ) ( f l o a t"1 . 2 3 " ) ( f l o a t" . 5 " ) ( f l o a t" 1 . 2 3 " ) ( f l o a t" . 5 " ) ( f l o a t" # 1 . 2 3 " ) 1 . 2 3 1 . 2 3 0 . 5 0 1 . 2 3 n i l n i l

( f l o a t" # 1 . 2 3 "0 . 0 ) 0 ( f l o a t ?1 2 3 ) n i l ( f l o a t ?( f l o a t1 2 3 ) ) t r u e ( f l o a t' ( abc ) ) n i l ( f l o a t' ( abc )0 ) 0 ( f l o a tn i l0 ) 0 ( f l o a t" a b c "" n o tan u m b e r " ) " n o tan u m b e r " ( f l o a t" 1 e 5 0 0 " ) i n f ( f l o a t" 1 e 5 0 0 " ) i n f ( p r i n t" E n t e raf l o a tn u m : " ) ( s e t' f n u m( f l o a t( r e a d l i n e ) ) )

Usetheintfunctiontoparseintegernumbers.

float?
syntax:(float?exp)
t r u e isreturnedonlyifexpevaluatestoafloatingpointnumberotherwise,n i l isreturned. ( s e t' n u m1 . 2 3 ) ( f l o a t ?n u m ) t r u e

floor
syntax:(floornumber) Returnsthenextlowestintegerbelownumberasafloatingpoint.
( f l o o r1 . 5 ) 2 ( f l o o r3 . 4 ) 3

Seealsotheceilfunction.

flt
syntax:(fltnumber) Convertsnumbertoa32bitfloatrepresentedbyaninteger.Thisfunctionisusedwhenpassing32bitfloatstolibraryroutines. newLISPfloatingpointnumbersare64bitandarepassedas64bitfloatswhencallingimportedClibraryroutines.
( f l t1 . 2 3 ) 1 0 6 7 2 8 2 5 9 6 ; ;p a s s3 2 b i tf l o a tt oC f u n c t i o n :f o o ( f l o a tv a l u e ) ( i m p o r t" m y l i b . s o "" f o o " ) ( f o o( f l t1 . 2 3 ) ) ( g e t i n t( p a c k" f "1 . 2 3 ) ) 1 0 6 7 2 8 2 5 9 6 ( u n p a c k" f "( p a c k" l d "( f l t1 . 2 3 4 5 ) ) ) ( 1 . 2 3 4 5 0 0 0 5 1 )

Thelasttwostatementsillustratetheinnerworkingsoff l t . Usetheimportfunctiontoimportlibraries.

fn
syntax:(fn(listparameters)expbody)
f n isusedtodefineanonymousfunctions,whicharefrequentlyusedinmap,sort,andmanyotherfunctionswherefunctionscanbe

usedasarguments. Usingananonymousfunctioneliminatestheneedtodefineanewfunctionwithdefine.Instead,afunctionisdefinedonthefly:
( m a p( f n( x )( +xx ) )' ( 12345 ) )( 24681 0 ) ( s o r t' ( " . . "" . . . "" . "" . . . . . " )( f n( xy )( >( l e n g t hx )( l e n g t hy ) ) ) ) ( " . . . . . "" . . . "" . . "" . " )

Theexampledefinesthefunctionfn(x),whichtakesaninteger(x)anddoublesit.Thefunctionismappedontoalistofarguments usingmap.Thesecondexampleshowsstringsbeingsortedbylength. Thelambdafunction(thelonger,traditionalform)canbeusedinplaceoff n .

for
syntax:(for(symnumfromnumto[numstep[expbreak]])body) Repeatedlyevaluatestheexpressionsinbodyforarangeofvaluesspecifiedinnumfromandnumto,inclusive.Astepsizemaybe specifiedwithnumstep.Ifnostepsizeisspecified,1 isassumed. Optionally,aconditionforearlyloopexitmaybedefinedinexpbreak.Ifthebreakexpressionevaluatestoanynonn i l value,the f o r loopreturnswiththevalueofexpbreak.Thebreakconditionistestedbeforeevaluatingbody.Ifabreakconditionisdefined, numstepmustbedefined,too. Thesymbolsymislocalindynamicscopetothef o r expression.Ittakesoneachvaluesuccessivelyinthespecifiedrangeasan integervalueifnostepsizeisspecified,orasafloatingpointvaluewhenastepsizeispresent.Afterevaluationofthef o r statement symassumesitspreviousvalue.
>( f o r( x11 02 )( p r i n t l nx ) ) 1 3 5 7 9 >( f o r( x860 . 5 )( p r i n t l nx ) ) 8 7 . 5 7 6 . 5 6 >( f o r( x11 0 02( >( *xx )3 0 ) )( p r i n t l nx ) ) 1 3 5

t r u e >_

Thesecondexampleusesarangeofnumbersfromhighesttolowest.Notethatthestepsizeisalwaysapositivenumber.Inthethird example,abreakconditionistested. Usethesequencefunctiontomakeasequenceofnumbers.

forall
syntax:(forallfuncconditionlist) Appliesthefunctioninfuncconditiontoallelementsinlist.Ifallelementsmeettheconditioninfunccondition,theresultist r u e otherwise,n i l isreturned.
( f o r a l ln u m b e r ?' ( 23467 ) ) ( f o r a l ln u m b e r ?' ( 2346" h e l l o "7 ) ) t r u e n i l

( f o r a l l( f n( x )( =x1 0 ) )' ( 1 01 01 01 01 0 ) ) t r u e

Usetheexistsfunctiontocheckifatleastoneelementinalistmeetsacondition.

fork
syntax:(forkexp) TheexpressioninexpislaunchedasanewLISPchildprocessthreadoftheplatformsOS.Thenewprocessinheritstheentire addressspace,butrunsindependentlysosymbolorvariablecontentschangedinthechildprocesswillnotaffecttheparentprocess orviceversa.Thechildprocessendswhentheevaluationofexpfinishes. Onsuccess,f o r k returnswiththechildprocessIDonfailure,n i l isreturned.Seealsothewaitpidfunction,whichwaitsfora childprocesstofinish. ThisfunctionisonlyavailableonLinux/UnixversionsofnewLISPandisbasedonthef o r k ( ) implementationoftheunderlying OS. AmuchsimplerautomatedmethodtolaunchprocessesandcollectresultsisavailablewithspawnandtheCilkAPI.
>( s e t' x0 ) 0 >( f o r k( w h i l e( <x2 0 )( p r i n t l n( i n cx ) )( s l e e p1 0 0 0 ) ) ) 1 7 6 >1 2 3 4 5 6

Theexampleillustrateshowthechildprocessthreadinheritsthesymbolspaceandhowitisindependentoftheparentprocess.The f o r k statementreturnsimmediatelywiththeprocessID1 7 6 .Thechildprocessincrementsthevariablex byoneeachsecondand printsittostandardout(boldface).Intheparentprocess,commandscanstillbeentered.Typex toseethatthesymbolx stillhasthe value0 (zero)intheparentprocess.Althoughstatementsenteredwillmixwiththedisplayofthechildprocessoutput,theywillbe

correctlyinputtotheparentprocess. Thesecondexampleillustrateshowpipecanbeusedtocommunicatebetweenprocesses.
# ! / u s r / b i n / n e w l i s p ( d e f i n e( c o u n t d o w n p r o cxc h a n n e l ) ( w h i l e( ! =x0 ) ( w r i t e l i n ec h a n n e l( s t r i n gx ) ) ( d e cx ) ) ) ( d e f i n e( o b s e r v e r p r o cc h a n n e l ) ( d o u n t i l( =i" 1 " ) ( p r i n t l n" p r o c e s s"( s e t qi( r e a d l i n ec h a n n e l ) ) ) ) ) ( m a ps e t' ( i no u t )( p i p e ) ) ( s e t' o b s e r v e r( f o r k( o b s e r v e r p r o ci n ) ) ) ( s e t' c o u n t e r( f o r k( c o u n t d o w n p r o c5o u t ) ) ) ;a v o i dz o m b i e s ( w a i t p i do b s e r v e r ) ( w a i t p i dc o u n t e r ) ( e x i t )

Thefollowingoutputisgeneratedbyobserverproc
p r o c e s s5 p r o c e s s4 p r o c e s s3 p r o c e s s2 p r o c e s s1

Thec o u n t d o w n p r o c writesnumberstothecommunicationpipe,wheretheyarepickedupbytheo b s e r v e r p r o c e s s and displayed. Aforkedprocesscaneitherexitbyitselforitcanbedestroyedusingthedestroyfunction.


( d e f i n e( f o r k d e s t r o y d e m o ) ( s e t' p i d( f o r k( d o t i m e s( i1 0 0 0 )( p r i n t l ni )( s l e e p1 0 ) ) ) ) ( s l e e p5 0 ) ( d e s t r o yp i d ) ) >( f o r k d e s t r o y d e m o ) 0 1 2 3 4 t r u e >

Theprocessstartedbyf o r k d e s t r o y d e m o willnotfinishbutisdestroyed50millisecondsafterstartbyacalltodestroy. Usethesemaphorefunctionforsynchronizingprocessesandshareforsharingmemorybetweenprocesses. Seespawnforamuchsimplerandautomatedwaytosynchronizeprocessesandcollectresults.

format
syntax:(formatstrformatexpdata1[expdata2...]) syntax:(formatstrformatlistdata)

Constructsaformattedstringfromexpdata1usingtheformatspecifiedintheevaluationofstrformat.Theformatspecifiedis identicaltotheformatusedforthep r i n t f ( ) functionintheANSIClanguage.Twoormoreexpdataargumentscanbespecified formorethanoneformatspecifierinstrformat. Inanalternativesyntax,thedatatobeformattedcanbepassedinsidealistinlistdata.


f o r m a t checksforavalidformatstring,matchingdatatype,andthecorrectnumberofarguments.Wrongformatsordatatypes

resultinerrormessages.int,float,orstringcanbeusedtoensurecorrectdatatypesandtoavoiderrormessages. Theformatstringhasthefollowinggeneralformat: "%w.pf" The% (percentsign)startsaformatspecification.Todisplaya% insideaformatstring,doubleit:% % Thew representsthewidthfield.Dataisrightaligned,exceptwhenprecededbyaminussign,inwhichcaseitisleftaligned.If precededbya+ (plussign),positivenumbersaredisplayedwitha+ .Whenprecededbya0 (zero),theunusedspaceisfilledwith leadingzeroes.Thewidthfieldisoptionalandservesalldatatypes. Thep representstheprecisionnumberofdecimals(floatingpointonly)orstringsandisseparatedfromthewidthfieldbyaperiod. Precisionisoptional.Whenusingtheprecisionfieldonstrings,thenumberofcharactersdisplayedislimitedtothenumberinp . Thef representsatypeflagandisessentialitcannotbeomitted. Belowarethetypesinf : format description s textstring c character(value1255) d decimal(32bit) u unsigneddecimal(32bit) x hexadecimallowercase X hexadecimaluppercase o octal(32bits)(notsupportedonallofnewLISPflavors) f floatingpoint e scientificfloatingpoint E scientificfloatingpoint g generalfloatingpoint

Formatting64bitnumbersusing32bitformatspecifierswilltruncateandformatthelower32bitsofthenumber. For64bitnumbersusethefollowingformatstringsonUnixlikeoperatingsystems: format description lld decimal(64bit) llu unsigneddecimal(64bit) llx hexadecimal(64bit) llX hexadecimaluppercase(64bit)

For64bitnumbers(sinceversion8.9.7)usethefollowingformatstringsonTru64Unix: format description ld decimal(64bit)

lu lx lX

unsigneddecimal(64bit) hexadecimal(64bit) hexadecimaluppercase(64bit)

OnWin32platformsthefollowingcharactersapplyfor64bitnumbers: format description I64d decimal(64bit) I64u unsigneddecimal(64bit) I64x I64X hexadecimal(64bit) hexadecimaluppercase(64bit)

Othertextmayoccurbetween,before,oraftertheformatspecs. NotethatonTru64Unixtheformatcharacteri canbeusedinsteadofd .

( f o r m a t" > > > % 6 . 2 f < < < "1 . 2 3 4 5 ) ( f o r m a t" > > > % 6 . 2 f < < < "1 . 2 3 4 5 ) ( f o r m a t" > > > % + 6 . 2 f < < < "1 . 2 3 4 5 ) ( f o r m a t" > > > % + 6 . 2 f < < < "1 . 2 3 4 5 ) ( f o r m a t" > > > % + 6 . 2 f < < < "1 . 2 3 4 5 ) ( f o r m a t" % e "1 2 3 4 5 6 7 8 9 ) ( f o r m a t" % 1 2 . 1 0 E "1 2 3 4 5 6 7 8 9 ) ( f o r m a t" % 1 0 g "1 . 2 3 ) " ( f o r m a t" % 1 0 g "1 . 2 3 4 ) "

" > > > 1 . 2 3 < < < " " > > > 1 . 2 3 < < < " " > > >+ 1 . 2 3 < < < " " > > >1 . 2 3 < < < " " > > > 1 . 2 3< < < "

" 1 . 2 3 4 5 6 8 e + 0 8 " " 1 . 2 3 4 5 6 7 8 9 0 0 E + 0 8 " 1 . 2 3 " 1 . 2 3 4 "

( f o r m a t" R e s u l t=% 0 5 d "2 ) " R e s u l t=0 0 0 0 2 " ( f o r m a t" % 1 5 s "" h e l l o " ) ( f o r m a t" % 1 5 s% d "" h e l l o "1 2 3 ) ( f o r m a t" % 5 . 2 s "" h e l l o " ) ( f o r m a t" % 5 . 2 s "" h e l l o " ) ( f o r m a t" % o "8 0 ) " 1 2 0 " " h e l l o " " h e " " h e " " h e l l o1 2 3 "

( f o r m a t" % x% X "11 ) " f f f f f f f fF F F F F F F F " ;6 4b i tn u m b e r so nW i n d o w s ( f o r m a t" % I 6 4 X "1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 ) " 1 B 6 9 B 4 B A 6 3 0 F 3 4 E " ;6 4b i tn u m b e r so nU n i x( e x c e p tT R U 6 4 ) ( f o r m a t" % l l X "1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 ) " 1 B 6 9 B 4 B A 6 3 0 F 3 4 E " ( f o r m a t" % c "6 5 ) " A "

Thedatatobeformattedcanbepassedinsidealist:
( s e t' L' ( " h e l l o "1 2 3 ) ) ( f o r m a t" % 1 5 s% d "L ) " h e l l o1 2 3 "

Iftheformatstringrequiresit,newLISP'sf o r m a t willautomaticallyconvertintegersintofloatingpointsorfloatingpointsinto integers:


( f o r m a t" % f "1 2 3 ) 1 2 3 . 0 0 0 0 0 0

( f o r m a t" % d "1 2 3 . 4 5 6 ) 1 2 3

fv
syntax:(fvnumratenumnpernumpmtnumpv[inttype]) Calculatesthefuturevalueofaloanwithconstantpaymentnumpmtandconstantinterestratenumrateafternumnperperiodof timeandabeginningprincipalvalueofnumpv.Ifpaymentisattheendoftheperiod,inttypeis0 (zero)orinttypeisomittedfor paymentatthebeginningofeachperiod,inttypeis1.
( f v( d i v0 . 0 71 2 )2 4 07 7 5 . 3 01 0 0 0 0 0 ) 0 . 5 5 4 4 6 4 5 0 5 2

Theexampleillustrateshowaloanof$100,000ispaiddowntoaresidualof$0.55after240monthlypaymentsatayearlyinterest rateof7percent. Seealsothefunctionsirr,nper,npv,pmt,andpv.

gammai
syntax:(gammainumanumb) CalculatestheincompleteGammafunctionofvaluesaandbinnumaandnumb,respectively.
( g a m m a i45 ) 0 . 7 3 4 9 7 4 0 8 4 7

TheincompleteGammafunctionisusedtoderivetheprobabilityofChitoexceedagivenvalueforadegreeoffreedom,df,as follows: Q(Chi|df)=Q(df/2,Chi/2)=gammai(df/2,Chi/2) Seealsotheprobchi2function.

gammaln
syntax:(gammalnnumx) CalculatesthelogGammafunctionofthevaluexinnumx.
( e x p( g a m m a l n6 ) ) 1 2 0

Theexampleusestheequalityofn!=gamma(n+1)tocalculatethefactorialvalueof5. ThelogGammafunctionisalsorelatedtotheBetafunction,whichcanbederivedfromit: Beta(z,w)=Exp(Gammaln(z)+Gammaln(w)Gammaln(z+w))

gcd

syntax:(gcdint1[int2...]) Calculatesthegreatestcommondivisorofagroupofintegers.Thegreatestcommondivisoroftwointegersthatarenotbothzerois thelargestintegerthatdividesbothnumbers.g c d willcalculatethegreatestcommondivisorforthefirsttwointegersinintiand thenfurtherreducetheargumentlistbycalculatingthegreatestcommondivisoroftheresultandthenextargumentintheparameter list.


( g c d0 ) ( g c d00 ) ( g c d1 0 ) ( g c d1 23 6 ) ( g c d1 53 66 ) 0 0 1 0 1 2 3

SeeWikipediafordetailsandtheoryaboutgcdnumbersinmathematics.

getchar
syntax:(getcharintaddress) Getsan8bitcharacterfromanaddressspecifiedinintaddress.Thisfunctionisusefulwhenusingimportedsharedlibrary functionswithimport.
c h a r*f o o ( v o i d ) { c h a r*r e s u l t ; r e s u l t=" A B C D E F G " ; r e t u r n ( r e s u l t ) ; }

ConsidertheaboveCfunctionfromasharedlibrary,whichreturnsacharacterpointer(addresstoastring).
( i m p o r t" m y l i b . s o "" f o o " ) ( p r i n t( g e t c h a r( f o o )) ) 6 5;A S C I I" A " ( p r i n t( g e t c h a r( +( f o o )1 ) ) ) 6 6;A S C I I" B "

Notethatitisunsafetousetheg e t c h a r functionwithanincorrectaddressinintaddress.Doingsocouldresultinthesystem crashingorbecomingunstable. Seealsotheaddress,getint,getlong,getfloat,getstring,pack,andunpackfunctions.

getfloat
syntax:(getfloatintaddress) Getsa64bitdoublefloatfromanaddressspecifiedinintaddress.Thisfunctionishelpfulwhenusingimportedsharedlibrary functions(withi m p o r t )thatreturnanaddresspointertoadoublefloatorapointertoastructurecontainingdoublefloats.
d o u b l ef l o a t*f o o ( v o i d ) { d o u b l ef l o a t*r e s u l t ; * r e s u l t=1 2 3 . 4 5 6 ; r e t u r n ( r e s u l t ) ; }

ThepreviousCfunctioniscompiledintoasharedlibrary.

( i m p o r t" m y l i b . s o "" f o o " ) ( g e t f l o a t( f o o ) ) 1 2 3 . 4 5 6 f o o isimportedandreturnsapointertoadoublefloatwhencalled.Notethatg e t f l o a t isunsafewhenusedwithanincorrect

addressinintaddressandmayresultinthesystemcrashingorbecomingunstable. Seealsotheaddress,getint,getlong,getchar,getstring,pack,andunpackfunctions.

getint
syntax:(getintintaddress) Getsa32bitintegerfromtheaddressspecifiedinintaddress.Thisfunctionishandywhenusingimportedsharedlibraryfunctions withi m p o r t ,afunctionreturninganaddresspointertoaninteger,orapointertoastructurecontainingintegers.
i n t*f o o ( v o i d ) { i n t*r e s u l t ; * r e s u l t=1 2 3 ; r e t u r n ( r e s u l t ) ; } i n tf o o b ( v o i d ) { i n tr e s u l t ; r e s u l t=4 5 6 ; r e t u r n ( r e s u l t ) ; }

ConsidertheCfunctionf o o (fromasharedlibrary),whichreturnsanintegerpointer(addressofaninteger).
( i m p o r t" m y l i b . s o "" f o o " ) ( g e t i n t( f o o ) ) 1 2 3 ( f o o b ) 4 5 6

Notethatusingg e t i n t withanincorrectaddressinintaddressisunsafeandcouldresultinthesystemcrashingorbecoming unstable. Seealsotheaddress,getchar,getfloat,getlong,getstring,pack,andunpackfunctions.

getlong
syntax:(getlongintaddress) Getsa64bitintegerfromtheaddressspecifiedinintaddress.Thisfunctionishandywhenusingi m p o r t toimportsharedlibrary functions,afunctionreturninganaddresspointertoalonginteger,orapointertoastructurecontaininglongintegers.
l o n gl o n gi n t*f o o ( v o i d ) { i n t*r e s u l t ; * r e s u l t=1 2 3 ; r e t u r n ( r e s u l t ) ; } l o n gl o n gi n tf o o b ( v o i d )

{ i n tr e s u l t ; r e s u l t=4 5 6 ; r e t u r n ( r e s u l t ) ; }

ConsidertheCfunctionf o o (fromasharedlibrary),whichreturnsanintegerpointer(addressofaninteger).
( i m p o r t" m y l i b . s o "" f o o " ) ( g e t i n t( f o o ) ) 1 2 3 ( f o o b ) 4 5 6

Notethatusingg e t l o n g withanincorrectaddressinintaddressisunsafeandcouldresultinthesystemcrashingorbecoming unstable. Seealsotheaddress,getchar,getfloat,getint,getstring,pack,andunpackfunctions.

getstring
syntax:(getstringintaddress) Getsacharacterstringfromtheaddressspecifiedinintaddress.Thisfunctionishelpfulwhenusingimportedsharedlibrary functionswithimport.
c h a r*f o o ( v o i d ) { c h a r*r e s u l t ; r e s u l t=" A B C D E F G " ; r e t u r n ( r e s u l t ) ; }

ConsidertheaboveCfunctionfromasharedlibrary,whichreturnsacharacterpointer(addresstoastring).
( i m p o r t" m y l i b . s o "" f o o " ) ( p r i n t( g e t s t r i n g( f o o ) ) ) " A B C D E F G "

Whenastringispassedasanargument,g e t s t r i n g willtakeitsaddressastheargument.Becauseg e t s t r i n g alwaysbreaksoff atthefirstfirst\ 0 0 0 (nullcharacter)itencounters,itcanbeusedtoretrieveastringfromabuffer:


( s e t' b u f f" A B C \ 0 0 0 \ 0 0 0 \ 0 0 0 D E F " ) " A B C \ 0 0 0 \ 0 0 0 \ 0 0 0 D E F " ( l e n g t hb u f f ) 9 ( g e t s t r i n gb u f f ) " A B C " ( l e n g t h( g e t s t r i n gb u f f ) ) 3 ;g e tas t r i n gf r o mo f f s e ti n t oab u f f e r ( g e t s t r i n g( +( a d d r e s sb u f f )6 ) )" D E F " ;u s eu n p a c kt og e tt h ew h o l eb u f f e r ( u n p a c k" s 9 "b u f f ) ( " A B C \ 0 0 0 \ 0 0 0 \ 0 0 0 D E F " )

Seealsothegetchar,getint,getfloat,pack,andunpackfunctions. Notethatg e t s t r i n g cancrashthesystemormakeitunstableifthewrongaddressisspecified.

geturl

syntax:(geturlstrurl[stroption][inttimeout[strheader]]) ReadsawebpageorfilespecifiedbytheURLinstrurlusingtheHTTPGETprotocol.Bothh t t p : / / andf i l e : / / URLsare handled." h e a d e r " canbespecifiedintheoptionalargumentstroptiontoretrieveonlytheheader.Theoption" l i s t " causes headerandpageinformationtobereturnedasseparatestringsinalist. A" d e b u g " optioncanbespecifiedeitheraloneorafterthe" h e a d e r " or" l i s t " optionseparatedbyonecharacter,i.e." h e a d e r d e b u g " or" l i s td e b u g " .Including"debug"outputsalloutgoinginformationtotheconsolewindow. Theoptionalargumentinttimeoutcanspecifyavalueinmilliseconds.Ifnodataisavailablefromthehostafterthespecified timeout,g e t u r l returnsthestringE R R :t i m e o u t .Whenothererrorconditionsoccur,g e t u r l returnsastringstartingwithE R R : andthedescriptionoftheerror.
g e t u r l handlesredirectionifitdetectsaL o c a t i o n : specinthereceivedheaderandautomaticallydoesasecondrequest.g e t u r l

alsounderstandstheT r a n s f e r E n c o d i n g :c h u n k e d formatandwillunpackdataintoanunchunkedformat.
g e t u r l requestsarealsounderstoodbynewLISPservernodes. ( g e t u r l" h t t p : / / w w w . n u e v a t e c . c o m " ) ( g e t u r l" h t t p : / / w w w . n u e v a t e c . c o m "3 0 0 0 ) ( g e t u r l" h t t p : / / w w w . n u e v a t e c . c o m "" h e a d e r " ) ( g e t u r l" h t t p : / / w w w . n u e v a t e c . c o m "" h e a d e r "5 0 0 0 ) ( g e t u r l" h t t p : / / w w w . n u e v a t e c . c o m "" l i s t " ) ( g e t u r l" f i l e : / / / h o m e / d b / d a t a . t x t " );a c c e s sl o c a lf i l es y s t e m ( e n v" H T T P _ P R O X Y "" h t t p : / / o u r p r o x y : 8 0 8 0 " ) ( g e t u r l" h t t p : / / w w w . n u e v a t e c . c o m / n e w l i s p / " )

Theindexpagefromthesitespecifiedinstrurlisreturnedasastring.Inthethirdline,onlytheHTTPheaderisreturnedinastring. Lines2and4showatimeoutvaluebeingused. Thesecondexampleshowsusageofaf i l e : / / URLtoaccess/ h o m e / d b / d a t a . t x t onthelocalfilesystem. Thethirdexampleillustratestheuseofaproxyserver.Theproxyserver'sURLmustbeintheoperatingsystem'senvironment.As shownintheexample,thiscanbeaddedusingtheenvfunction. Theinttimeoutcanbefollowedbyanoptionalcustomheaderinstrheader:

Customheader
Thecustomheadermaycontainoptionsforbrowsercookiesorotherdirectivestotheserver.Whennostrheaderisspecified, newLISPsendscertainheaderinformationbydefault.Afterthefollowingrequest:
( g e t u r l" h t t p : / / s o m e h o s t . c o m "5 0 0 0 )

newLISPwillconfigureandsendtherequestandheaderbelow:
G E T/H T T P / 1 . 1 H o s t :s o m e h o s t . c o m U s e r A g e n t :n e w L I S Pv 8 8 0 0 C o n n e c t i o n :c l o s e

Asanalternative,thestrheaderoptioncouldbeused:
( g e t u r l" h t t p : / / s o m e h o s t . c o m "5 0 0 0 " U s e r A g e n t :M o z i l l a / 4 . 0 \ r \ n C o o k i e :n a m e = f r e d \ r \ n " )

newLISPwillnowsendthefollowingrequestandheader:
G E T/H T T P / 1 . 1 H o s t :s o m e h o s t . c o m U s e r A g e n t :M o z i l l a / 4 . o C o o k i e :n a m e = f r e d

C o n n e c t i o n :c l o s e

Notethatwhenusingacustomheader,newLISPwillonlysupplytheG E T requestline,aswellastheH o s t : andC o n n e c t i o n : headerentries.newLISPinsertsallotherentriessuppliedinthecustomheaderbetweentheH o s t : andC o n n e c t i o n : entries.Each entrymustendwithacarriagereturnlinefeedpair:\ r \ n . SeeanHTTPtransactionsreferenceforvalidheaderentries. Customheaderscanalsobeusedintheputurlandposturlfunctions.

global
syntax:(globalsym1[sym2...]) Oneormoresymbolsinsym1[sym2...]canbemadegloballyaccessiblefromcontextsotherthanMAIN.Thestatementhastobe executedintheMAINcontext,andonlysymbolsbelongingtoMAINcanbemadeglobal.g l o b a l returnsthelastsymbolmade global.
( g l o b a l' a V a r' x' y' z ) z ( d e f i n e( f o ox ) ( ) ) ( c o n s t a n t( g l o b a l' f o o ) )

Thesecondexampleshowshowconstantandg l o b a l canbecombinedintoonestatement,protectingandmakingaprevious functiondefinitionglobal.

global?
syntax:(global?sym) Checksifsymbolinsymisglobal.Builtinfunctions,contextsymbols,andallsymbolsmadeglobalusingthefunctionglobalare global:
g l o b a l ?' p r i n t ) ( g l o b a l' v a r ) ( g l o b a l ?' v a r ) t r u e v a r t r u e

( c o n s t a n t( g l o b a l' f o o ) ) ( g l o b a l ?' f o o ) t r u e

if
syntax:(ifexpconditionexp1[exp2]) syntax:(ifexpcond1exp1expcond2exp2[...]) Ifthevalueofexpconditionisneithern i l noranemptylist,theresultofevaluatingexp1isreturnedotherwise,thevalueofexp2 isreturned.Ifexp2isabsent,thevalueofexpconditionisreturned.

( s e t' x5 0 ) ( i f( <x1 0 0 )" s m a l l "" b i g " ) ( s e t' x1 0 0 0 ) ( i f( <x1 0 0 )" s m a l l "" b i g " ) ( i f( >x2 0 0 0 )" b i g " )

5 0 " s m a l l " 1 0 0 0 " b i g " n i l

;m o r et h a no n es t a t e m e n ti nt h et r u eo rf a l s e ;p a r tm u s tb eb l o c k e dw i t h( b e g i n. . . ) ( i f( =xy ) ( b e g i n ( s o m e f u n cx ) ( s o m e f u n cy ) ) ( b e g i n ( d o t h i sxy ) ( d o t h a txy ) ) )

Thesecondformofi f workssimilarlytocond,exceptitdoesnottakeparenthesesaroundtheconditionbodypairofexpressions. Inthisform,i f canhaveanunlimitednumberofarguments.


( d e f i n e( c l a s s i f yx ) ( i f ( <x0 )" n e g a t i v e " ( <x1 0 )" s m a l l " ( <x2 0 )" m e d i u m " ( > =x3 0 )" b i g " " n / a " ) ) ( c l a s s i f y1 5 ) ( c l a s s i f y1 0 0 ) ( c l a s s i f y2 2 ) ( c l a s s i f y1 0 ) " m e d i u m " " b i g " " n / a " " n e g a t i v e "

Thelastexpression," n / a " ,isoptional.Whenthisoptionisomitted,theevaluationof( > =x3 0 ) isreturned,behavingexactlylike atraditionalcondbutwithoutrequiringparenthesesaroundtheconditionexpressionpairs. Inanycase,thewholei f expressionalwaysreturnsthelastexpressionorconditionevaluated. Seealsothewhenandunlessfunctions.

ifft
syntax:(ifftlistnum) CalculatestheinversediscreteFouriertransformonalistofcomplexnumbersinlistnumusingtheFFTmethod(FastFourier Transform).Eachcomplexnumberisspecifiedbyitsrealpart,followedbyitsimaginarypart.Incaseonlyrealnumbersareused, theimaginarypartissetto0 . 0 (zero).Whenthenumberofelementsinlistnumisnotanintegerpowerof2,i f f t increasesthe numberofelementsbypaddingthelistwithzeroes.Whencomplexnumbersare0 intheimaginarypart,simplenumberscanbe used.
( i f f t( f f t' ( ( 10 )( 20 )( 30 )( 40 ) ) ) ) ( ( 10 )( 20 )( 30 )( 40 ) ) ; ;w h e ni m a g i n a r yp a r ti s0 ,p l a i nn u m b e r sw o r kt o o ( i f f t( f f t' ( 1234 ) ) ) ( ( 10 )( 20 )( 30 )( 40 ) )

Theinverseoperationofi f f t isthefftfunction.

import
syntax:(importstrlibnamestrfunctionname["cdecl"]) syntax:(importstrlibnamestrfunctionnamestrreturntype[strparamtype...]) syntax:(importstrlibname) Importsthefunctionspecifiedinstrfunctionnamefromasharedlibrarynamedinstrlibname.Dependingonthesyntaxused, stringlabelsforreturnandparametertypescanbespecified Ifthelibraryinstrlibnameisnotinthesystem'slibrarypath,thefullpathnameshouldbespecified. Afunctioncanbeimportedonlyonce.Arepeatedimportofthesamefunctionwillsimplyreturnthesamealreadyallocated functionaddress. Onlibffienabledversionscapableofthesecondextendedsyntaximportedsymbolsareprotectedagainstchangeandcanonlybe modifiedusingconstant. ThethirdsyntaxonOSX,LinuxandotherUnixonlyallowspreloadinglibrarieswithoutimportingfunctions.Thisisnecessary whenotherlibraryimportsneedaccessinternallytootherfunctionsfrompreloadedlibraries. Incorrectlyusingi m p o r t cancauseasystembuserrororasegfaultcanoccurandcrashnewLISPorleaveitinanunstablestate.

Thesimplei m p o r t syntax
Mostlibraryfunctionscanbeimportedusingthesimplerfirstsyntax.ThisformispresentonallcompileflavorsofnewLISP.The APIexpectsallfunctionargumentstobepassedonthestackineithercdeclorstdcallconventions.On32bitplatforms,integers, pointerstostringsandbufferssometimesfloatingpointvaluescanbepassedasparameters.On64bitplatformsonlyintegerscanbe passedbutnofloatingpointvalues.Asreturnvaluesonly32bitor64bitvaluesandpointersareallowed.Nofloatingpoint numberscanbereturned.Stringsmustberetrievedwiththegetstringhelperfunction.Regardlessoftheselimitations,mostmodules includedinthedistributionusethissimpleimportAPI. Ifpointersarereturnedtostringsorstructuresthefollowinghelperfunctionscanbeusedextractdata:getchar,getint,getfloat,get string,unpack Topasspointersfordatastructuresthefollowingfunctionshelptopackdataandcalculateaddresses:address,pack. TotransformnewLISPdatatypesintothedatatypesneededbytheimportedfunction,usethefunctionsfloatfor64bitdouble floats,fltfor32bitfloats,andintfor32bitintegers.Bydefault,newLISPpassesfloatingpointnumbersas64bitdoublefloats, integersas32bitintegers,andstringsas32bitintegersforstringaddresses(pointersinC).Floatscanonlybeusedwith32bit versionsofnewLISPandlibraries.Tousefloatingpointnumbersina64bitenvironmentusetheextendedi m p o r t syntax.
; ;d e f i n eL I B Cp l a t f o r mi n d e p e n d e n t ( d e f i n eL I B C( l o o k u po s t y p e' ( ( " W i n 3 2 "" m s v c r t . d l l " ) ( " O S X "" l i b c . d y l i b " ) ( p r i n t f" % g% s% d% c \ n "1 . 2 3" h e l l o "9 9 96 5 ) 1 . 2 3h e l l o9 9 9A 1 7;r e t u r nv a l u e ; ;i m p o r tW i n 3 2D L L si nW i n 3 2v e r s i o n s ( i m p o r t" k e r n e l 3 2 . d l l "" G e t T i c k C o u n t " ) G e t T i c k C o u n t ( i m p o r t" u s e r 3 2 . d l l "" M e s s a g e B o x A " ) M e s s a g e B o x A ( G e t T i c k C o u n t ) 3 3 2 8 8 9 6

Inthefirstexample,thestring"1.23hello999A"isprintedasasideeffect,andthevalue17(numberofcharactersprinted)is returned.AnyCfunctioncanbeimportedfromanysharedlibraryinthisway. ThemessageboxexamplepopsupaWindowsdialogbox,whichmaybehiddenbehindtheconsolewindow.Theconsoleprompt

doesnotreturnuntilthe'OK'buttonispressedinthemessagebox.
; ; t h i sp o p su pam e s s a g eb o x ( M e s s a g e B o x A0" T h i si st h eb o d y "" C a p t i o n "1 )

TheotherexamplesshowseveralimportsofWin32DLLfunctionsandthedetailsofpassingvaluesbyvalueorbyreference. Wheneverstringsornumbersarepassedbyreference,spacemustbereservedbeforehand.
( i m p o r t" k e r n e l 3 2 . d l l "" G e t W i n d o w s D i r e c t o r y A " ) ; ;a l l o c a t i n gs p a c ef o ras t r i n gr e t u r nv a l u e ( s e t' s t r( d u p" \ 0 0 0 "6 4 ) ) ;r e s e r v es p a c ea n di n i t i a l i z e ( G e t W i n d o w s D i r e c t o r y As t r( l e n g t hs t r ) ) s t r " C : \ \ W I N D O W S \ 0 0 0 \ 0 0 0 \ 0 0 0. . ." ; ;u s et r i mo rg e t s t r i n gt oc u to fb i n a r yz e r o s ( g e t s t r i n gs t r ) " C : \ \ W I N D O W S " ( t r i ms t r ) " C : \ \ W I N D O W S " ( i m p o r t" k e r n e l 3 2 . d l l "" G e t C o m p u t e r N a m e A " ) ; ;a l l o c a t em e m o r ya n di n i t i a l i z et oz e r o s ( s e t' s t r( d u p" \ 0 0 0 "6 4 ) ) ( s e t' l e n( l e n g t hs t r ) ; ;c a l lt h ef u n c t i o n ; ;t h el e n g t ho ft h es t r i n gi sp a s s e da sa d d r e s sr e f e r e n c e ; ;s t r i n gs t ri sa u t o m a t i c a l l yp a s tb ya d d r e s s( Cp o i n t e r ) ( G e t C o m p u t e r N a m e As t r( a d d r e s sl e n ) ) s t r " L U T Z P C \ 0 0 0 \ 0 0 0. . ." ( t r i ms t r ) " L U T Z P C " i m p o r t returnstheaddressofthefunction,whichcanbeusedtoassignadifferentnametotheimportedfunction. ( s e t' i m p r i m e( i m p o r t" l i b c . s o . 6 "" p r i n t f " ) ) p r i n t f @ 4 0 0 8 6 2 A 0 ( i m p r i m e" % s% d "" h o l a "1 2 3 ) " h o l a1 2 3 "

TheWin32andCygwinversionsofnewLISPusesstandardcallstdcallconventionstocallDLLlibraryroutinesbydefault.Thisis necessaryforcallingDLLsthatbelongtotheWin32operatingsystem.MostthirdpartyDLLsarecompiledforCdeclarationcdecl callingconventionsandmayneedtospecifythestring" c d e c l " asanadditionallastargumentwhenimportingfunctions.newLISP compiledforMacOSX,LinuxandotherUnixsystemsusesthecdeclcallingconventionsbydefaultandignoresanyadditional string.


; ;f o r c ec d e c lc a l l i n gc o n v e n t i o n so nW i n 3 2 ( i m p o r t" s q l i t e . d l l "" s q l i t e _ o p e n "" c d e c l " ) s q l i t e _ o p e n< 6 7 3 D 4 8 8 8 >

Importedfunctionsmaytakeuptofourteenarguments.Notethatfloatingpointargumentstakeuptwospaceseach(e.g.,passing fivefloatstakesuptenofthefourteenparameters).

Theextendedi m p o r t syntax
TheextendedimportAPIworkswiththesecondsyntax.Itisbasedonthepopularl i b f f i librarywhichispreinstalledonmostOS platforms.ThestartupbannerofnewLISPshouldshowthewordl i b f f i indicatingtherunningversionofnewLISPiscompiledto usetheextendedi m p o r t API.Thefunctionsysinfocanalsobeusedtocheckforl i b f f i support. TheAPIworkswithallatomicCdatatypesforpassedparametersandreturnvalues.TheextendedAPIrequiresthatparameter typesarespecifiedinthei m p o r t statementasstringtypelabels.ProgramswrittenwithextendedimportAPIwillrunwithout changeon32bitand64bitnewLISPandlibraries.Integers,floatingpointvaluesandstringscanbereturnedwithoutusinghelper functions.

Thefollowingtypescanbespecifiedforthereturnvalueinstrreturntypeandforfunctionparametersinstrparamtype: label Ctypeforreturnvalueandarguments "void" void(onlyasreturntype) "byte" byteunsigned8bit "char" charsigned8bit "unsignedshortint" unsignedshortint16bit "shortint" shortintsigned16bit "unsignedint" unsignedint32bit "int" intsigned32bit "long" "longlong" "float" "double" "char*" "void*" newLISPreturnandargumenttype n i l isreturned integer integer integer integer integer integer

longsigned32or64bitdependingonplatform integer longlongsigned64bit integer float32bit IEEE75464bitfloatcutto32bitprecision double64bit IEEE75464bitfloat displayablestringreturn(zeroterminated) char*32or64bitptrdependingonplatform stringbufferarg(noaddr.since10.4.2) integeraddressreturn void*32or64bitptrdependingonplatform eitherstringbufferorintegeraddressarg

Thetypes" c h a r * " and" v o i d * canbeinterchangedandaretreatedidenticalinsidel i b f f i .Dependingonthetypeofarguments passedandthetypeofreturnvalues,oneortheotherisused. Aggregatetypescanbecomposedusingthestructfunction. Thefollowingexamplesshowhowtheextendedi m p o r t syntaxcanhandlereturnvaluesoffloatingpointvaluesandstrings:


; ;r e t u r naf l o a tv a l u e ,L I B Cw a sd e f i n e de a r l i e r ; n a m e r e t u r n a r g ( i m p o r tL I B C" a t o f "" d o u b l e "" c h a r * " ) ( a t o f" 3 . 1 4 1 " )3 . 1 4 1 ; ;r e t u r nac o p i e ds t r i n g ; n a m e r e t u r n a r g 1 a r g 2 ( i m p o r tL I B C" s t r c p y "" c h a r * "" c h a r * "" c h a r * " ) ( s e t' f r o m" H e l l oW o r l d " ) ( s e t' t o( d u p" \ 0 0 0 "( l e n g t hf r o m ) ) );r e s e r v em e m o r y ( s t r c p yt of r o m )" H e l l oW o r l d "

Thec h a r * typetakesastringbufferonly.The" v o i d * typecantakeeitherastringbufferoramemoryaddressnumberasinput. Whenusing" v o i d * " asareturntypetheaddressnumberoftheresultbufferwillbereturned.Thisisusefulwhenreturningpointers todatastructures.Thesepointerscanthenbeusedwithunpackandstructfordestructuring.Inthefollowingexamplethereturntype ischangedtov o i d * :


( i m p o r tL I B C" s t r c p y "" v o i d * "" c h a r * "" c h a r * " ) ( s e t' f r o m" H e l l oW o r l d " ) ( s e t' t o( d u p" \ 0 0 0 "( l e n g t hf r o m ) ) ) ( s t r c p yt of r o m ) 2 4 4 9 4 2 4 ( a d d r e s st o ) 2 4 4 9 4 2 4 ( u n p a c k" s 1 1 "2 4 4 9 4 2 4 )" H e l l oW o r l d " ( g e t s t r i n g2 4 4 9 4 2 4 ) " H e l l oW o r l d " t o " H e l l oW o r l d "

AnewLISPstringisalwayspassedbyit'saddressreference. ForamorecomplexexampleseethisOpenGLdemo.

Memorymanagement

Anyallocationperformedbyimportedforeignfunctionshastobedeallocatedmanuallyifthere'snocallintheimportedAPItodo so.SeetheCodePatternsinnewLISPdocumentforanexample. Incaseofcallingforeignfunctionswithpassingbyreference,memoryforvariablesneedstobeallocatedbeforehandbynewLISP seeimportofG e t W i n d o w s D i r e c t o r y A aboveandhence,memoryneedsnotbedeallocatedmanually,becauseitismanaged automaticallybynewLISP.

inc!
syntax:(incplace[num]) Incrementsthenumberinplaceby1 . 0 orbytheoptionalnumbernumandreturnstheresult.i n c performsfloatarithmeticand convertsintegernumberspassedintofloatingpointtype. placeiseitherasymboloraplaceinaliststructureholdinganumber,oranumberreturnedbyanexpression.
( s e t' x0 ) ( i n cx ) x ( i n cx0 . 2 5 ) x ( i n cx ) 0 1 1 1 . 2 5 1 . 2 5 2 . 2 5

Ifasymbolforplacecontainsn i l ,itistreatedasifcontaining0 . 0 :
z ( i n cz ) n i l 1

( s e t' zn i l ) ( i n cz0 . 0 1 ) 0 . 0 1

Placesinaliststructureoranumberreturnedbyanotherexpressioncanbeupdatedtoo:
( s e t' l' ( 1234 ) ) ( i n c( l3 )0 . 1 )4 . 1 ( i n c( f i r s tl ) )2 l( 2234 . 1 ) ( i n c( +34 ) )8

Usethe++functionforincrementingnumbersinintegermode.Usedectodecrementnumbersinfloatingpointmode.

index
syntax:(indexexppredicateexplist) Appliesthepredicateexppredicatetoeachelementofthelistexplistandreturnsalistcontainingtheindicesoftheelementsfor whichexppredicateistrue.
( i n d e xs y m b o l ?' ( 12d4fg5h ) ) ( 2457 ) ( d e f i n e( b i g ?x )( >x5 ) ) ( l a m b d a( x )( >x5 ) ) ( i n d e xb i g ?' ( 11 036451 1 ) ) ( 136 )

( s e l e c t' ( 11 036451 1 )' ( 136 ) )( 136 )

Thepredicatemaybeabuiltinpredicate,auserdefinedfunction,oralambdaexpression. Usethefilterfunctiontoreturntheelementsthemselves.

inf?
syntax:(inf?float) Ifthevalueinfloatisinfinitethefunctionreturnst r u e elsen i l .
( i n f ?( d i v10 ) )t r u e ( d i v00 )N a N

Notethatanintegerdivisionbyzeroe.g.( /10 ) willthrowan"divisionbyzero"errorandnotyieldinfinity.SeealsoNaN?to checkifafloatingpointnumberisvalid.

int
syntax:(intexp[expdefault[intbase]]) Iftheexpressioninexpevaluatestoanumberorastring,theresultisconvertedtoanintegerandreturned.Ifexpcannotbe convertedtoaninteger,thenn i l ortheevaluationofexpdefaultwillbereturned.Thisfunctionismostlyusedwhentranslating stringsfromuserinputorfromparsingtext.Ifexpevaluatestoastring,thestringmuststartwithadigitoneormorespacesorthe+ orsign.Thestringmustbeginwith'0 x 'forhexadecimalstringsor'0 '(zero)foroctalstrings.Ifexpisinvalid,i n t returnsn i l asa defaultvalueifnototherwisespecified. Asecondoptionalparametercanbeusedtoforcethenumberbaseofconversiontoaspecificvalue. Integerslargerthan9,223,372,036,854,775,807aretruncatedto9,223,372,036,854,775,807.Integerssmallerthan 9,223,372,036,854,775,808aretruncatedto9,223,372,036,854,775,808. Whenconvertingfromafloat(asinthesecondformofi n t ),floatingpointvalueslargerorsmallerthantheintegermaximumor minimumarealsotruncated.AfloatingpointexpressionevaluatingtoN a N isconvertedto0 (zero).
( i n t" 1 2 3 " ) ( i n t"1 2 3 " ) ( i n t" a 1 2 3 "0 ) ( i n t( t r i m"1 2 3 " ) ) ( i n t" 0 x F F " ) ( i n t" 0 5 5 " ) ( i n t" 1 . 5 6 7 " ) ( i n t1 . 5 6 7 ) 1 2 3 1 2 3 0 1 2 3 2 5 5 4 5 1 1

( i n t e g e r ?1 . 0 0 ) n i l ( i n t e g e r ?( i n t1 . 0 0 ) ) t r u e ( i n t" 1 1 1 1 "02 ) 1 5 ;b a s e2c o n v e r s i o n ( i n t" 0 F F "01 6 ) 2 5 5 ;b a s e1 6c o n v e r s i o n ( i n t' x y z ) n i l ( i n t' x y z0 ) 0 ( i n tn i l1 2 3 ) 1 2 3

( i n t" a b c "( t h r o w e r r o r" n o tan u m b e r " ) ) E R R :u s e re r r o r:n o tan u m b e r ( p r i n t" E n t e ran u m : " ) ( s e t' n u m( i n t( r e a d l i n e ) ) ) ( i n t( b i t s1 2 3 4 5 )02 )1 2 3 4 5

Theinversefunctiontoi n t withbase2 isbits. Usethefloatfunctiontoconvertargumentstofloatingpointnumbers.

integer?
syntax:(integer?exp) Returnst r u e onlyifthevalueofexpisanintegerotherwise,itreturnsn i l .
( s e t' n u m1 2 3 ) 1 2 3 ( i n t e g e r ?n u m ) t r u e

intersect
syntax:(intersectlistAlistB) syntax:(intersectlistAlistBbool) Inthefirstsyntax,i n t e r s e c t returnsalistcontainingonecopyofeachelementfoundbothinlistAandlistB.
( i n t e r s e c t' ( 301323421 )' ( 1425 ) ) ( 241 )

Inthesecondsyntax,i n t e r s e c t returnsalistofallelementsinlistAthatarealsoinlistB,withouteliminatingduplicatesinlistA. boolisanexpressionevaluatingtot r u e oranyothervaluenotn i l .


( i n t e r s e c t' ( 301323421 )' ( 1425 )t r u e ) ( 12421 )

Seealsothesetfunctionsdifference,uniqueandunion.

invert
syntax:(invertmatrix[floatpivot]) Returnstheinversionofatwodimensionalmatrixinmatrix.Thematrixmustbesquare,withthesamenumberofrowsand columns,andnonsingular(invertible).Matrixinversioncanbeusedtosolvesystemsoflinearequations(e.g.,multipleregression instatistics).newLISPusesLUdecompositionofthematrixtofindtheinverse. Optionally0 . 0 oraverysmallvaluecanbespecifiedinfloatpivot.ThisvaluesubstitutespivotelementsintheLUdecomposition algorithm,whichresultinzerowhenthealgorithmdealswithasingularmatrix. Thedimensionsofamatrixaredefinedbythenumberofrowstimesthenumberofelementsinthefirstrow.Formissingelements

innonrectangularmatrices,0 . 0 (zero)isassumed.Amatrixcaneitherbeanestedlistoranarray.
( s e t' A' ( ( 111 )( 145 )( 120 ) ) ) ( i n v e r tA ) ( ( 1 029 )( 514 )( 615 ) ) ( i n v e r t( i n v e r tA ) )( ( 111 )( 145 )( 120 ) ) ;s o l v eA x=bf o rx ( m u l t i p l y( i n v e r tA )' ( ( 1 )( 2 )( 3 ) ) )( ( 4 1 )( 1 9 )( 2 3 ) ) ;t r e a t m e n to fs i n g u l a rm a t r i c e s ( i n v e r t' ( ( 21 )( 42 ) ) ) n i l ( i n v e r t' ( ( 21 )( 42 ) )0 . 0 ) ( ( i n fi n f )( i n fi n f ) ) ( i n v e r t' ( ( 21 )( 42 ) )1 e 2 0 ) ( ( 5 e + 1 92 . 5 e + 1 9 )( 1 e + 2 05 e + 1 9 ) ) i n v e r t willreturnn i l ifthematrixissingularandcannotbeinverted,andfloatpivotisnotspecified.

Alloperationsshownhereonlistscanbeperformedonarrays,aswell. Seealsothematrixfunctionsdet,mat,multiplyandtranspose.

irr
syntax:(irrlistamounts[listtimes[numguess]]) Calculatestheinternalrateofreturnofacashflowpertimeperiod.Theinternalrateofreturnistheinterestratethatmakesthe presentvalueofacashflowequalto0 . 0 (zero).Inflowing(negativevalues)andoutflowing(positivevalues)amountsare specifiedinlistamounts.Ifnotimeperiodsarespecifiedinlisttimes,amountsinlistamountscorrespondtoconsecutivetime periodsincreasingby1(1,2,3).Thealgorithmusedisiterative,withaninitialguessof0.5(50percent).Optionally,adifferent initialguesscanbespecified.Thealgorithmreturnswhenaprecisionof0.000001(0.0001percent)isreached.n i l isreturnedifthe algorithmcannotconvergeafter50iterations. irrisoftenusedtodecidebetweendifferenttypesofinvestments.
( i r r' ( 1 0 0 05 0 04 0 03 0 02 0 01 0 0 ) ) 0 . 2 0 2 7 ( n p v0 . 2 0 2 7' ( 5 0 04 0 03 0 02 0 01 0 0 ) ) 1 0 0 0 . 0 3 3 8 4 8;~1 0 0 0 ( i r r' ( 1 0 0 05 0 04 0 03 0 02 0 01 0 0 )' ( 034567 ) ) 0 . 0 9 9 8 ( i r r' ( 5 0 0 02 0 0 05 0 0 06 0 0 0 )' ( 031 21 8 ) ) 0 . 0 3 2 1

Ifaninitialinvestmentof1,000yields500afterthefirstyear,400aftertwoyears,andsoon,finallyreaching0 . 0 (zero)afterfive years,thenthatcorrespondstoayearlyreturnofabout20.2percent.Thenextlinedemonstratestherelationbetweeni r r andnpv. Only9.9percentreturnsarenecessarywhenmakingthefirstwithdrawalafterthreeyears. Inthelastexample,securitieswereinitiallypurchasedfor5,000,thenforanother2,000threemonthslater.Afterayear,securities for5,000aresold.Sellingtheremainingsecuritiesafter18monthsrenders6,000.Theinternalrateofreturnis3.2percentper month,orabout57percentin18months. Seealsothefv,nper,npv,pmt,andpvfunctions.

jsonerror

syntax:(jsonerror) Whenjsonparsereturnsn i l duetoafailedJSONdatatranslation,thisfunctionretrievesanerrordescriptionandthelastscan positionoftheparser.


;f a i l e dp a r s er e t u r n sn i l ( j s o n p a r s e[ t e x t ] { " a d d r e s s "" h t t p : / / e x a m p l e . c o m " } [ / t e x t ] )n i l ;i n s p e c tt h ee r r o ri n f o r m a t i o n ( j s o n e r r o r )( " m i s s i n g:c o l o n "1 1 )

jsonparse
syntax:(jsonparsestrjsondata) ThisfunctionparsesJSONformattedtextandtranslatedittonewLISPSexpressions.AlldatatypesconformingtotheECMA262 standardaretranslated.TheresultinglistsfromJSONobjectdatacanbeprocessedusingassoc,lookupandref. ThefollowingexampleshowsanestedJSONobjectfromafilep e r s o n . j s o n :
{ " n a m e " :" J o h nS m i t h " , " a g e " :3 2 , " e m p l o y e d " :t r u e , " a d d r e s s " :{ " s t r e e t " :" 7 0 1F i r s tA v e . " , " c i t y " :" S u n n y v a l e ,C A9 5 1 2 5 " , " c o u n t r y " :" U n i t e dS t a t e s " } , " c h i l d r e n " :[ { " n a m e " :" R i c h a r d " , " a g e " :7 } , { " n a m e " :" S u s a n " , " a g e " :4 } , { " n a m e " :" J a m e s " , " a g e " :3 } ]

Thefileisread,parsedandtheresultingSexpressionstoredinj s p :
( s e t' j s p( j s o n p a r s e( r e a d f i l e" p e r s o n . j s o n " ) ) ) (( " n a m e "" J o h nS m i t h " ) ( " a g e "3 2 ) ( " e m p l o y e d "t r u e ) ( " a d d r e s s "(( " s t r e e t "" 7 0 1F i r s tA v e . " ) ( " c i t y "" S u n n y v a l e ,C A9 5 1 2 5 " ) ( " c o u n t r y "" U n i t e dS t a t e s " ) )) ( " c h i l d r e n "( ( ( " n a m e "" R i c h a r d " )( " a g e "7 ) ) ( ( " n a m e "" S u s a n " )( " a g e "4 ) ) ( ( " n a m e "" J a m e s " )( " a g e "3 ) ) )) )

Datacanbeextractedusingassoc,lookuporref:

;t h ea d d r e s s ( l o o k u p" a d d r e s s "j s p ) ( ( " s t r e e t "" 7 0 1F i r s tA v e . " )( " c i t y "" S u n n y v a l e ,C A9 5 1 2 5 " )( " c o u n t r y "" U n i t e dS t a t e s " ) ) ;t h ec i t yo ft h ea d d r e s s ( l o o k u p" c i t y "( l o o k u p" a d d r e s s "j s p ) ) " S u n n y v a l e ,C A9 5 1 2 5 " ;ac h i l dn a m e dS u s a n ( r e f' ( (*" S u s a n " )* )j s pm a t c ht r u e ) ( ( " n a m e "" S u s a n " )( " a g e "4 ) ) ;a l ln a m e s ( m a pl a s t( r e f a l l' ( " n a m e "* )j s pm a t c ht r u e ) ) ( " J o h nS m i t h "" R i c h a r d "" S u s a n "" J a m e s " ) ;o n l yn a m e so fc h i l d r e n ( m a pl a s t( r e f a l l' ( " n a m e "* )( l o o k u p" c h i l d r e n "j s p )m a t c ht r u e ) ) ( " R i c h a r d "" S u s a n "" J a m e s " ) ;n a m e so fc h i l d r e no t h e rm e t h o d ( m a pl a s t( m a pf i r s t( l o o k u p" c h i l d r e n "j s p ) ) ) ( " R i c h a r d "" S u s a n "" J a m e s " )

AlthoughmostofthetimeJSONobjecttypesareparsed,allJSONdatatypescanbeparseddirectly,withoutoccurringaspartofa JSONobject.ThefollowingexamplesshowparsingofaJSONarray:
;p a r s eaJ S O Na r r a yd a t at y p e ( j s o n p a r s e" [ 1 ,2 ,3 ,4 ,5 ] " )( 12345 )

WhentheUTF8capableversionofnewLISPisused,JSONformattedUnicodegetstranslatedintoUTF8:
;p a r s eaJ S O No b j e c td a t at y p ea n d sU n i c o d e ;t h eo u t e r{ , }a r en e w L I S Ps t r i n gd e l i m i t e r s[ t e x t ] , [ / t e x t ]t a g sc o u l da l s ob eu s e d ;t h ei n n e r{ , }a r eJ S O No b j e c td e l i m i t e r s ( j s o n p a r s e{{ " g r e e kl e t t e r s ":" \ u 0 3 b 1 \ u 0 3 b 2 \ u 0 3 b 3 \ u 0 3 b 4 " }} )( ( " g r e e kl e t t e r s "" " ) ) ;s t r i n g sl o n g e rt h a n2 0 4 7b y t e ss h o u l db ed e l i m t e dw i t h[ t e x t ] ,[ / t e x t ]t a g s ( j s o n p a r s e[ t e x t ] { " g r e e kl e t t e r s ":" \ u 0 3 b 1 \ u 0 3 b 2 \ u 0 3 b 3 \ u 0 3 b 4 " } [ / t e x t ] )( ( " g r e e kl e t t e r s "" " ) )

ThehexcoderepresentationofUnicodercharactersinJSONisthesameascanbeusedinUTF8enablednewLISP. BecauseJSONobjectscontain{ , } , " characters,quotesshouldnotbeusedtolimitJSONdata,orallquotesinsidetheJSONdata wouldneedaprecedingbackslash\ .{ , } bracescanbeusedaslongasbracesinsidetheJSONdataarebalanced.Thesafest delimiterare[ t e x t ] ,[ / t e x t ] tagstheysuppressallspecialprocessingofthestringwhenreadbynewLISPandaresuitableto delimitlargedatasizesgreater2047bytes.

join
syntax:(joinlistofstrings[strjoint[booltrailjoint]]) Concatenatesthegivenlistofstringsinlistofstrings.Ifstrjointispresent,itisinsertedbetweeneachstringinthejoin.Ifbooltrail jointist r u e thenajointstringisalsoappendedtothelaststring.
( s e t' l s t' ( " t h i s "" i s "" a "" s e n t e n c e " ) ) ( j o i nl s t"" ) " t h i si sas e n t e n c e " ( j o i n( m a ps t r i n g( s l i c e( n o w )03 ) )" " ) " 2 0 0 3 1 1 2 6 "

( j o i n( e x p l o d e" k e e pi tt o g e t h e r " ) ) " k e e pi tt o g e t h e r " ( j o i n' ( " A "" B "" C " )" " ) ( j o i n' ( " A "" B "" C " )" "t r u e ) " A B C " " A B C "

Seealsotheappend,string,andexplodefunctions,whicharetheinverseofthej o i n operation.

kmeansquery
syntax:(kmeansquerylistdatamatrixcentroids) syntax:(kmeansquerylistdatamatrixdata) Inthefirstusage,k m e a n s q u e r y calculatestheEuclidiandistancesfromthedatavectorgiveninlistdatatothecentroidsgivenin matrixcentroids.Thedatavectorinlistdatahasmelements.The2dimensionallistinmatrixcentroids,resultfromaprevious kmeanstrainclustering,haskrowsandmcolumnsforkcentroidsmeasuringmfeatures.
;c e n t r o i d sf r o mp r e v i o u sk m e a n s t r a i n K : c e n t r o i d s (( 6 . 3 97 . 1 8 8 3 3 3 3 3 35 . 9 3 5 ) ( 7 . 9 2 5 7 1 4 2 8 63 . 8 4 5 7 1 4 2 8 69 . 1 9 8 5 7 1 4 2 9 ) ( 2 . 2 0 7 1 4 2 8 5 72 . 8 8 1 4 2 8 5 7 10 . 8 8 8 5 7 1 4 2 8 6 )) ( k m e a n s q u e r y' ( 123 )K : c e n t r o i d s ) ( 8 . 0 3 6 4 8 7 2 7 99 . 4 7 5 9 9 4 2 6 72 . 5 8 6 9 3 6 5 7 );d i s t a n c e st oc l u s t e r1 ,2a n d3

Thedatarecord( 123 ) showsthesmallestdistancetothe3rdclustercentroidandwouldbeclassifiedasbelongingtothatcluster. Inthesecondapplicationk m e a n s q u e r y calculatesEuclidiandistancestoalistofotherdatapointswhicharenotcentroids.The followingexamplecalculatesdistancesofthe( 123 ) datavectortoalloriginalpointsfromtheoriginalkmeanstraindataanalysis. Thedatainmatrixdatacanbeeitheranestedlistora2dimensionalarray. ThisvectorcouldbesortedforasubsequentkNN(kNearestNeighbor)analysis:
( k m e a n s q u e r y' ( 123 )d a t a ) ( 1 0 . 9 1 6 7 1 1 9 63 . 1 9 0 6 2 6 8 9 89 . 1 9 7 2 3 3 2 83 . 0 1 4 4 1 5 3 6 69 . 0 7 9 7 6 3 2 1 3 6 . 8 3 1 3 0 2 9 58 . 5 3 3 1 1 1 9 7 69 . 6 2 4 8 1 6 8 8 16 . 4 4 4 2 6 1 0 1 32 . 0 1 3 1 0 7 0 5 1 3 . 1 8 6 5 4 9 8 5 89 . 4 7 5 1 9 9 2 0 69 . 3 2 9 3 6 7 6 12 . 8 7 4 7 8 6 9 4 97 . 0 8 4 6 3 8 3 1 1 1 0 . 9 6 2 2 1 2 3 71 0 . 5 0 0 8 0 4 7 33 . 1 6 2 4 1 9 9 5 92 . 4 2 3 6 7 4 8 9 69 . 5 2 6 4 3 6 8 9 9 ) ;s h o wd i s t a n c e st om e m b e r si ne a c hc l u s t e r ;f o rc l u s t e rl a b e l e d1 ( s e l e c t( k m e a n s q u e r y' ( 123 )d a t a )( K : c l u s t e r s0 ) ) ( 9 . 0 7 9 7 6 3 2 1 36 . 8 3 1 3 0 2 9 59 . 6 2 4 8 1 6 8 8 16 . 4 4 4 2 6 1 0 1 37 . 0 8 4 6 3 8 3 1 11 0 . 5 0 0 8 0 4 7 3 ) ;f o rc l u s t e rl a b e l e d2 ( s e l e c t( k m e a n s q u e r y' ( 123 )d a t a )( K : c l u s t e r s1 ) ) ( 1 0 . 9 1 6 7 1 1 9 69 . 1 9 7 2 3 3 2 88 . 5 3 3 1 1 1 9 7 69 . 4 7 5 1 9 9 2 0 69 . 3 2 9 3 6 7 6 11 0 . 9 6 2 2 1 2 3 79 . 5 2 6 4 3 6 8 9 9 ) ;f o rc l u s t e rl a b e l e d3 ( s e l e c t( k m e a n s q u e r y' ( 123 )d a t a )( K : c l u s t e r s2 ) ) ( 3 . 1 9 0 6 2 6 8 9 83 . 0 1 4 4 1 5 3 6 62 . 0 1 3 1 0 7 0 5 13 . 1 8 6 5 4 9 8 5 82 . 8 7 4 7 8 6 9 4 93 . 1 6 2 4 1 9 9 5 92 . 4 2 3 6 7 4 8 9 6 )

Weseethatthesmallestdistancesareshownforthedatapointsinthe3rdclusteratoffset2. Ifthenumbersofelementsfeaturesinrecordsoflistdataisdifferentfromthenumberofcolumnsinthedataorcentroidmatrix, thenthesmalleristakenforcalculatingtheEuclidiandistances.Thisisusefulwhenthelastcolumnofthedatamatrixdoesnot containfeaturedata,butlabelsidentifyingtheclustermembershipofadatapoint.

kmeanstrain
syntax:(kmeanstrainmatrixdataintkcontext[matrixcentroids]) ThefunctionperformsKmeansclusteranalysisonmatrixdata.Allndatarecordsinmatrixdataarepartitionedintoanumberof intkdifferentgroups. Both,then*mmatrixdataandtheoptionalk*mmatrixcentroidscanbeeithernestedlistsor2dimensionalarrays. TheKmeansalgorithmtriestominimizethesumofsquaredinnerclusterdistances(SSQ)fromtheclustercentroid.Witheach iterationthecentroidsgetmovedclosertotheirfinalposition.Onsomedatasets,theendresultcandependonthestartingcentroid points.Therightchoiceofinitialcentroidscanspeeduptheprocessandavoidnotwantedlocalminima. Whennooptionalmatrixcentroidsaregiven,k m e a n s t r a i n willassignaninitialrandomclustermembershiptoeachdatarowand calculatestartingcentroids.
k m e a n s t r a i n returnsavectoroftotalSSQs,thesumofsquaredinnerdistancesfromthecentroidinsidetheclusterforallclusters.

TheIteratingalgorithmstopswhenthechangeofSSQfromonetothenextiterationislessthan1e10. Otherresultsoftheanalysisarestoredaslistsinvariablesofcontext. Thefollowingexampleanalyses20datarecordsmeasuringm=3featuresandtriestopartitiondataintok=3clusters.Other numbersthank=3couldbetried.Thetargetisaresultwithfewclustersofhighdensitymeasuredbytheaverageinnercluster distances.


( s e t' d a t a' ( ( 6 . 5 74 . 9 61 1 . 9 1 ) ( 2 . 2 94 . 1 81 . 0 6 ) ( 8 . 6 32 . 5 18 . 1 1 ) ( 1 . 8 51 . 8 90 . 1 1 ) ( 7 . 5 67 . 9 35 . 0 6 ) ( 3 . 6 17 . 9 55 . 1 1 ) ( 7 . 1 83 . 4 68 . 7 ) ( 8 . 1 76 . 5 97 . 4 9 ) ( 5 . 4 45 . 95 . 5 7 ) ( 2 . 4 32 . 1 41 . 5 9 ) ( 2 . 4 82 . 2 60 . 1 9 ) ( 8 . 1 63 . 8 38 . 9 3 ) ( 8 . 4 95 . 3 17 . 4 7 ) ( 3 . 1 23 . 11 . 4 ) ( 6 . 7 76 . 0 43 . 7 6 ) ( 7 . 0 14 . 21 1 . 9 ) ( 6 . 7 98 . 7 28 . 6 2 ) ( 1 . 1 74 . 4 61 . 0 2 ) ( 2 . 1 12 . 1 40 . 8 5 ) ( 9 . 4 42 . 6 57 . 3 7 ) ) ) ( k m e a n s t r a i nd a t a3' M A I N : K ) ( 4 3 9 . 7 9 4 9 3 5 79 0 . 7 4 7 4 2 7 68 5 . 0 6 6 3 3 1 6 38 2 . 7 4 5 9 7 6 1 9 ) ;c l u s t e rm e m b e r s h i p K : l a b e l s( 23231121133223121332 ) ;t h ec e n t r o i df o re a c hc l u s t e r K : c e n t r o i d s (( 6 . 3 97 . 1 8 8 3 3 3 3 3 35 . 9 3 5 ) ( 7 . 9 2 5 7 1 4 2 8 63 . 8 4 5 7 1 4 2 8 69 . 1 9 8 5 7 1 4 2 9 ) ( 2 . 2 0 7 1 4 2 8 5 72 . 8 8 1 4 2 8 5 7 10 . 8 8 8 5 7 1 4 2 8 6 ))

ThereturnedlistofSSQsshowshowineachiterationthesumofinnersquareddistancesdecreases.ThelistinK : l a b e l s showsthe membershipfoeachdatapointinthesameorderasinthedata. ThecentroidsinK : c e n t r o i d s canbeusedforlaterclassificationofnewdatarecordsusingkmeansquery. TheaverageinnerK : d e v i a t i o n s fromclustermemberstotheircentroidshowhowdenseaclusterispacked.Formally,deviations

arecalculatedsimilarlytoEuclidiandistancesandtostandarddeviationsinconventionalstatistics.Squaringthedeviationsand multiplyingeachwiththeirclustersize(numberofmembersinthecluster)showstheinnerSSQofeachcluster:
;a v e r a g ei n n e rd e v i a t i o n so fc l u s t e rm e m b e r st ot h ec e n t r o i d ;d e v i a t i o n=s q r t ( s s q o f c l u s t e r/n o f c l u s t e r ) K : d e v i a t i o n s ( 2 . 4 5 7 0 5 2 2 0 92 . 2 6 0 0 8 9 3 9 71 . 2 4 0 2 3 6 9 7 5 ) ;c a l c u l a t i n gi n n e rS S Q sf r o mc l u s t e rd e v i a t i o n s ( m a pm u l' ( 677 )( m a pm u lK : d e v i a t i o n sK : d e v i a t i o n s ) ) ( 3 6 . 2 2 2 6 3 3 3 33 5 . 7 5 6 0 2 8 5 71 0 . 7 6 7 3 1 4 2 9 );i n n e rS S Q s ;S S Qf r o ml a s ti t e r a t i o na ss u mo fi n n e rS S Q s ( a p p l ya d d' ( 3 6 . 2 2 2 6 3 3 3 33 5 . 7 5 6 0 2 8 5 71 0 . 7 6 7 3 1 4 2 9 ) )8 2 . 7 4 5 9 7 6 1 9 K : c l u s t e r s givesindicesofdatarecordsintotheoriginaldataforeachcluster.Withthese,individualclusterscanbeextractedfrom

thedataforfurtheranalysis:
;c e a c ho ft h er e s u l tc l u s t e r sw i t hi n d i c e si n t ot h ed a t as e t K : c l u s t e r s (( 45781 41 6 ) ( 0261 11 21 51 9 ) ( 1391 01 31 71 8 )) ;c l u s t e ro fd a t ar e c o r d sl a b e l e d1a to f f s e t0 ( s e l e c td a t a( K : c l u s t e r s0 ) ) (( 7 . 5 67 . 9 35 . 0 6 ) ( 3 . 6 17 . 9 55 . 1 1 ) ( 8 . 1 76 . 5 97 . 4 9 ) ( 5 . 4 45 . 95 . 5 7 ) ( 6 . 7 76 . 0 43 . 7 6 ) ( 6 . 7 98 . 7 28 . 6 2 )) ;c l u s t e ro fd a t ar e c o r d sl a b e l e d2a to f f s e t1 ( s e l e c td a t a( K : c l u s t e r s1 ) ) (( 6 . 5 74 . 9 61 1 . 9 1 ) ( 8 . 6 32 . 5 18 . 1 1 ) ( 7 . 1 83 . 4 68 . 7 ) ( 8 . 1 63 . 8 38 . 9 3 ) ( 8 . 4 95 . 3 17 . 4 7 ) ( 7 . 0 14 . 21 1 . 9 ) ( 9 . 4 42 . 6 57 . 3 7 )) ;c l u s t e ro fd a t ar e c o r d sl a b e l e d3a to f f s e t2 ( s e l e c td a t a( K : c l u s t e r s2 ) ) (( 2 . 2 94 . 1 81 . 0 6 ) ( 1 . 8 51 . 8 90 . 1 1 ) ( 2 . 4 32 . 1 41 . 5 9 ) ( 2 . 4 82 . 2 60 . 1 9 ) ( 3 . 1 23 . 11 . 4 ) ( 1 . 1 74 . 4 61 . 0 2 ) ( 2 . 1 12 . 1 40 . 8 5 ))

Inthelastexampletheclusterlabels(from1to3)areaddedtothedata:
;a p p e n dac l u s t e rl a b e lt oe a c hd a t ar e c o r d ( s e t' l a b e l e d d a t a( t r a n s p o s e( p u s hK : l a b e l s( t r a n s p o s ed a t a )1 ) ) ) l a b e l e d d a t a : (( 6 . 5 74 . 9 61 1 . 9 12 ) ( 2 . 2 94 . 1 81 . 0 63 ) ( 8 . 6 32 . 5 18 . 1 12 ) ( 1 . 8 51 . 8 90 . 1 13 ) ( 7 . 5 67 . 9 35 . 0 61 ) ( 3 . 6 17 . 9 55 . 1 11 ) . . .. . . ( 2 . 1 12 . 1 40 . 8 53 ) ( 9 . 4 42 . 6 57 . 3 72 ))

TheresultcontextshouldbeprefixedwithM A I N whencodeiswritteninanamespacecontext.Ifthecontextdoesnotexistsalready, itwillbecreated.

ResultsinK : l a b e l s ,K : c l u s t e r s ,K : c e n t r o i d s andK : d e v i a t i o n s willbeoverwritten,ifalreadypresentfrompreviousrunsof k m e a n s t r a i n .

lambda
Seethedescriptionoffn,whichisashorterformofwritingl a m b d a .

lambdamacro
Seethedescriptionofdefinemacro.

lambda?
syntax:(lambda?exp) Returnst r u e onlyifthevalueofexpisalambdaexpressionotherwise,returnsn i l .
( d e f i n e( s q u a r ex )( *xx ) )( l a m b d a( x )( *xx ) ) s q u a r e( l a m b d a( x )( *xx ) ) ( l a m b d a ?s q u a r e ) t r u e

Seedefineanddefinemacroformoreinformationaboutlambdaexpressions.

lastutf8
syntax:(lastlist) syntax:(lastarray) syntax:(laststr) Returnsthelastelementofalistorastring.
( l a s t' ( 12345 ) ) 5 ( l a s t' ( ab( cd ) ) ) ( cd ) ( s e t' A( a r r a y32( s e q u e n c e16 ) ) ) ( ( 12 )( 34 )( 56 ) ) ( l a s tA ) ( 56 ) ( l a s t' ( ) ) E R R :l i s ti se m p t y

Inthesecondversionthelastcharacterinthestringstrisreturnedasastring.
( l a s t" n e w L I S P " ) " P "

NotethatlastworksoncharacterboundariesratherthanbyteboundarieswhentheUTF8enabledversionofnewLISPisused.See alsofirst,restandnth.

lasterror
syntax:(lasterror) syntax:(lasterrorinterror) ReportsthelasterrorgeneratedbynewLISPduetosyntaxerrorsorexhaustionofsomeresource.Forasummaryofallpossible errorsseethechapterErrorcodesintheappendix. IfnoerrorhasoccurredsincethenewLISPsessionwasstarted,n i l isreturned. Wheninterrorisspecified,alistofthenumberandtheerrortextisreturned.
( l a s t e r r o r ) n i l ( a b c ) E R R :i n v a l i df u n c t i o n:( a b c ) ( l a s t e r r o r )( 2 4" E R R :i n v a l i df u n c t i o n:( a b c ) " ) ( l a s t e r r o r2 4 )( 2 4" i n v a l i df u n c t i o n " ) ( l a s t e r r o r1 )( 1" n o te n o u g hm e m o r y " ) ( l a s t e r r o r1 2 3 4 5 )( 1 2 3 4 5" U n k n o w ne r r o r " )

Forerrornumbersoutofrangethestring" U n k n o w ne r r o r " isgivenfortheerrortext. Errorscanbetrappedbyerroreventanduserdefinederrorhandlers. Seealsoneterrorforerrorsgeneratedbynetworkingconditionsandsyserrorforerrorsgeneratedbytheoperatingsystem.

legal?
syntax:(legal?str) ThetokeninstrisverifiedasalegalnewLISPsymbol.Nonlegalsymbolscanbecreatedusingthesymfunction(e.g.symbols containingspaces,quotes,orothercharactersnotnormallyallowed).Nonlegalsymbolsarecreatedfrequentlywhenusingthemfor associativedataaccess:
( s y m b o l ?( s y m" o n et w o " ) ) t r u e ( l e g a l ?" o n et w o " ) n i l ;c o n t a i n sas p a c e

( s e t( s y m" o n et w o " )1 2 3 ) 1 2 3 ( e v a l( s y m" o n et w o " ) ) 1 2 3

Theexampleshowsthatthestring" o n et w o " doesnotcontainalegalsymbolalthoughasymbolcanbecreatedfromthisstring andtreatedlikeavariable.

length
syntax:(lengthexp)

Returnsthenumberofelementsinalist,thenumberofrowsinanarray,orthenumberofbytesinastring.
l e n g t h appliedtoasymbolreturnsthelengthofthesymbolname.Appliedtoanumber,l e n g t h returnsthenumberofbytes

neededinmemorytostorethatnumber:4or8forintegersand8forfloatingpointnumbers.
( l e n g t h' ( ab( cd )e ) ) ( l e n g t h' ( ) ) ( s e t' s o m e L i s t' ( qwerty ) ) ( l e n g t hs o m e L i s t ) 4 0 ( qwerty ) 6

( s e t' a r y( a r r a y24' ( 0 ) ) ) ( ( 1234 )( 5678 ) ) ( l e n g t ha r y ) 2 ( l e n g t h" H e l l oW o r l d " ) 1 1 ( l e n g t h" " ) 0 ( l e n g t h' s o m e V a r ) 7 ( l e n g t h1 2 3 ) 8 ( l e n g t h1 . 2 3 ) 8 ( l e n g t h( g e t i n t" \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 1 " ) )4

Useutf8lentocalculatethenumberofUTF8charactersinastring.

let
syntax:(let((sym1[expinit1])[(sym2[expinit2])...])body) syntax:(let(sym1expinit1[sym2expinit2...])body) Oneormorevariablessym1,sym2,...aredeclaredlocallyandinitializedwithexpressionsinexpinit1,expinit2,etc.Inthefully parenthesizedfirstsyntax,initializersareoptionalandassumedn i l ifmissing. Whenthelocalvariablesareinitialized,theinitializerexpressionsevaluateusingsymbolbindingsasbeforethel e t statement.To incrementallyusesymbolbindingsasevaluatedduringtheinitializationoflocalsinl e t ,useletn. Oneormoreexpressionsinexpbodyareevaluatedusingthelocaldefinitionsofsym1,sym2etc.l e t isusefulforbreakingup complexexpressionsbydefininglocalvariablesclosetotheplacewheretheyareused.Thesecondformomitstheparentheses aroundthevariableexpressionpairsbutfunctionsidentically.
( d e f i n e( s u m s qab ) ( l e t( ( x( *aa ) )( y( *bb ) ) ) ( +xy ) ) ) ( s u m s q34 )2 5 ( d e f i n e( s u m s qab ) ;a l t e r n a t i v es y n t a x ( l e t( x( *aa )y( *bb ) ) ( +xy ) ) )

Thevariablesx andy areinitialized,thentheexpression( +xy ) isevaluated.Theletformisjustanoptimizedversionand syntacticconvenienceforwriting:


( ( l a m b d a( s y m 1[ s y m 2. . .] )e x p b o d y)e x p i n i t 1[e x p i n i t 2] )

Seealsoletnforanincrementalornestedformofl e t andlocalforinitializington i l .Seelocalforautomaticinitializationof variableston i l .

letex

syntax:(letex((sym1[expinit1])[(sym2[expinit2])...])body) syntax:(letex(sym1expinit1[sym2expinit2...])body) Thisfunctioncombinesletandexpandtoexpandlocalvariablesintoanexpressionbeforeevaluatingit.Inthefullyparenthesized firstsyntaxinitializersareoptionalandassumedn i l ifmissing. Bothformsprovidethesamefunctionality,butinthesecondformtheparenthesesaroundtheinitializerscanbeomitted:


( l e t e x( x1y2z3 )' ( xyz ) ) ( 123 )

( l e t e x(( x1 )( y' ( abc ) )( z" h e l l o " ))' ( xyz ) ) ( 1( abc )" h e l l o " )

Beforetheexpression' ( xyz ) getsevaluated,x ,y andz areliterallyreplacedwiththeinitializersfromthel e t e x initializerlist. Thefinalexpressionwhichgetsevaluatedis' ( 123 ) . Inthesecondexampleafunctionm a k e a d d e r isdefinedformakingadderfunctions:
( d e f i n e( m a k e a d d e rn ) ( l e t e x( cn )( l a m b d a( x )( +xc ) ) ) ) ( d e f i n ea d d 3( m a k e a d d e r3 ) )( l a m b d a( x )( +x3 ) ) ( a d d 31 0 )1 3 ;l e t e xc a ne x p a n ds y m b o l si n t ot h e m s e l v e s ;t h ef o l l o w i n gf o r ma l s ow o r k s ( d e f i n e( m a k e a d d e rn ) ( l e t e x( nn )( l a m b d a( x )( +xn ) ) ) ) l e t e x evaluatesn totheconstant3 andreplacesc withitinthelambdaexpression.Thesecondexamplesshows,howal e t e x

variablecanbeexpandedintoitself.

letn
syntax:(letn((sym1[expinit1])[(sym2[expinit2])...])body) syntax:(letn(sym1expinit1[sym2expinit2...])body)
l e t n islikeanestedletandworkssimilarlytolet,butwillincrementallyusethenewsymbolbindingswhenevaluatingthe

initializerexpressionsasifseveralletwerenested.Inthefullyparenthesizedfirstsyntax,initializersareoptionalandassumedn i l if missing. Thefollowingcomparisonofletandl e t n showthedifference:


( s e t' x1 0 ) ( l e t( ( x1 )( y( +x1 ) ) ) ( l i s txy ) ) ( 11 1 ) ( l e t n( ( x1 )( y( +x1 ) ) ) ( l i s txy ) ) ( 12 )

Whileinthefirstexampleusingletthevariabley iscalculatedusingthebindingofx beforetheletexpression,inthesecond exampleusingl e t n thevariabley iscalculatedusingthenewlocalbindingofx .


( l e t n ( x1yx ) ( +xy ) ) 2 ; ;s a m ea sn e s t e dl e t ' s

( l e t( x1 ) ( l e t( yx ) ( +xy ) ) ) 2 l e t n workslikeseveralnestedlet.Theparenthesesaroundtheinitializerexpressionscanbeomitted.

list
syntax:(listexp1[exp2...]) Theexpareevaluatedandthevaluesusedtoconstructanewlist.Notethatargumentsofarraytypeareconvertedtolists.
( l i s t12345 ) ( 12345 ) ( l i s t' a' ( bc )( +34 )' ( )' * )( a( bc )7( )* )

Seealsoconsandpushforotherformsofbuildinglists.

list?
syntax:(list?exp) Returnst r u e onlyifthevalueofexpisalistotherwisereturnsn i l .Notethatlambdaandlambdamacroexpressionsarealso recognizedasspecialinstancesofalistexpression.
( s e t' v a r' ( 1234 ) ) ( l i s t ?v a r ) ( 1234 ) t r u e

( d e f i n e( d o u b l ex )( +xx ) ) ( l i s t ?d o u b l e ) t r u e

load
syntax:(loadstrfilename1[strfilename2...][symcontext]) LoadsandtranslatesnewLISPfromasourcefilespecifiedinoneormorestrfilenameandevaluatestheexpressionscontainedin thefile(s).Whenloadingissuccessful,l o a d returnstheresultofthelastexpressioninthelastfileevaluated.Ifafilecannotbe loaded,l o a d throwsanerror. Anoptionalsymcontextcanbespecified,whichbecomesthecontextofevaluation,unlesssuchacontextswitchisalreadypresent inthefilebeingloaded.Bydefault,fileswhichdonotcontaincontextswitcheswillbeloadedintotheM A I N context. ThestrfilenamespecscancontainURLs.Bothh t t p : / / andf i l e : / / URLsaresupported.
( l o a d" m y f i l e . l s p " ) ( l o a d" a f i l e . l s p "" b f i l e . l s p " ) ( l o a d" f i l e . l s p "" h t t p : / / m y s i t e . o r g / m y p r o " ) ( l o a d" h t t p : / / 1 9 2 . 1 6 8 . 0 . 2 1 : 6 0 0 0 / / h o m e / t e s t / p r o g r a m . l s p " )

( l o a d" a f i l e . l s p "" b f i l e . l s p "' M y C T X ) ( l o a d" f i l e : / / / u s r / s h a r e / n e w l i s p / m y s q l . l s p " )

Incaseexpressionsevaluatedduringthel o a d arechangingthecontext,thiswillnotinfluencetheprogrammingmoduledoingthe l o a d . Thecurrentcontextafterthel o a d statementwillalwaysbethesameasbeforethel o a d . NormalfilespecsandURLscanbemixedinthesameloadcommand.


l o a d withH T T P URLscanalsobeusedtoloadcoderemotelyfromnewLISPservernodesrunningonaUnixlikeoperating

system.Inthismode,l o a d willissueanHTTPGETrequesttothetargetURL.Notethatadoublebackslashisrequiredwhenpath namesarespecifiedrelativetotherootdirectory.l o a d inH T T P modewillobservea60secondtimeout. ThesecondtolastlinecausesthefilestobeloadedintothecontextM y C T X .Thequoteforcesthecontexttobecreatedifitdidnot exist. Thef i l e : / / URLisfollowedbyathird/ forthedirectoryspec.

local
syntax:(local(sym1[sym2...])body) Initializesoneormoresymbolsinsym1ton i l ,evaluatestheexpressionsinbody,andreturnstheresultofthelastevaluation.
l o c a l workssimilarlytolet,butlocalvariablesareallinitializedton i l . l o c a l providesasimplewaytolocalizevariableswithoutexplicitinitialization.

log
syntax:(lognum) syntax:(lognumnumbase) Inthefirstsyntax,theexpressioninnumisevaluatedandthenaturallogarithmicfunctioniscalculatedfromtheresult.
( l o g1 ) ( l o g( e x p1 ) ) 0 1

Inthesecondsyntax,anarbitrarybasecanbespecifiedinnumbase.
( l o g1 0 2 42 ) ( l o g( e x p1 )( e x p1 ) ) 1 0 1

Seealsoexp,whichistheinversefunctiontol o g withbasee(2.718281828).

lookup
syntax:(lookupexpkeylistassoc[intindex[expdefault]])

Findsinlistassocanassociation,thekeyelementofwhichhasthesamevalueasexpkey,andreturnstheintindexelementof association(orthelastelementifintindexisabsent). Optionally,expdefaultcanbespecified,whichisreturnedifanassociationmatchingexpkeycannotbefound.Iftheexpdefaultis absentandnoassociationhasbeenfound,n i l isreturned. SeealsoIndexingelementsofstringsandlists.


l o o k u p issimilartoassocbutgoesonestepfurtherbyextractingaspecificelementfoundinthelist. ( s e t' p a r a m s' ( ( n a m e" J o h nD o e " ) ( a g e3 5 ) ( g e n d e r" M " ) ( b a l a n c e1 2 . 3 4 ) ) ) ( l o o k u p' a g ep a r a m s ) 3 5

;u s et o g e t h e rw i t hs e t ft om o d i f ya n da s s o c i a t i o nl i s t ( s e t f( l o o k u p' a g ep a r a m s )4 2 ) 4 2 ( l o o k u p' a g ep a r a m s ) 4 2 ( s e t' p e r s o n s' ( ( " J o h nD o e "3 5" M "1 2 . 3 4 ) ( " M i c k e yM o u s e "6 5" N "1 2 3 4 5 6 7 8 ) ) ) ( l o o k u p" M i c k e yM o u s e "p e r s o n s2 ) ( l o o k u p" M i c k e yM o u s e "p e r s o n s3 ) ( l o o k u p" J o h nD o e "p e r s o n s1 ) ( l o o k u p" J o h nD o e "p e r s o n s2 ) " N " 6 5 3 5 " M "

( l o o k u p" J a n eD o e "p e r s o n s1" N / A " ) " N / A "

Seealsoassoc

lowercaseutf8
syntax:(lowercasestr) Convertsthecharactersofthestringinstrtolowercase.Anewstringiscreated,andtheoriginalisleftunaltered.
( l o w e r c a s e" H E L L OW O R L D " ) " h e l l ow o r l d " ( s e t' S t r" A B C " ) ( l o w e r c a s eS t r ) " a b c " S t r " A B C "

Seealsotheuppercaseandtitlecasefunctions.

macro?
syntax:(macro?exp) returnst r u e ifexpevaluatestoalambdamacroexpressionotherwise,n i l isreturned.
( d e f i n e m a c r o( m y s e t ql vr v )( s e tl v( e v a lr v ) ) )

( m a c r o ?m y s e t q ) t r u e

mainargs
syntax:(mainargs) syntax:(mainargsintindex)
m a i n a r g s returnsalistwithseveralstringmembers,oneforprograminvocationandoneforeachofthecommandlinearguments. n e w l i s p123 >( m a i n a r g s ) ( " / u s r / b i n / n e w l i s p "" 1 "" 2 "" 3 " )

Aftern e w l i s p123 isexecutedatthecommandprompt,m a i n a r g s returnsalistcontainingthenameoftheinvokingprogram andthreecommandlinearguments. Optionally,m a i n a r g s cantakeanintindexforindexingintothelist.Notethatanindexoutofrangewillcausen i l tobereturned, notthelastelementofthelistlikeinlistindexing.


n e w l i s pabc >( m a i n a r g s0 ) " / u s r / b i n / n e w l i s p " >( m a i n a r g s1 ) " c " >( m a i n a r g s2 ) " b " >( m a i n a r g s1 0 ) n i l

NotethatwhennewLISPisexecutedfromascript,m a i n a r g s alsoreturnsthenameofthescriptasthesecondargument:
# ! / u s r / b i n / n e w l i s p # #s c r i p tt os h o wt h ee f f e c to f' m a i n a r g s 'i ns c r i p tf i l e ( p r i n t( m a i n a r g s )" \ n " ) ( e x i t ) #e n do fs c r i p tf i l e ; ;e x e c u t es c r i p ti nt h eO Ss h e l l : s c r i p t123 ( " / u s r / b i n / n e w l i s p "" . / s c r i p t "" 1 "" 2 "" 3 " )

Tryexecutingthisscriptwithdifferentcommandlineparameters.

makedir
syntax:(makedirstrdirname[intmode]) Createsadirectoryasspecifiedinstrdirname,withtheoptionalaccessmodeintmode.Returnst r u e orn i l dependingonthe outcome.Ifnoaccessmodeisspecified,mostUnixsystemsdefaulttod r w x r x r x . OnUnixsystems,theaccessmodespecifiedwillalsobemaskedbytheOS'susermasksetbythesystemadministrator.Theuser

maskcanberetrievedonUnixsystemsusingthecommandu m a s k andisusually0 0 2 2 (octal),whichmaskswrite(andcreation) permissionfornonownersofthefile.


; ;0( z e r o )i nf r o n to f7 5 0m a k e si ta no c t a ln u m b e r ( m a k e d i r" a d i r "0 7 5 0 )

Thisexamplecreatesadirectorynameda d i r inthecurrentdirectorywithanaccessmodeof0 7 5 0 (octal750=d r w x r x ).

map
syntax:(mapexpfunctorlistargs1[listargs2...]) Successivelyappliestheprimitivefunction,definedfunction,orlambdaexpressionexpfunctortotheargumentsspecifiedinlist args1,listargs2,returningallresultsinalist.
( m a p+' ( 123 )' ( 5 06 07 0 ) ) ( 5 16 27 3 ) ( m a pi f' ( t r u en i lt r u en i lt r u e )' ( 12345 )' ( 67891 0 ) ) ' ( 17395 ) ( m a p( f n( xy )( *xy ) )' ( 34 )' ( 2 01 0 ) ) ( 6 04 0 )

Thesecondexampleshowshowtodynamicallycreateafunctionform a p :
( d e f i n e( f o oo pp ) ( a p p e n d( l a m b d a( x ) )( l i s t( l i s to pp' x ) ) ) )

Wecanalsousetheshorterf n :
( d e f i n e( f o oo pp ) ( a p p e n d( f n( x ) )( l i s t( l i s to pp' x ) ) ) ) f o o nowworkslikeafunctionmaker: ( f o o' a d d2 ) ( l a m b d a( x )( a d d2x ) ) ( m a p( f o oa d d2 )' ( 12345 ) ) ( 34567 ) ( m a p( f o om u l3 )' ( 12345 ) ) ( 3691 21 5 )

NotethatthequotebeforetheoperandcanbeomittedbecauseprimitivesevaluatetothemselvesinnewLISP. Byincorporatingm a p intothefunctiondefinition,wecandothefollowing:


( d e f i n e( l i s t m a po ppl s t ) ( m a p( l a m b d a( x )( o ppx ) )l s t ) ) ( l i s t m a p+2' ( 1234 ) ) ( 3456 ) ( l i s t m a pm u l1 . 5' ( 1234 ) ) ( 1 . 534 . 56 ) m a p alsosetstheinternallistindex$ i d x . ( m a p( f n( x )( l i s t$ i d xx ) )' ( abc ) )( ( 0a )( 1b )( 2c ) )

Thenumberofargumentsusedisdeterminedbythelengthofthefirstargumentlist.Argumentsmissinginotherargumentlists causemaptostopcollectingparametersforthatlevelofarguments.Thisensuresthatthenthparameterlistgetsconvertedtothenth columnduringthetranspositionoccurring.Ifanargumentlistcontainstoomanyelements,theextraoneswillbeignored. Specialformswhichuseparenthesesassyntaxcannotbemapped(i.e.case).

mat
syntax:(mat+||*|/matrixAmatrixB) syntax:(mat+||*|/matrixAnumber) Usingthefirstsyntax,thisfunctionperformsfastfloatingpointscalaroperationsontwodimensionalmatricesinmatrixAormatrix B.Thetypeofoperationisspecifiedbyoneofthefourarithmeticoperators+ ,,* ,or/ .Thistypeofarithmeticoperatoristypically usedforintegeroperationsinnewLISP.Inthecaseofm a t ,however,alloperationswillbeperformedasfloatingpointoperations (a d d ,s u b ,m u l ,d i v ). MatricesinnewLISParetwodimensionallistsorarrays.Internally,newLISPtranslateslistsandarraysintofast,accessibleC languagedataobjects.ThismakesmatrixoperationsinnewLISPasfastasthosecodeddirectlyinC.Thesameistrueforthematrix operationsmultiplyandinvert.
( s e t' A' ( ( 123 )( 456 ) ) ) ( s e t' BA ) ( m a t+AB ) ( m a t-AB ) ( m a t*AB ) ( m a t/AB ) ( ( 246 )( 81 01 2 ) ) ( ( 000 )( 000 ) ) ( ( 149 )( 1 62 53 6 ) ) ( ( 111 )( 111 ) )

;s p e c i f yt h eo p e r a t o ri nav a r i a b l e ( s e t' o p+ ) ( m a to pAB ) ( ( 246 )( 81 01 2 ) )

Usingthesecondsyntax,allcellsinmatrixAareoperatedonwithascalarinnumber:
( m a t+A5 ) ( m a t-A2 ) ( m a t*A3 ) ( m a t/A1 0 ) ( ( 678 )( 91 01 1 ) ) ( ( 101 )( 234 ) ) ( ( 369 )( 1 21 51 8 ) ) ( ( . 1. 2. 3 )( . 4. 5. 6 ) )

Seealsotheothermatrixoperationsdet,invert,multiply,andtranspose.

match
syntax:(matchlistpatternlistmatch[bool]) Thepatterninlistpatternismatchedagainstthelistinlistmatch,andthematchingexpressionsarereturnedinalist.Thethree wildcardcharacters? ,+ ,and* canbeusedinlistpattern. Wildcardcharactersmaybenested.m a t c h returnsalistofmatchedexpressions.Foreach? (questionmark),amatchingexpression elementisreturned.Foreach+ (plussign)or* (asterisk),alistcontainingthematchedelementsisreturned.Ifthepatterncannotbe matchedagainstthelistinlistmatch,m a t c h returnsn i l .Ifnowildcardcharactersarepresentinthepatternanemptylistisreturned. Optionally,theBooleanvaluet r u e (oranyotherexpressionnotevaluatington i l )canbesuppliedasathirdargument.Thiscauses m a t c h toshowallelementsinthereturnedresult.
m a t c h isfrequentlyemployedasafunctorparameterinfind,ref,refallandreplaceandisinternallyusedbyfindallforlists. ( m a t c h' ( a?c )' ( abc ) ) ( b ) ( m a t c h' ( a?? )' ( abc ) ) ( bc )

( m a t c h' ( a?c )' ( a( xyz )c ) ) ( ( xyz ) ) ( m a t c h' ( a?c )' ( a( xyz )c )t r u e ) ( a( xyz )c ) ( m a t c h' ( a?c )' ( axyzc ) ) n i l ( m a t c h' ( a*c )' ( axyzc ) ) ( ( xyz ) ) ( m a t c h' ( a( bc? )xyz )' ( a( bcd )xyz ) ) ( d ) ( m a t c h' ( a( * )x?z )' ( a( bcd )xyz ) ) ( ( bcd )y ) ( m a t c h' ( + )' ( ) ) n i l ( m a t c h' ( + )' ( a ) ) ( ( a ) ) ( m a t c h' ( + )' ( ab ) ) ( ( ab ) ) ( m a t c h' ( a( * )x?z )' ( a( )xyz ) ) ( ( )y ) ( m a t c h' ( a( + )x?z )' ( a( )xyz ) ) n i l

Notethatthe* operatortriestograbthefewestnumberofelementspossible,butm a t c h backtracksandgrabsmoreelementsifa matchcannotbefound. The+ operatorworkssimilarlytothe* operator,butitrequiresatleastonelistelement. Thefollowingexampleshowshowthematchedexpressionscanbeboundtovariables.


( m a ps e t' ( xy )( m a t c h' ( a( ?c )d* )' ( a( bc )def ) ) ) x b y ( ef )

Notethatm a t c h forstringshasbeeneliminated.Formorepowerfulstringmatching,useregex,find,findallorparse. unifyisanotherfunctionformatchingexpressionsinaPROLOGlikemanner.

max
syntax:(maxnum1[num2...]) Evaluatestheexpressionsnum1andreturnsthelargestnumber.
( m a x4623 . 5 47 . 1 ) 7 . 1

Seealsotheminfunction.

member
syntax:(memberexplist) syntax:(memberstrkeystr[numoption]) Inthefirstsyntax,m e m b e r searchesfortheelementexpinthelistlist.Iftheelementisamemberofthelist,anewliststartingwith theelementfoundandtherestoftheoriginallistisconstructedandreturned.Ifnothingisfound,n i l isreturned.Whenspecifying numoption,m e m b e r performsaregularexpressionsearch.

( s e t' a L i s t' ( abcdefgh ) ) ( abcdefgh ) ( m e m b e r' da L i s t ) ( defgh ) ( m e m b e r5 5a L i s t ) n i l

Inthesecondsyntax,m e m b e r searchesforstrkeyinstr.Ifstrkeyisfound,allofstr(startingwithstrkey)isreturned.n i l is returnedifnothingisfound.


( m e m b e r" L I S P "" n e w L I S P " ) ( m e m b e r" L I "" n e w L I S P " ) ( m e m b e r" "" n e w L I S P " ) ( m e m b e r" x y z "" n e w L I S P " ) ( m e m b e r" l i "" n e w L I S P "1 ) " L I S P " " L I S P " " n e w L I S P " n i l " L I S P "

Seealsotherelatedfunctionssliceandfind.

min
syntax:(minnum1[num2...]) Evaluatestheexpressionsnum1andreturnsthesmallestnumber.
( m i n4623 . 5 47 . 1 ) 2

Seealsothemaxfunction.

mod
syntax:(modnum1num2[num3...]) syntax:(modnum1) Calculatesthemodularvalueofthenumbersinnum1andnum2.m o d computestheremainderfromthedivisionofthenumerator numibythedenominatornumi+1.Specifically,thereturnvalueisnumeratorn*denominator,wheren isthequotientofthe numeratordividedbythedenominator,roundedtowardszerotoaninteger.Theresulthasthesamesignasthenumeratorandits magnitudeislessthanthemagnitudeofthedenominator. Inthesecondsyntax1 isassumedfornum2andtheresultisthefractionalpartofnum1.
( m o d1 0 . 53 . 3 ) 0 . 6 ( m o d1 0 . 53 . 3 ) 0 . 6 ( m o d1 0 . 5 ) 0 . 5

Usethe%(percentsign)functionwhenworkingwithintegersonly.

mul
syntax:(mulnum1num2[num3...]) Evaluatesallexpressionsnum1,calculatingandreturningtheproduct.m u l canperformmixedtypearithmetic,butitalways returnsfloatingpointnumbers.AnyfloatingpointcalculationwithN a N alsoreturnsN a N .
( m u l123451 . 1 ) 1 3 2

( m u l0 . 50 . 5 )

0 . 2 5

multiply
syntax:(multiplymatrixAmatrixB) ReturnsthematrixmultiplicationofmatricesinmatrixAandmatrixB.IfmatrixAhasthedimensionsnbymandmatrixBthe dimensionskbyl(mandkmustbeequal),theresultisannbylmatrix.m u l t i p l y canperformmixedtypearithmetic,butthe resultsarealwaysdoubleprecisionfloatingpoints,evenifallinputvaluesareintegers. Thedimensionsofamatrixaredeterminedbythenumberofrowsandthenumberofelementsinthefirstrow.Formissingelements innonrectangularmatrices,0 . 0 isassumed.Amatrixcaneitherbeanestedlistorarray.
( s e t' A' ( ( 123 )( 456 ) ) ) ( s e t' B' ( ( 12 )( 12 )( 12 ) ) ) ( m u l t i p l yAB ) ( ( 61 2 )( 1 53 0 ) ) ( s e t' v' ( 1 02 03 0 ) ) ( m u l t i p l yA( t r a n s p o s e( l i s tv ) ) )( ( 1 4 0 )( 3 2 0 ) )

Whenmultiplyingamatrixwithavectorofn elements,thevectormustbetransformedinton rowsby1 columnmatrixusing transpose. Alloperationsshownhereonlistscanbeperformedonarrays,aswell. Seealsothematrixoperationsdet,invert,matandtranspose.

name
Thisfunctionisdeprecated,useterminstead.

NaN?
syntax:(NaN?float) TestsiftheresultofafloatingpointmathoperationisaN a N .CertainfloatingpointoperationsreturnaspecialIEEE754number formatcalledaN a N for'NotaNumber'.
;f l o a t i n gp o i n to p e r a t i o no nN a Ny i e l dN a N ( s e t' x( s q r t1 ) ) N a N ( N a N ?x ) t r u e ( a d dx1 2 3 ) N a N ( m u lx1 2 3 ) N a N ;i n t e g e ro p e r a t i o n st r e a tN a Na sz e r o ( +x1 2 3 ) 1 2 3 ( *x1 2 3 ) 0 ;c o m p a r i s o n sw i t hN a Nv a l u e sy i e l dn i l ( >x0 ) n i l ( < =x0 ) n i l ( =xx ) n i l

( s e t' i n f i n i t y( m u l1 . 0 e 2 0 01 . 0 e 2 0 0 ) )i n f ( N a N ?( s u bi n f i n i t yi n f i n i t y ) )t r u e

NotethatallfloatingpointarithmeticoperationswithaN a N yieldaN a N .AllcomparisonswithN a N returnn i l ,butt r u e when comparingtoitself.Comparisonwithitself,however,wouldresultinnott r u e whenusingANSIC.IntegeroperationstreatN a N as 0 (zero)values. Seealsoinf?fortestingafloatingpointvalueforinfinity.

netaccept
syntax:(netacceptintsocket) Acceptsaconnectiononasocketpreviouslyputintolisteningmode.Returnsanewlycreatedsockethandleforreceivingand sendingdataonthisconnection.
( s e t' s o c k e t( n e t l i s t e n1 2 3 4 ) ) ( n e t a c c e p ts o c k e t )

Notethatforportslessthan1024,newLISPmustbestartedinsuperusermodeonUnixlikeoperatingsystems. Seealsothefiless e r v e r andc l i e n t examplesinthee x a m p l e s / directoryofthesourcedistribution.

netclose
syntax:(netcloseintsocket[true]) Closesanetworksocketinintsocketthatwaspreviouslycreatedbyanetconnectornetacceptfunction.Returnst r u e onsuccess andn i l onfailure.
( n e t c l o s ea S o c k )

Theoptionaltrueflagsuppressesimmediateshutdownofsocketsbywaitingforpendingdatatransmissionstofinish.

netconnect
syntax:(netconnectstrremotehostintport[inttimeoutms]) syntax:(netconnectstrremotehostintport[strmode[intttl]]) syntax:(netconnectstrfilepath) Inthefirstsyntax,connectstoaremotehostcomputerspecifiedinstrremotehostandaportspecifiedinintport.Returnsasocket handleafterhavingconnectedsuccessfullyotherwise,returnsn i l .
( s e t' s o c k e t( n e t c o n n e c t" e x a m p l e . c o m "8 0 ) ) ( n e t s e n ds o c k e t" G E T/ \ r \ n \ r \ n " ) ( n e t r e c e i v es o c k e tb u f f e r1 0 0 0 0 ) ( p r i n t l nb u f f e r ) ( e x i t )

Ifsuccessful,then e t c o n n e c t functionreturnsasocketnumberwhichcanbeusedtosendandreceiveinformationfromthehost.

IntheexampleaHTTPGETrequestissentandsubsequentlyawebpagereceived.NotethatnewLISPhasalreadyabuiltin functiongeturlofferingthesamefunctionality. Optionallyatimeoutvalueinttimeoutinmillisecondscanbespecified.Withoutatimeoutvaluethefunctionwillwaitupto10 secondsforanopenport.Withatimeoutvaluethefunctioncanbemadetoreturnonanunavailableportmuchearlierorlater.The followingexampleshowsaportscannerlookingforopenports:


( s e t' h o s t( m a i n a r g s2 ) ) ( p r i n t l n" S c a n n i n g :"h o s t ) ( f o r( p o r t11 0 2 4 ) ( i f( s e t' s o c k e t( n e t c o n n e c th o s tp o r t5 0 0 ) ) ( p r i n t l n" o p e np o r t :"p o r t""( o r( n e t s e r v i c ep o r t" t c p " )" " ) ) ( p r i n tp o r t" \ r " ) ) )

TheprogramstakesthehoststringfromtheshellcommandlineaseitheradomainnameoranIPnumberindotnotationthentries toopeneachportfrom1to1024.Foreachopenporttheportnumberandtheservicedescriptionstringisprinted.Ifnodescription isavailable,anemptystring""isoutput.Forclosedportsthefunctionoutputsnumbersintheshellwindowstayingonthesame line. OnUnixn e t c o n n e c t mayreturnwithn i l beforethetimeoutexpires,whentheportisnotavailable.OnWin32n e t c o n n e c t willalwayswaitforthetimeouttoexpirebeforefailingwithn i l .

UDPcommunications
Inthesecondsyntax,athirdparameter,thestring" u d p " or" u " canbespecifiedintheoptionalstrmodetocreateasocketsuitedfor UDP(UserDatagramProtocol)communications.InUDPmode,n e t c o n n e c t doesnottrytoconnecttotheremotehost,but createsthesocketandbindsittotheremoteaddress,ifanaddressisspecified.AsubsequentnetsendwillsendaUDPpacket containingthattargetaddress.Whenusingnetsendto,onlyoneofthetwofunctionsn e t c o n n e c t orn e t s e n d t o should provideatargetaddress.Theotherfunctionshouldspecifyandemptystring" " asthetargetaddress.
; ;e x a m p l es e r v e r ( n e t l i s t e n4 0 9 6" 2 2 6 . 0 . 0 . 1 "" u d p " ) 5 ( n e t r e c e i v e f r o m52 0 ) ; ;e x a m p l ec l i e n tI ( n e t c o n n e c t" 2 2 6 . 0 . 0 . 1 "4 0 9 6" u d p " )3 ( n e t s e n d3" h e l l o " ) ; ;e x a m p l ec l i e n tI I ( n e t c o n n e c t" "4 0 9 6" u d p " )3 ( n e t s e n d t o" 2 2 6 . 0 . 0 . 1 "4 0 9 6" h e l l o "3 )

ThefunctionsnetreceiveandnetreceivefromcanbothbeusedandwillperformUDPcommunicationswhenthe" u d p " optionas beenusedinn e t l i s t e n orn e t c o n n e c t .netselectandnetpeekcanbeusedtocheckforreceiveddatainanonblocking fashion. netlistenbindsaspecificlocaladdressandporttothesocket.Whenn e t c o n n e c t isused,thelocaladdressandportwillbepicked bythesocketstackfunctionsofthehostOS.

UDPmulticastcommunications
Whenspecifying" m u l t i " or" m " asathirdparameterforstrmode,asocketforUDPmulticastcommunicationswillbecreated. Optionally,thefourthparameteri n t t t l canbespecifiedasaTTL(timetolive)value.Ifnointttlvalueisspecified,avalueof3 isassumed. NotethatspecifyingUDPmulticastmodeinn e t c o n n e c t doesnotactuallyestablishaconnectiontothetargetmulticastaddress butonlyputsthesocketintoUDPmulticastingmode.Onthereceivingside,usenetlistentogetherwiththeUDPmulticastoption.
; ;e x a m p l ec l i e n tI ( n e t c o n n e c t" "4 0 9 6" m u l t i " ) 3 ( n e t s e n d t o" 2 2 6 . 0 . 0 . 1 "4 0 9 6" h e l l o "3 )

; ;e x a m p l ec l i e n tI I ( n e t c o n n e c t" 2 2 6 . 0 . 0 . 1 "4 0 9 6" m u l t i " ) 3 ( n e t s e n d3" h e l l o " ) ; ;e x a m p l es e r v e r ( n e t l i s t e n4 0 9 6" 2 2 6 . 0 . 0 . 1 "" m u l t i " ) 5 ( n e t r e c e i v e f r o m52 0 ) ( " h e l l o "" 1 9 2 . 1 6 8 . 1 . 9 4 "3 2 7 6 9 )

Ontheserverside,netpeekornetselectcanbeusedfornonblockingcommunications.Intheaboveexample,theserverwould blockuntiladatagramisreceived. Theaddress2 2 6 . 0 . 0 . 1 isjustonemulticastaddressintheClassDrangeofmulticastaddressesfrom2 2 4 . 0 . 0 . 0 to 2 3 9 . 2 5 5 . 2 5 5 . 2 5 5 . Thenetsendandnetreceivefunctionscanalsobeusedinsteadofnetsendtoandnetreceivefrom.

UDPbroadcastcommunications
Specifyingthestring" b r o a d c a s t " or" b " inthethirdparameter,strmode,causesUDPbroadcastcommunicationstobesetup.In thiscase,thebroadcastaddressendingin255isused.
; ;e x a m p l ec l i e n t ( n e t c o n n e c t" 1 9 2 . 1 6 8 . 2 . 2 5 5 "3 0 0 0" b r o a d c a s t " ) 3 ( n e t s e n d3" h e l l o " ) ; ;e x a m p l es e r v e r ( n e t l i s t e n3 0 0 0" "" u d p " ) 5 ( n e t r e c e i v e5b u f f1 0 ) b u f f " h e l l o " ; ;o r ( n e t r e c e i v e f r o m51 0 ) ( " h e l l o "" 1 9 2 . 1 6 8 . 2 . 1 "4 6 6 2 0 )

Notethatonthereceivingside,netlistenshouldbeusedwiththedefaultaddressspecifiedwithan" " (emptystring).Broadcasts willnotbereceivedwhenspecifyinganaddress.AswithallUDPcommunications,netlistendoesnotactuallyputthereceiving sideinlistenmode,butrathersetsupthesocketsforthespecificUDPmode. Thenetselectornetpeekfunctionscanbeusedtocheckforincomingcommunicationsinanonblockingfashion.

LocaldomainUnixsockets
Inthethirdsyntax,n e t c o n n e c t connectstoaserveronthelocalfilesystemviaalocaldomainUnixsocketnamedusingstrfile path.Returnsasockethandleafterhavingconnectedsuccessfullyotherwise,returnsn i l .
( n e t c o n n e c t" / t m p / m y s o c k e t " ) 3 ;o nO S / 2u s e" \ \ s o c k e t \ \ "p r e f i x ( n e t c o n n e c t" \ \ s o c k e t \ \ m y s o c k e t " )

Alocaldomainfilesystemsocketiscreatedandreturned.Ontheserverside,localdomainsocketshavebeencreatedusingnet listenandnetaccept.Aftertheconnectionhasbeenestablishedthefunctionsnetselect,netsendandnetreceivecanbeusedas usualforTCP/IPstreamcommunications.Thistypeofconnectioncanbeusedasafastbidirectionalcommunicationschannel betweenprocessesonthesamefilesystem.ThistypeofconnectionisnotavailableonWin32platforms.

neterror
syntax:(neterror)

syntax:(neterrorinterror) Retrievesthelasterrorthatoccurredwhencallingaanyofthefollowingfunctions:netaccept,netconnect,neteval,netlisten,net lookup,netreceive,netreceiveudp,netselect,netsend,netsendudp,andnetservice.Wheneveroneofthesefunctionsfails,it returnsn i l andn e t e r r o r canbeusedtoretrievemoreinformation. Functionsthatcommunicateusingsocketsclosethesocketautomaticallyandremoveitfromthenetsessionslist. Eachsuccessfulterminationofanet*functionclearstheerrornumber. Thefollowingmessagesarereturned: no description 1 Cannotopensocket 2 DNSresolutionfailed 3 Notavalidservice 4 Connectionfailed 5 Acceptfailed 6 Connectionclosed 7 Connectionbroken 8 Socketsend()failed 9 Socketrecv()failed 10 Cannotbindsocket 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Toomanysocketsinnetselect Listenfailed BadlyformedIP Selectfailed Peekfailed Notavalidsocket Cannotunblocksocket Operationtimedout HTTPbadformedURL HTTPfileoperationfailed HTTPtransferfailed HTTPinvalidresponsefromserver HTTPnoresponsefromserver HTTPdocumentempty HTTPerrorinheader HTTPerrorinchunkedformat

( n e t e r r o r )n i l ( n e t c o n n e c t" j h g h j g k j h g "8 0 ) n i l ( n e t e r r o r ) ( 2" E R R :" D N Sr e s o l u t i o nf a i l e d " )

Wheninterrorisspecifiedthenumberanderrortextforthaterrornumberisreturned.
( n e t e r r o r1 0 )( 1 0" C a n n o tb i n ds o c k e t " )

Seealsolasterrorandsyserror.

neteval
syntax:(netevalstrhostintportexp[inttimeout[funchandler]]) syntax:(neteval'((strhostintportexp)...)[inttimeout[funchandler]]) CanbeusedtoevaluatesourceremotelyononeormorenewLISPservers.Thisfunctionhandlesallcommunicationsnecessaryto connecttotheremoteservers,sendsourceforevaluation,andwaitandcollectresponses. Theexpressioninexpevaluatestoeitherastringoranexpressionwhichwillbeevaluatedremotelyintheenvironmentofthetarget node. TheremoteTCP/IPserversarestartedinthefollowingway:
n e w l i s pcd4 7 1 1& ;o rw i t hl o g g i n gc o n n e c t i o n s n e w l i s plcd4 7 1 1& ;c o m m u n i c a t ev i aU i xl o c a ld o m a i ns o c k e t n e w l i s pc/ t m p / m y s o c k e t

Insteadof4 7 1 1 ,anyotherportnumbercanbeused.Multiplenodescanbestartedondifferenthostsandwiththesameordifferent portnumbers.Thel orL loggingoptionscanbespecifiedtologconnectionsandremotecommands. Thed daemonmodeallowsnewLISPtomaintainstatebetweenconnections.Whenkeepingstatebetweenconnectionsisnot desired,theinetddaemonmodeoffersmoreadvantages.TheInterneti n e t d orx i n e t d servicesdaemonwillstartanewnewLISP processforeachclientconnection.Thismakesformuchfasterservicingofmultipleconnections.Ind daemonmode,eachnew clientrequestwouldhavetowaitforthepreviousrequesttobefinished.Seethechapterinetddaemonmodeonhowtoconfigure thismodecorrectly. Inthefirstsyntax,n e t e v a l talkstoonlyoneremotenewLISPservernode,sendingthehostinstrhostonportintportarequestto evaluatetheexpressionexp.Ifinttimeoutisnotgiven,n e t e v a l willwaitupto60secondsforaresponseafteraconnectionis made.Otherwise,ifthetimeoutinmillisecondshasexpired,n i l isreturnedelse,theevaluationresultofexpisreturned.
;t h ec o d et ob ee v a l u a t e di sg i v e ni naq u o t e de x p r e s s i o n ( n e t e v a l" 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 1' ( +34 ) ) 7 ;e x p r e s s i o na sas t r i n g ( n e t e v a l" 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 1" ( +34 ) " ) ;w i t ht i m e o u t ( n e t e v a l" 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 1' ( +34 )1 ) ( n e t e r r o r ) 7 n i l ;t i m e o u tt os h o r t ( 1 7" E R R :O p e r a t i o nt i m e do u t " )

( n e t e v a l" 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 1' ( +34 )1 0 0 0 ) 7 ;p r o g r a mc o n t a i n e di nav a r i a b l e ( s e t' p r o g' ( +34 ) ) ( n e t e v a l" 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 1p r o g )

;s p e c i f yal o c a l d o m a i nU n i xs o c k e t( n o ta v a i l a b l eo nW i n 3 2 ) ( n e t e v a l" / t m p / m y s o c k e t "0' ( +34 ) ) 7

Thesecondsyntaxofn e t e v a l returnsalistoftheresultsafteralloftheresponsesarecollectedortimeoutoccurs.Responsesthat timeoutreturnn i l .ThelastexamplelineshowshowtospecifyalocaldomainUnixsocketspecifyingthesocketpathandaport numberof0 .Connectionerrorsorerrorsthatoccurwhensendinginformationtonodesarereturnedasalistoferrornumbersand descriptiveerrorstrings.Seethefunctionneterrorforalistofpotentialerrormessages.

;t w od i f f e r e n tr e m o t en o d e sd i f f e r e n tI P s ( n e t e v a l' ( ( " 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 1' ( +34 ) ) ( " 1 9 2 . 1 6 8 . 1 . 9 5 "4 7 1 1' ( +56 ) ) )5 0 0 0 ) ( 71 1 ) ;t w op e r s i s t e n tn o d e so nt h es a m eC P Ud i f f e r e n tp o r t s ( n e t e v a l' ( ( " l o c a l h o s t "8 0 8 1' ( f o o" a b c " ) ) ( " l o c a l h o s t "8 0 8 2' ( m y f u n c1 2 3 ) ' ) )3 0 0 0 ) ;i n e t do rx i n e t dn o d e so nt h es a m es e r v e ra n dp o r t ;n o d e sa r el o a d e do nd e m a n d ( n e t e v a l' ( ( " l o c a l h o s t "2 0 0 0' ( f o o" a b c " ) ) ( " l o c a l h o s t "2 0 0 0' ( m y f u n c1 2 3 ) ) )3 0 0 0 )

Thefirstexampleshowstwoexpressionsevaluatedontwodifferentremotenodes.Inthesecondexample,bothnodesrunonthe localcomputer.ThismaybeusefulwhendebuggingortakingadvantageofmultipleCPUsonthesamecomputer.Whenspecifying 0 fortheportnumber,n e t e v a l takesthehostnameasthefilepathtothelocaldomainUnixsocket. Notethatdefinitionsoff o o andm y f u n c mustbothexistinthetargetenvironment.Thiscanbedoneusingan e t e v a l sending d e f i n e statementsbefore.Italsocanbedonebypreloadingcodewhenstartingremotenodes. Whennodesareinetdorxinetdcontrolled,severalnodesmayhavethesameIPaddressandportnumber.Inthiscase,theUnix daemoninetdorxinetdwillstartmultiplenewLISPserversondemand.Thisisusefulwhentestingdistributedprogramsonjustone machine.Thelastexampleillustratesthiscase.ItisalsousefulonmulticoreCPUs,wheretheplatformOScandistributedifferent processesontodifferentCPUcores. Thesourcesentforevaluationcanconsistofentiremultilineprograms.Thisway,remotenodescanbeloadedwithprogramsfirst, thenspecificfunctionscanbecalled.Forlargeprogramfiles,thefunctionsputurlorsave(withaURLfilename)canbeusedto transferprograms.Thean e t e v a l statementcouldloadtheseprograms. Optionally,ahandlerfunctioncanbespecified.Thisfunctionwillberepeatedlycalledwhilewaitingandonceforeveryremote evaluationcompletion.
( d e f i n e( m y h a n d l e rp a r a m ) ( i fp a r a m ( p r i n t l np a r a m ) ) ) ( s e t' N o d e s' ( ( " 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 1 ) ( " 1 9 2 . 1 6 8 . 1 . 9 5 "4 7 1 1 ) ) ) ( s e t' P r o g s' ( ( +34 ) ( +56 ) ) ) ( n e t e v a l( m a p( f n( np )( l i s t( n0 )( n1 )p ) )N o d e sP r o g s )5 0 0 0m y h a n d l e r ) ( " 1 9 2 . 1 6 8 . 1 . 9 4 "4 7 1 17 ) ( " 1 9 2 . 1 6 8 . 1 . 9 5 "4 7 1 11 1 )

Theexampleshowshowthelistofnodespecscanbeassembledfromalistofnodesandsourcestoevaluate.Thismaybeuseful whenconnectingtoalargernumberofremotenodes.
( n e t e v a l( l i s t ( l i s t( N o d e s00 )( N o d e s01 )( P r o g s0 ) ) ( l i s t( N o d e s10 )( N o d e s11 )( P r o g s1 ) ) )3 0 0 0m y h a n d l e r )

Whilewaitingforinputfromremotehosts,m y h a n d l e r willbecalledwithn i l astheargumenttop a r a m .Whenaremotenoderesult

iscompletelyreceived,m y h a n d l e r willbecalledwithp a r a m settoalistcontainingtheremotehostnameorIPnumber,theport, andtheresultingexpression.n e t e v a l willreturnt r u e beforeatimeoutorn i l ifthetimeoutwasreachedorexceeded.Allremote hoststhatexceededthetimeoutlimitwillcontainan i l intheirresultslist. Foralongerexampleseethisprogram:mapreduce.Theexampleshowshowawordcountingtaskgetsdistributedtothreeremote nodes.Thethreenodescountwordsindifferenttextsandthemasternodereceivesandconsolidatestheresults.

netinterface
syntax:(netinterfacestripaddr) syntax:(netinterface) Setsthedefaultlocalinterfaceaddresstobeusedfornetworkconnections.Ifnotsetthennetworkfunctionswilldefaulttoan internaldefaultaddress,exceptwhenoverwrittenbyanoptionalinterfaceaddressgiveninnetlisten. Whennostripaddrisspecified,thecurrentdefaultisreturned.Ifthen e t i n t e r f a c e hasnotbeenusedyettospecifyanIP address,theaddress0 . 0 . 0 . 0 isreturned.Thismeansthatallnetworkroutineswillusethedefaultaddresspreconfiguredbythe underlyingoperatingsystem. Thisfunctionhasonlyusageonmultihomedserverswitheithermultiplenetworkinterfacehardwareorotherwisesuppliedmultiple IPnumbers.Onallothermachinesnetworkfunctionswillautomaticallyselectthesinglenetworkinterfaceinstalled. Onerrorthefunctionreturnsn i l andneterrorcanbeusedtoreporttheerror.
( n e t i n t e r f a c e" 1 9 2 . 1 6 8 . 1 . 9 5 " ) " 1 9 2 . 1 6 8 . 1 . 9 5 " ( n e t i n t e r f a c e" l o c a l h o s t " ) " 1 2 7 . 0 . 0 . 1 "

AninterfaceaddresscanbedefinedaseitheranIPaddressoraname.Thereturnvalueistheaddressgiveninstripaddr

netipv
syntax:(netipvintversion) syntax:(netipv) SwitchesbetweenIPv4andIPv6internetprotocolversions.intversioncontainseithera4forIPv4ora6forIPv6.Whenno parameterisgiven,n e t i p v returnsthecurrentsetting.
( n e t i p v ) ( n e t i p v6 ) 4 6

BydefaultnewLISPstartsupinIPv4mode.TheIPv6protocolmodecanalsobespecifiedfromthecommandlinewhenstarting newlisp:
n e w l i s p6

Onceasocketisconnectedwitheithernetconnectorlistenedonwithnetlisten,thenetaccept,netselect,netsend,netreceiveand netreceivefromfunctionsautomaticallyadjusttotheaddressprotocolusedwhencreatingthesockets.Differentconnectionswith differentIPv4/6settingscanbeopenatthesametime. Note,thatcurrentlynetpacketdoesnotsupportIPv6andwillworkinIPv4moderegardlessofsettings.

netlisten
syntax:(netlistenintport[stripaddr[strmode]]) syntax:(netlistenstrfilepath) Listensonaportspecifiedinintport.Acallton e t l i s t e n returnsimmediatelywithasocketnumber,whichisthenusedbythe blockingnetacceptfunctiontowaitforaconnection.Assoonasaconnectionisaccepted,netacceptreturnsasocketnumberthat canbeusedtocommunicatewiththeconnectingclient.
( s e t' p o r t1 2 3 4 ) ( s e t' l i s t e n( n e t l i s t e np o r t ) ) ( u n l e s sl i s t e n( b e g i n ( p r i n t" l i s t e n i n gf a i l e d \ n " ) ( e x i t ) ) ) ( p r i n t" W a i t i n gf o rc o n n e c t i o no n :"p o r t" \ n " ) ( s e t' c o n n e c t i o n( n e t a c c e p tl i s t e n ) ) ( i fc o n n e c t i o n ( w h i l e( n e t r e c e i v ec o n n e c t i o nb u f f1 0 2 4" \ n " ) ( p r i n tb u f f ) ( i f( =b u f f" \ r \ n " )( e x i t ) ) ) ( p r i n t" C o u l dn o tc o n n e c t \ n " ) )

Theexamplewaitsforaconnectiononport1234,thenreadsincominglinesuntilanemptylineisreceived.Notethatlisteningon portslowerthan1024mayrequiresuperuseraccessonUnixsystems. Oncomputerswithmorethanoneinterfacecard,specifyinganoptionalinterfaceIPaddressornameinstripaddrdirectsn e t l i s t e n tolistenonthespecifiedaddress.


; ;l i s t e no nas p e c i f i ca d d r e s s ( n e t l i s t e np o r t" 1 9 2 . 1 6 8 . 1 . 5 4 " )

LocaldomainUnixsockets
Inthesecondsyntax,n e t l i s t e n listensforaclientonthelocalfilesystemviaalocaldomainUnixsocketnamedusingstrfile path.Ifsuccessful,returnsasockethandlethatcanbeusedwithnetaccepttoacceptaclientconnectionotherwise,returnsn i l .
( n e t l i s t e n" / t m p / m y s o c k e t " ) 5 ;o nO S / 2u s e" \ \ s o c k e t \ \ "p r e f i x ( n e t l i s t e n" \ \ s o c k e t \ \ m y s o c k e t " ) ( n e t a c c e p t5 )

Alocaldomainfilesystemsocketiscreatedandlistenedon.Aclientwilltrytoconnectusingthesamestrfilepath.Aftera connectionhasbeenacceptedthefunctionsnetselect,netsendandnetreceivecanbeusedasusualforTCP/IPstream communications.Thistypeofconnectioncanbeusedasafastbidirectionalcommunicationschannelbetweenprocessesonthe samefilesystem.ThistypeofconnectionisnotavailableonWin32platforms.

UDPcommunications
Asathirdparameter,theoptionalstring" u d p " or" u " canbespecifiedinstrmodetocreateasocketsuitedforUDP(User DatagramProtocol)communications.Asocketcreatedinthiswaycanbeuseddirectlywithnetreceivefromtoawaitincoming UDPdatawithoutusingn e t a c c e p t ,whichisonlyusedinTCPcommunications.Thenetreceivefromcallwillblockuntila UDPdatapacketisreceived.Alternatively,netselectornetpeekcanbeusedtocheckforreadydatainanonblockingfashion.To senddatabacktotheaddressandportreceivedwithnetreceivefrom,usenetsendto. Notethatnetpeerwillnotwork,asUDPcommunicationsdonotmaintainaconnectedsocketwithaddressinformation.
( n e t l i s t e n1 0 0 0 2" 1 9 2 . 1 6 8 . 1 . 1 2 0 "" u d p " )

( n e t l i s t e n1 0 0 0 2" "" u d p " )

Thefirstexamplelistensonaspecificnetworkadapter,whilethesecondexamplelistensonthedefaultadapter.Bothcallsreturna socketnumberthatcanbeusedinsubsequentnetreceive,netreceivefrom,netsendto,netselect,ornetpeekfunctioncalls. BothaUDPserverandUDPclientcanbesetupusingn e t l i s t e n withthe" u d p " option.Inthismode,n e t l i s t e n doesnot reallylistenasinTCP/IPcommunicationsitjustbindsthesockettothelocalinterfaceaddressandport. Foraworkingexample,seethefilese x a m p l e s / c l i e n t ande x a m p l e s / s e r v e r inthenewLISPsourcedistribution. Insteadofn e t l i s t e n andthe" u d p " option,thefunctionsnetreceiveudpandnetsendudpcanbeusedforshorttransactions consistingonlyofonedatapacket.
n e t l i s t e n ,netselect,andnetpeekcanbeusedtofacilitatenonblockingreading.Thelistening/readingsocketisnotclosedbutis

usedagainforsubsequentreads.Incontrast,whenthenetreceiveudpandnetsendudppairisused,bothsidesclosethesockets aftersendingandreceiving.

UDPmulticastcommunications
Iftheoptionalstringstrmodeisspecifiedas" m u l t i " or" m " ,n e t l i s t e n returnsasocketsuitableformulticasting.Inthiscase, stripaddrcontainsoneofthemulticastaddressesintherange2 2 4 . 0 . 0 . 0 to2 3 9 . 2 5 5 . 2 5 5 . 2 5 5 .n e t l i s t e n willregisterstrip addrasanaddressonwhichtoreceivemulticasttransmissions.ThisaddressshouldnotbeconfusedwiththeIPaddressofthe serverhost.
; ;e x a m p l ec l i e n t ( n e t c o n n e c t" 2 2 6 . 0 . 0 . 1 "4 0 9 6" m u l t i " ) 3 ( n e t s e n d t o" 2 2 6 . 0 . 0 . 1 "4 0 9 6" h e l l o "3 ) ; ;e x a m p l es e r v e r ( n e t l i s t e n4 0 9 6" 2 2 6 . 0 . 0 . 1 "" m u l t i " ) 5 ( n e t r e c e i v e f r o m52 0 ) ( " h e l l o "" 1 9 2 . 1 6 8 . 1 . 9 4 "3 2 7 6 9 )

Ontheserverside,netpeekornetselectcanbeusedfornonblockingcommunications.Intheexampleabove,theserverwould blockuntiladatagramisreceived. Thenetsendandnetreceivefunctionscanbeusedinsteadofnetsendtoandnetreceivefrom.

Packetdivertsocketsandports
Ifstrmodeisspecifiedas" d i v e r t " ,adivertsocketcanbecreatedforadivertportinintportonBSDlikeplatforms.Thecontent ofIPaddressinstripaddrisignoredandcanbespecifiedasanemptystring.Onlytheintportisrelevantandwillbeboundtothe rawsocketreturned. Tousethedivertoptioninn e t l i s t e n ,newLISPmustruninsuperusermode.ThisoptionisonlyavailableonUnixlike platforms. Thedivertsocketwillreceiveallrawpacketsdivertedtothedivertport.Packetsmayalsobewrittenbacktoadivertsocket,in whichcasetheyreenterOSkernelIPpacketprocessing. RulesforpacketdiversiontothedivertportmustbedefinedusingeithertheipfwBSDoripchainsLinuxconfigurationutilities. Thenetreceivefromandnetsendtofunctionsareusedtoreadandwriterawpacketsonthedivertsocketcreatedandreturnedby then e t l i s t e n statement.Thesameaddressreceivedbynetreceivefromisusedinthenetsendtocallwhenreinjectingthe packet:
;r u l e sh a v eb e e np r e v i o u s l yc o n f i g u r e df o rad i v e r tp o r t

( s e t' d i v e r t S o c k e t( n e t l i s t e nd i v e r t P o r t" "" d i v e r t " ) ) ( u n t i l( n e t e r r o r ) ( s e t' r l i s t( n e t r e c e i v e f r o md i v e r t S o c k e tm a x B y t e s ) ) ( s e t' b u f f e r( r l i s t1 ) ) ;b u f f e rc a nb ep r o c e s s e dh e r eb e f o r er e i n j e c t i n g ( n e t s e n d t o( r l i s t0 )d i v e r t P o r tb u f f e rd i v e r t S o c k e t ) )

FormoreinformationseetheUnixmanpagesfordivertandtheipfw(BSDs)oripchains(Linux)configurationutilities.

netlocal
syntax:(netlocalintsocket) ReturnstheIPnumberandportofthelocalcomputerforaconnectiononaspecificintsocket.
( n e t l o c a l1 6 ) ( " 2 0 4 . 1 7 9 . 1 3 1 . 7 3 "1 6 8 9 )

Usethenetpeerfunctiontoaccesstheremotecomputer'sIPnumberandport.

netlookup
syntax:(netlookupstripnumber) syntax:(netlookupstrhostname[bool]) ReturnseitherahostnamestringfromstripnumberinIPdotformatortheIPnumberindotformatfromstrhostname:
( n e t l o o k u p" 2 0 9 . 2 4 . 1 2 0 . 2 2 4 " ) " w w w . n u e v a t e c . c o m " ( n e t l o o k u p" w w w . n u e v a t e c . c o m " ) " 2 0 9 . 2 4 . 1 2 0 . 2 2 4 " ( n e t l o o k u p" 2 1 6 . 1 6 . 8 4 . 6 6 . s b l x b l . s p a m h a u s . o r g "t r u e ) " 2 1 6 . 1 6 . 8 4 . 6 6 "

Optionally,aboolflagcanbespecifiedinthesecondsyntax.Iftheexpressioninboolevaluatestoanythingotherthann i l ,hostby namelookupwillbeforced,evenifthenamestringstartswithanIPnumber.

netpacket
syntax:(netpacketstrpacket) Thefunctionallowscustomconfigurednetworkpacketstobesentviaarawsocketsinterface.Thepacketinstrpacketmuststart withanIP(InternetProtocol)headerfollowedbyeitheraTCP,UDPorICMPheaderandoptionaldata.newLISPmustberunwith superuserprivileges,andthisfunctionisonlyavailableonMacOSX,LinuxandotherUnixoperatingsystemsandonlyforIPv4. Currentlyn e t p a c k e t isIPv4onlyandhasbeentestedonMacOSX,LinuxandOpenBSD. Onsuccessthefunctionreturnsthenumberofbytessent.Onfailurethefunctionreturnsn i l andboth,neterrorandsyserror, shouldbeinspected. Whencustomconfiguredpacketscontainzerosinthechecksumfields,n e t p a c k e t willcalculateandinsertthecorrectchecksums. Alreadyexistingchecksumsstayuntouched.

ThefollowingexampleinjectsaUDPpacketforIPnumber1 9 2 . 1 6 8 . 1 . 9 2 .TheIPheaderconsistsof20bytesendingwiththe targetIPnumber.ThefollowingUDPheaderhasalengthof8bytesandisfollowedbythedatastringH e l l oW o r l d .The checksumbytesinbothheadersareleftas0 x 0 00 x 0 0 andwillberecalculatedinternally.


;p a c k e ta sg e n e r a t e db y :( n e t s e n d u d p" 1 9 2 . 1 6 8 . 1 . 9 2 "1 2 3 4 5" H e l l oW o r l d " ) ( s e t' u d p p a c k e t( p a c k( d u p" b "3 9 )' ( 0 x 4 50 x 0 00 x 0 00 x 2 70 x 4 b0 x 8 f0 x 0 00 x 0 00 x 4 00 x 1 10 x 0 00 x 0 01 9 2 1 6 8 1 9 5 1 9 2 1 6 8 1 9 2 0 x f 20 x c 80 x 3 00 x 3 90 x 0 00 x 1 30 x 0 00 x 0 00 x 4 80 x 6 50 x 6 c0 x 6 c 0 x 6 f0 x 2 00 x 5 70 x 6 f0 x 7 20 x 6 c0 x 6 4 ) ) ) ( u n l e s s( n e t p a c k e tu d p p a c k e t ) ( p r i n t l n" n e t e r r o r :"( n e t e r r o r ) ) ( p r i n t l n" s y s e r r o r :"( s y s e r r o r ) ) )

Then e t p a c k e t functionisusedwhentestingnetsecurity.Itswrongapplicationcanupsetthecorrectfunctioningofnetwork routersandotherdevicesconnectedtoanetwork.Forthisreasonthefunctionshouldonlybeusedonwellisolated,privateintra netsandonlybynetworkprofessionals. Forotherexamplesofpacketconfiguration,seethefileq a s p e c i f i c t e s t s / q a p a c k e t inthenewLISPsourcedistribution.

netpeek
syntax:(netpeekintsocket) Returnsthenumberofbytesreadyforreadingonthenetworksocketintsocket.Ifanerroroccursortheconnectionisclosed,n i l is returned.
( s e t' a S o c k( n e t c o n n e c t" a s e r v e r . c o m "1 2 3 ) ) ( w h i l e(=( n e t p e e ka S o c k )0 ) ( d o s o m e t h i n g e l s e ) ) ( n e t r e c e i v ea S o c kb u f f1 0 2 4 )

Afterconnecting,theprogramwaitsinawhileloopuntila S o c k canberead. Usethepeekfunctiontocheckfiledescriptorsands t d i n .

netpeer
syntax:(netpeerintsocket) ReturnstheIPnumberandportnumberoftheremotecomputerforaconnectiononintsocket.
( n e t p e e r1 6 ) ( " 1 9 2 . 1 0 0 . 8 1 . 1 0 0 "1 3 )

Usethenetlocalfunctiontoaccessthelocalcomputer'sIPnumberandportnumber.

netping
syntax:(netpingstraddress[inttimeout[intcountbool]]])

syntax:(netpinglistaddresses[inttimeout[intcountbool]]]) ThisfunctionisonlyavailableonUnixbasedsystemsandmustberuninsuperusermode,i.e.using:s u d on e w l i s p tostart newLISPonMacOSXorotherBSD's,orastherootuseronLinux.Broadcastmodeandspecifyingrangeswiththe(hyphen)or *(star)arenotavailableonIPv6addressmode. SuperusermodeisnotrequiredonMacOSX. Inthefirstsyntax,n e t p i n g sendsapingICMP64byteechorequesttotheaddressspecifiedinstraddress.Ifitisabroadcast address,theICMPpacketwillbereceivedbyalladdressesonthesubnet.Notethatforsecurityreasons,manycomputersdonot answerICMPbroadcastping(ICMP_ECHO)requests.Anoptionaltimeoutparametercanbespecifiedininttimeout.Ifnotimeout isspecified,awaitingtimeof1000milliseconds(onesecond)isassumed.
n e t p i n g returnseitheralistoflistsofIPstringsandroundtriptimeinmicrosecondsforwhicharesponsewasreceivedoran

emptylistifnoresponsewasreceived. Areturnvalueofn i l indicatesafailure.Usetheneterrorfunctiontoretrievetheerrormessage.IfthemessagereadsC a n n o to p e n s o c k e t ,itisprobablybecausenewLISPisrunningwithoutrootpermissions.newLISPcanbestartedusing:


s u d on e w l i s p

Alternatively,newLISPcanbeinstalledwiththesetuserIDbitsettoruninsuperusermode.
( n e t p i n g" n e w l i s p . o r g " ) ( ( " 6 6 . 2 3 5 . 2 0 9 . 7 2 "6 3 4 0 8 0 ) ) ( n e t p i n g" 1 2 7 . 0 . 0 . 1 " ) ( ( " 1 2 7 . 0 . 0 . 1 "1 1 5 ) ) ( n e t p i n g" y a h o o . c o m "3 0 0 0 ) n i l

Inthesecondsyntax,n e t p i n g isruninbatchmode.Onlyonesocketisopenedinthismode,butmultipleICMPpacketsaresent outoneeachtomultipleaddressesspecifiedinalistorspecifiedbyrange.Packetsaresentoutasfastaspossible.Inthiscase, multipleanswerscanbereceived.Ifthesameaddressisspecifiedmultipletimes,thereceivingIPaddresswillbefloodedwith ICMPpackets. Tolimitthenumberofresponsestobewaitedforinbroadcastorbatchmode,anadditionalargumentindicatingthemaximum numberofresponsestoreceivecanbespecifiedinintcount.Usageofthisparametercancausethefunctiontoreturnsoonerthan thespecifiedtimeout.Whenagivennumberofresponseshasbeenreceived,n e t p i n g willreturnbeforethetimeouthasoccurred. Notspecifyingintcountorspecifying0 assumesanintcountequaltothenumberofpacketssentout. Asthirdoptionalparameter,at r u e valuecanbespecified.Thissettingwillreturnanerrorstringinsteadoftheresponsetime,ifthe hostdoesnotanswer.
( n e t p i n g' ( " n e w l i s p . o r g "" 1 9 2 . 1 6 8 . 1 . 2 5 5 " )2 0 0 02 0 ) ( ( " 6 6 . 2 3 5 . 2 0 9 . 7 2 "8 2 6 4 2 0 )( " 1 9 2 . 1 6 8 . 1 . 1 "1 2 4 )( " 1 9 2 . 1 6 8 . 1 . 2 5 4 "2 1 0 ) ) ( n e t p i n g" 1 9 2 . 1 6 8 . 1 . * "5 0 0 );f r o m1t o2 5 4 ( ( " 1 9 2 . 1 6 8 . 1 . 1 "1 2 0 )( " 1 9 2 . 1 6 8 . 1 . 2 "2 4 5 )( " 1 9 2 . 1 6 8 . 2 . 3 "1 8 0 )( " 1 9 2 . 1 6 8 . 2 . 2 5 4 "2 3 4 ) ) ( n e t p i n g" 1 9 2 . 1 6 8 . 1 . * "5 0 02 );r e t u r n sa f t e r2r e s p o n s e s ( ( " 1 9 2 . 1 6 8 . 1 . 3 "1 1 5 )( " 1 9 2 . 1 6 8 . 1 . 1 "1 4 5 ) ) ( n e t p i n g" 1 9 2 . 1 6 8 . 1 . 1 1 0 "1 0 0 0 );r e t u r n sa f t e r1s e c o n d ( ( " 1 9 2 . 1 6 8 . 1 . 3 "1 9 6 )( " 1 9 2 . 1 6 8 . 1 . 1 "2 0 5 ) ) ( n e t p i n g' ( " 1 9 2 . 1 6 8 . 1 . 1 0 0 1 2 0 "" 1 9 2 . 1 6 8 . 1 . 1 2 4 1 3 2 " )2 0 0 0 );r e t u r n sa f t e r2s e c o n d s ( )

BroadcastorbatchmodeaswellasnormaladdressesandIPnumbersorhostnamescanbemixedinonen e t p i n g statement byputtingalloftheIPspecsintoalist. Thesecondandthirdlinesshowhowthebatchmodeofn e t p i n g canbeinitiatedbyspecifyingthe* (asterisk)asawildcard characterforthelastsubnetoctetintheIPnumber.ThefourthandfifthlinesshowhowanIPrangecanbespecifiedforthelast subnetoctetintheIPnumber.n e t p i n g williteratethroughallnumbersfromeither1to254forthestar* ortherangespecified, sendinganICMPpackettoeachaddress.NotethatthisisdifferentfromthebroadcastmodespecifiedwithanIPoctetof2 5 5 . Whileinbroadcastmode,n e t p i n g sendsoutonlyonepacket,whichisreceivedbymultipleaddresses.Batchmodeexplicitly

generatesmultiplepackets,oneforeachtargetaddress.Whenspecifyingbroadcastmode,intcountshouldbespecified,too. WhensendinglargerlistsofIPsinbatchmodeoveronesocket,alongertimeoutmaybenecessarytoallowenoughtimeforallof thepacketstobesentoutoveronesocket.Ifthetimeoutistooshort,thefunctionn e t p i n g mayreturnanincompletelistorthe emptylist( ) .Inthiscase,neterrorwillreturnatimeouterror.Onerror,n i l isreturnedandneterrorcanbeusedtoretrievean errormessage. Onsomesystemsonlylistsuptoaspecificlengthcanbehandledregardlessofthetimeoutspecified.Inthiscase,therangeshould bebrokenupintosubrangesandusedwithmultiplen e t p i n g invocations.Inanycase,n e t p i n g willsendoutpackagesas quicklyaspossible.

netreceive!
syntax:(netreceiveintsocketsymbufferintmaxbytes[waitstring]) Receivesdataonthesocketintsocketintoastringcontainedinsymbuffer.symbuffercanalsobeadefaultfunctorspecifiedbya contextsymbolforreferencepassinginandoutofuserdefinedfunctions. Amaximumofintmaxbytesisreceived.n e t r e c e i v e returnsthenumberofbytesread.Ifthereisabreakintheconnection,n i l isreturned.Thespacereservedinsymbufferisexactlythesizeofbytesread. Notethatn e t r e c e i v e isablockingcallanddoesnotreturnuntilthedataarrivesatintsocket.Usenetpeekornetselecttofind outifasocketisreadyforreading. Optionally,awaitstringcanbespecifiedasafourthparameter.n e t r e c e i v e thenreturnsafteracharacterorstringofcharacters matchingwaitstringisreceived.Thewaitstringwillbepartofthedatacontainedinsymbuffer.
( d e f i n e( g e t t i m e ) ( s e t' s o c k e t( n e t c o n n e c t" n e t c o m . c o m "1 3 ) ) ( n e t r e c e i v es o c k e tb u f2 5 6 ) ( p r i n tb u f" \ n " ) ( n e t c l o s es o c k e t ) )

Whencallingg e t t i m e ,theprogramconnectstoport13oftheservernetcom.com.Port13isadatetimeserviceonmostserver installations.Uponconnection,theserversendsastringcontainingthedateandtimeofday.


( d e f i n e( n e t r e c e i v e l i n es o c k e ts B u f f ) ( n e t r e c e i v es o c k e ts B u f f2 5 6" \ n " ) ) ( s e t' b y t e s R e c e i v e d( n e t r e c e i v e l i n es o c k e t' s m ) )

Thesecondexampledefinesanewfunctionn e t r e c e i v e l i n e ,whichreturnsafterreceivinganewlinecharacter(astring containingonecharacterinthisexample)or256characters.The"\n"stringispartofthecontentsofsBuff. Notethatwhenthefourthparameterisspecified,n e t r e c e i v e isslowerthanthenormalversionbecauseinformationisread characterbycharacter.Inmostsituations,thespeeddifferencecanbeneglected.

netreceivefrom
syntax:(netreceivefromintsocketintmaxsize)
n e t r e c e i v e f r o m canbeusedtosetupnonblockingUDPcommunications.Thesocketinintsocketmustpreviouslyhavebeen

openedbyeithernetlistenornetconnect(bothusingthe" u d p " option).intmaxsizespecifiesthemaximumnumberofbytesthat

willbereceived.OnLinux/BSD,ifmorebytesarereceived,thosewillbediscardedonWin32,n e t r e c e i v e f r o m returnsn i l andclosesthesocket. Onsuccessn e t r e c e i v e returnsalistofthedatastring,remoteIPnumberandremoteportused.Onfailureitreturnsn i l .


; ;l i s t e no np o r t1 0 0 1o nt h ed e f a u l ta d d r e s s ( n e t l i s t e n1 0 0 1" "" u d p " ) 1 9 8 0 ; ;o p t i o n a l l yp o l lf o ra r r i v i n gd a t aw i t h1 0 0 m st i m e o u t ( w h i l e( n o t( n e t s e l e c t1 9 8 0" r "1 0 0 0 0 0 ) )( d o s o m e t h i n g. . .) ) ( n e t r e c e i v e f r o m1 9 8 02 0 ) ( " h e l l o "" 1 9 2 . 1 6 8 . 0 . 5 "3 2 4 0 ) ; ;s e n da n s w e rb a c kt os e n d e r ( n e t s e n d t o" 1 9 2 . 1 6 8 . 0 . 5 "3 2 4 0" h e l l ot oy o u "1 9 8 0 ) ( n e t c l o s e1 9 8 0 );c l o s es o c k e t

Thesecondlineinthisexampleisoptional.Withoutit,then e t r e c e i v e f r o m callwouldblockuntildataarrives.AUDPserver couldbesetupbylisteningandpollingseveralports,servingthemastheyreceivedata. Notethatn e t r e c e i v e couldnotbeusedinthiscasebecauseitdoesnotreturnthesender'saddressandportinformation,which arerequiredtotalkback.InUDPcommunications,thedatapacketitselfcontainstheaddressofthesender,notthesocketover whichcommunicationtakesplace.n e t r e c e i v e canalsobeusedforTCP/IPcommunications. Seealsothenetconnectfunctionwiththe" u d p " optionandthenetsendtofunctionforsendingUDPdatapacketsoveropen connections. ForblockingshortUDPtransactions,seethenetsendudpandnetreceiveudpfunctions.

netreceiveudp
syntax:(netreceiveudpintportintmaxsize[intmicrosec[straddrif]]) ReceivesaUserDatagramProtocol(UDP)packetonportintport,readingintmaxsizebytes.Ifmorethanintmaxsizebytesare received,bytesoverintmaxsizearediscardedonLinux/BSDonWin32,n e t r e c e i v e u d p returnsn i l .n e t r e c e i v e u d p blocksuntiladatagramarrivesortheoptionaltimeoutvalueinintmicrosecexpires.Whensettingupcommunicationsbetween datagramsenderandreceiver,then e t r e c e i v e u d p statementmustbesetupfirst. Noprevioussetupusingn e t l i s t e n orn e t c o n n e c t isnecessary.
n e t r e c e i v e u d p returnsalistcontainingastringoftheUDPpacketfollowedbyastringcontainingthesender'sIPnumberand

theportused.
; ;w a i tf o rd a t a g r a mw i t hm a x i m u m2 0b y t e s ( n e t r e c e i v e u d p1 0 0 0 12 0 ) ; ;o r ( n e t r e c e i v e u d p1 0 0 0 12 05 0 0 0 0 0 0 ) ;w a i tf o rm a x5s e c o n d s ; ;e x e c u t e do nr e m o t ec o m p u t e r ( n e t s e n d u d p" n u e v a t e c . c o m "1 0 0 1" H e l l o " ) 4 ; ;r e t u r n e df r o mt h en e t r e c e i v e u d ps t a t e m e n t ( " H e l l o "" 1 2 8 . 1 2 1 . 9 6 . 1 "3 3 1 2 ) ; ;s e n d i n gb i n a r yi n f o r m a t i o n ( n e t s e n d u d p" a h o s t . c o m "2 2 2 2( p a c k" cccc "0123 ) ) 4 ; ;e x t r a c t i n gt h er e c e i v e di n f o ( s e t' b u f f( f i r s t( n e t r e c e i v e u d p2 2 2 21 0 ) ) )

( p r i n t( u n p a c k" cccc "b u f f ) ) ( 0123 )

Seealsothenetsendudpfunctionforsendingdatagramsandthepackandunpackfunctionsforpackingandunpackingbinary information. Tolistenonaspecifiedaddressoncomputerswithmorethanoneinterfacecard,aninterfaceIPaddressornamecanbeoptionally specifiedinstraddrif.Whenspecifyingstraddrif,atimeoutmustalsobespecifiedinintwait. Asanalternative,UDPcommunicationcanbesetupusingnetlisten,ornetconnecttogetherwiththe" u d p " optiontomakenon blockingdataexchangepossiblewithnetreceivefromandnetsendto.

netselect
syntax:(netselectintsocketstrmodeintmicroseconds) syntax:(netselectlistsocketsstrmodeintmicroseconds) Inthefirstform,n e t s e l e c t findsoutaboutthestatusofonesocketspecifiedinintsocket.Dependingonstrmode,thesocketcan becheckedifitisreadyforreadingorwriting,orifthesockethasanerrorcondition.Atimeoutvalueisspecifiedinintmicro seconds. Inthesecondsyntax,n e t s e l e c t cancheckforalistofsocketsinlistsockets. Thefollowingvaluecanbegivenforstrmode:
" r e a d " or" r " tocheckifreadyforreadingoraccepting. " w r i t e " or" w " tocheckifreadyforwriting. " e x c e p t i o n " or" e " tocheckforanerrorcondition.

Read,send,oracceptoperationscanbehandledwithoutblockingbyusingthen e t s e l e c t function.n e t s e l e c t waitsfora sockettobereadyforthevaluegiveninintmicroseconds,thenreturnst r u e orn i l dependingonthereadinessofthesocket. Duringtheselectloop,otherportionsoftheprogramcanrun.Onerror,neterrorisset.When1 isspecifiedforintmicroseconds, n e t s e l e c t willnevertimeout.


( s e t' l i s t e n s o c k e t( n e t l i s t e n1 0 0 1 ) ) ; ;w a i tf o rc o n n e c t i o n ( w h i l e( n o t( n e t s e l e c tl i s t e n s o c k e t" r e a d "1 0 0 0 ) ) ( i f( n e t e r r o r )( p r i n t( n e t e r r o r ) ) ) ) ( s e t' c o n n e c t i o n( n e t a c c e p tl i s t e n s o c k e t ) ) ( n e t s e n dc o n n e c t i o n" h e l l o " ) ; ;w a i tf o ri n c o m i n gm e s s a g e ( w h i l e( n o t( n e t s e l e c tc o n n e c t i o n" r e a d "1 0 0 0 ) ) ( d o s o m e t h i n g ) ) ( n e t r e c e i v ec o n n e c t i o nb u f f1 0 2 4 )

Whenn e t s e l e c t isused,severallistenandconnectionsocketscanbewatched,andmultipleconnectionscanbehandled.When usedwithalistofsockets,n e t s e l e c t willreturnalistofreadysockets.Thefollowingexamplewouldlistenontwosocketsand continueacceptingandservicingconnections:


( s e t' l i s t e n l i s t' ( 1 0 0 11 0 0 2 ) ) ;a c c e p t c o n n e c t i o n ,r e a d c o n n e c t i o na n dw r i t e c o n n e c t i o n ;a r eu s e rd e f i n e df u n c t i o n s ( w h i l e( n o t( n e t e r r o r ) ) ( d o l i s t( c o n n( n e t s e l e c tl i s t e n l i s t" r "1 0 0 0 ) )

( a c c e p t c o n n e c t i o nc o n n ) ) ;b u i l da na c c e p t l i s t ( d o l i s t( c o n n( n e t s e l e c ta c c e p t l i s t" r "1 0 0 0 ) ) ( r e a d c o n n e c t i o nc o n n ) ) ;r e a do nc o n n e c t e ds o c k e t s ( d o l i s t( c o n n( n e t s e l e c ta c c e p t l i s t" w "1 0 0 0 ) ) ( w r i t e c o n n e c t i o nc o n n ) ) ) ;w r i t eo nc o n n e c t e ds o c k e t s

Inthesecondsyntax,alistisreturnedcontainingallthesocketsthatpassedthetestiftimeoutoccurred,anemptylistisreturned.An errorcausesneterrortobeset. Notethatsupplyinganonexistentsocketton e t s e l e c t willcauseanerrortobesetinneterror.

netsend
syntax:(netsendintsocketstrbuffer[intnumbytes]) Sendsthecontentsofstrbufferontheconnectionspecifiedbyintsocket.Ifintnumbytesisspecified,uptointnumbytesaresent. Ifintnumbytesisnotspecified,theentirecontentswillbesent.n e t s e n d returnsthenumberofbytessentorn i l onfailure. Onfailure,useneterrortogetmoreerrorinformation.
( s e t' b u f" h e l l ot h e r e " ) ( n e t s e n ds o c kb u f ) ( n e t s e n ds o c kb u f5 ) 1 1 5

( n e t s e n ds o c k" b y eb y e " )7

Thefirstn e t s e n d sendsthestring" h e l l ot h e r e " ,whilethesecondn e t s e n d sendsonlythestring" h e l l o " .

netsendto
syntax:(netsendtostrremotehostintremoteportstrbufferintsocket) CanbeusedforeitherUDPorTCP/IPcommunications.Thesocketinintsocketmusthavepreviouslybeenopenedwithanet connectornetlistenfunction.Iftheopeningfunctionswasusedwiththe" u d p " option,n e t l i s t e n orn e t c o n n e c t arenotused tolistenortoconnectbutonlytocreatetheUDPsocket.Thehostinstrremotehostcanbespecifiedeitherasahostnameorasan IPnumberstring. Whenusingn e t c o n n e c t togetherwithn e t s e n d t o ,thenonlyoneofthefunctionsshouldspecifytheremotehost.Theother shouldleavetheaddressasanemptystring.
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;U D Ps e r v e r ( s e t' s o c k e t( n e t l i s t e n1 0 0 0 1" "" u d p " ) ) ( i fs o c k e t( p r i n t l n" s e r v e rl i s t e n i n go np o r t"1 0 0 0 1 ) ( p r i n t l n( n e t e r r o r ) ) ) ( w h i l e( n o t( n e t e r r o r ) ) ( s e t' m s g( n e t r e c e i v e f r o ms o c k e t2 5 5 ) ) ( p r i n t l n" >"m s g ) ( n e t s e n d t o( n t h1m s g )( n t h2m s g ) ( u p p e r c a s e( f i r s tm s g ) )s o c k e t ) ) ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;U D Pc l i e n t ( s e t' s o c k e t( n e t l i s t e n1 0 0 0 2" "" u d p " ) ) ( i f( n o ts o c k e t )( p r i n t l n( n e t e r r o r ) ) ) ( w h i l e( n o t( n e t e r r o r ) ) ( p r i n t" >" )

( n e t s e n d t o" 1 2 7 . 0 . 0 . 1 "1 0 0 0 1( r e a d l i n e )s o c k e t ) ( n e t r e c e i v es o c k e tb u f f2 5 5 ) ( p r i n t l n" >"b u f f ) )

Intheexamplesboth,theclientandtheserverusen e t l i s t e n tocreatetheUDPsocketforsendingandreceiving.Theserver extractstheclientaddressandportfromthemessagereceivedandusesitinthen e t s e n d t o statement. Seealsothenetreceivefromfunctionandthenetlistenfunctionwiththe" u d p " option. ForblockingshortUDPtransactionsusenetsendudpandnetreceiveudp.

netsendudp
syntax:(netsendudpstrremotehostintremoteportstrbuffer[bool]) SendsaUserDatagramProtocol(UDP)tothehostspecifiedinstrremotehostandtotheportinintremoteport.Thedatasentisin strbuffer. ThetheoreticalmaximumdatasizeofaUDPpacketonanIPv4systemis64KminusIPlayeroverhead,butmuchsmalleronmost Unixflavors.8kseemstobeasafesizeonMacOSX,BSDsandLinux. Noprevioussetupusingn e t c o n n e c t orn e t l i s t e n isnecessary.n e t s e n d u d p returnsimmediatelywiththenumberofbytes sentandclosesthesocketused.Ifnon e t r e c e i v e u d p statementiswaitingatthereceivingside,thedatagramsentislost.When usingdatagramcommunicationsoverinsecureconnections,settingupasimpleprotocolbetweensenderandreceiveris recommendedforensuringdelivery.UDPcommunicationbyitselfdoesnotguaranteereliabledeliveryasTCP/IPdoes.
( n e t s e n d u d p" s o m e h o s t . c o m "3 3 3 3" H e l l o " ) 5 n e t s e n d u d p isalsosuitableforsendingbinaryinformation(e.g.,thezerocharacterorothernonvisiblebytes).Foramore

comprehensiveexample,seenetreceiveudp. Optionally,thesendingsocketcanbeputinbroadcastmodebyspecifyingt r u e oranyexpressionnotevaluatington i l inbool:


( n e t s e n d u d p" 1 9 2 . 1 6 8 . 1 . 2 5 5 "2 0 0 0" H e l l o "t r u e ) 5

TheUDPwillbesenttoallnodesonthe1 9 2 . 1 6 8 . 1 network.Notethatonsomeoperatingsystems,sendingthenetworkmask2 5 5 withouttheboolt r u e optionwillenablebroadcastmode. Asanalternative,thenetconnectfunctionusingthe" u d p " optiontogetherwiththenetsendtofunctioncanbeusedtotalktoa UDPlistenerinanonblockingfashion.

netservice
syntax:(netservicestrservicestrprotocol) syntax:(netserviceintportstrprotocol) Inthefirstsyntaxn e t s e r v i c e makesalookupintheservicesdatabaseandreturnsthestandardportnumberforthisservice. Inthesecondsyntaxaserviceportissuppliedinintporttolookuptheservicename. Returnsn i l onfailure.
;g e tt h ep o r tn u m b e rf r o mt h en a m e ( n e t s e r v i c e" f t p "" t c p " ) 2 1

( n e t s e r v i c e" h t t p "" t c p " ) 8 0 ( n e t s e r v i c e" n e t e v a l "" t c p " ) 4 7 1 1 ;i fc o n f i g u r e d ;g e tt h es e r v i c en a m ef r o mt h ep o r tn u m b e r ( n e t s e r v i c e2 2" t c p " ) " s s h "

netsessions
syntax:(netsessions) Returnsalistofactivelisteningandconnectionsockets.

new
syntax:(newcontextsourcesymcontexttarget[bool]) syntax:(newcontextsource) Thecontextcontextsourceiscopiedtosymcontexttarget.Ifthetargetcontextdoesnotexist,anewcontextwiththesamevariable namesanduserdefinedfunctionsasincontextsourceiscreated.Ifthetargetcontextalreadyexists,thennewsymbolsand definitionsareadded.Existingsymbolsareonlyoverwrittenwhentheexpressioninboolevaluatestoanythingotherthann i l otherwise,thecontentofexistingsymbolswillremain.Thismakesmixinsofcontextobjectspossible.n e w returnsthetargetcontext, whichcannotbeMAIN. Inthesecondsyntax,theexistingcontextincontextsourcegetscopiedintothecurrentcontextasthetargetcontext. Allreferencestosymbolsintheoriginatingcontextwillbetranslatedtoreferencesinthetargetcontext.Thisway,allfunctionsand datastructuresreferringtosymbolsintheoriginalcontextwillnowrefertosymbolsinthetargetcontext.
( n e wC T X' C T X 2 ) C T X 2 ; ;f o r c eo v e r w r i t eo fe x i s t i n gs y m b o l s ( n e wC T XM y C T Xt r u e ) M y C T X

ThefirstlineintheexamplecreatesanewcontextcalledC T X 2 thathastheexactsamestructureastheoriginalone.NotethatC T X isnotquotedbecausecontextsevaluatetothemselves,butCTX2mustbequotedbecauseitdoesnotexistyet. ThesecondlinemergesthecontextC T X intoM y C T X .AnyexistingsymbolsofthesamenameinM y C T X willbeoverwritten.Because M y C T X alreadyexists,thequotebeforethecontextsymbolcanbeomitted. Contextsymbolsneednotbementionedexplicitly,buttheycanbecontainedinvariables:


( s e t' f o o : x1 2 3 ) ( s e t' b a r : y9 9 9 ) ( s e t' c t x af o o ) ( s e t' c t x bb a r ) ( n e wc t x ac t x b ) ;f r o mf o ot ob a r b a r : x 1 2 3 ;xh a sb e e na d d e dt ob a r b a r : y 9 9 9 )

Theexamplereferstocontextsinvariablesandmergescontextf o o intob a r . Seealsothefunctiondefnewformovingandmergingsinglefunctionsinsteadofentirecontexts.Seethecontextfunctionfora morecomprehensiveexampleofn e w .

nil?
syntax:(nil?exp) Iftheexpressioninexpevaluateston i l ,thenn i l ? returnst r u e otherwise,itreturnsn i l .
( m a pn i l ?' ( xn i l 1n i l" h i "( ) ) ) ( n i lt r u en i lt r u en i ln i l ) ( n i l ?n i l ) t r u e ( n i l ?' ( ) ) n i l ;n i l ?m e a n ss t r i c t l yn i l ( n i l ?( n o t' ( ) ) ) n i l

Then i l ? predicateisusefulfordistinguishingbetweenn i l andtheemptylist( ) . Notethatn i l ? meansstrictlyn i l whilet r u e ? meanseverythingnotn i l ortheemptylist( ) .

normal
syntax:(normalfloatmeanfloatstdevintn) syntax:(normalfloatmeanfloatstdev) Inthefirstform,n o r m a l returnsalistoflengthintnofrandom,continuouslydistributedfloatingpointnumberswithameanof floatmeanandastandarddeviationoffloatstdev.Therandomgeneratorusedinternallycanbeseededusingtheseedfunction.
( n o r m a l1 031 0 ) ( 76 . 5 6 3 4 7 6 5 6 21 1 . 9 3 9 4 5 3 1 26 . 1 5 3 3 2 0 3 1 29 . 9 8 8 2 8 1 2 5 7 . 9 8 4 3 7 51 0 . 1 7 8 7 1 0 9 46 . 5 8 9 8 4 3 7 59 . 4 2 5 7 8 1 2 51 2 . 1 1 2 3 0 4 6 9 )

Inthesecondform,n o r m a l returnsasinglenormaldistributedfloatingpointnumber:
( n o r m a l01 ) 0 . 6 6 3 0 8 5 9 3 7 5

Seealsotherandomandrandfunctionsforevenlydistributednumbers,ambforrandomizingevaluationinalistofexpressions,and seedforsettingadifferentstartpointforpseudorandomnumbergeneration.

not
syntax:(notexp) Ifexpevaluateston i l ortheemptylist( ) ,thent r u e isreturnedotherwise,n i l isreturned.
( n o tt r u e ) ( n o tn i l ) ( n o t' ( ) ) ( n o t( <11 0 ) ) ( n o t( n o t( <11 0 ) ) ) n i l t r u e t r u e n i l t r u e

now
syntax:(now[intminutesoffset[intindex]]) Returnsinformationaboutthecurrentdateandtimeasalistofintegers.Anoptionaltimezoneoffsetcanbespecifiedinminutesin intminutesoffset.Thiscausesthetimetobeshiftedforwardorbackwardintime,beforebeingsplitintoseparatedatevalues. Anoptionallistindexinintindexmakesn o w returnaspecificmemberintheresultlist.
( n o w ) ( 2 0 0 222 71 82 13 01 4 0 0 0 05 733 0 00 ) ( n o w02 ) 3 0 0;m i n u t e sw e s to fG M T ( a p p l yd a t e v a l u e( n o w ) ) 1 0 1 4 8 3 4 0 9 0

Thenumbersrepresentthefollowingdatetimefields: format year month day hour minute second microsecond dayofcurrentyear dayofcurrentweek timezoneoffsetinminutes daylightsavingstimetype description Gregoriancalendar (112) (131) (023)UTC (059) (059) (0999999)OSspecific,millisecondresolution Jan1stis1 (17)startingMonday westofGMT (06)onLinux/UnixorbiasinminutesonWin32

ThesecondexamplereturnstheCoordinatedUniversalTime(UTC)timevalueofsecondsafterJanuary1,1970. Rangingfrom0to23,hoursaregiveninUTCandarenotadjustedforthelocaltimezone.Theresolutionofthem i c r o s e c o n d s fielddependsontheoperatingsystemandplatform.Onsomeplatforms,thelastthreedigitsofthem i c r o s e c o n d s fieldarealways0 (zero). The"dayoftheweek"fieldstartswith1onMondayconformingtotheISO8601internationalstandardfordateandtime representation. Onsomeplatforms,thedaylightsavingstimeflagisnotactiveandreturns0 (zero)evenduringdaylightsavingstime(dst). Dependingonthegeographicalarea,thedaylightsavingstimetype(dst)hasadifferentvaluefrom1to6: type 0 1 2 3 4 5 6 area notondst USAstyledst Australianstyledst WesternEuropeandst MiddleEuropeandst EasternEuropeandst Canadadst

Seealsothedate,datelist,dateparse,datevalue,time,andtimeofdayfunctions.

nper
syntax:(npernuminterestnumpmtnumpv[numfv[inttype]]) Calculatesthenumberofpaymentsrequiredtopayaloanofnumpvwithaconstantinterestrateofnuminterestandpaymentnum pmt.Ifpaymentisattheendoftheperiod,inttypeis0 (zero)orinttypeisomittedforpaymentatthebeginningofeachperiod,int typeis1.
( n p e r( d i v0 . 0 71 2 )7 7 5 . 3 01 0 0 0 0 0 ) 2 3 9 . 9 9 9 2 8 2 8

Theexamplecalculatesthenumberofmonthlypaymentsrequiredtopayaloanof$100,000atayearlyinterestrateof7percent withpaymentsof$775.30. Seealsothefv,irr,npv,pmt,andpvfunctions.

npv
syntax:(npvnuminterestlistvalues) Calculatesthenetpresentvalueofaninvestmentwithafixedinterestratenuminterestandaseriesoffuturepaymentsandincome inlistvalues.Paymentsarerepresentedbynegativevaluesinlistvalues,whileincomeisrepresentedbypositivevaluesinlist values.
( n p v0 . 1' ( 1 0 0 01 0 0 01 0 0 0 ) ) 2 4 8 6 . 8 5 1 9 9 1 ( n p v0 . 1' ( 2 4 8 6 . 8 5 1 9 9 11 0 0 01 0 0 01 0 0 0 ) ) 1 . 4 3 4 3 8 6 8 3 2 e 0 8 ;~0 . 0( z e r o )

Intheexample,aninitialinvestmentof$2,481.85wouldallowforanincomeof$1,000aftertheendofthefirst,second,andthird years. Seealsothefv,irr,nper,pmt,andpvfunctions.

nthutf8
syntax:(nthintindexlist) syntax:(nthintindexarray) syntax:(nthintindexstr) syntax:(nthlistindiceslist) syntax:(nthlistindicesarray) Inthefirstsyntaxgroupn t h usesintindexanindexintothelist,arrayorstrfoundandreturningtheelementfoundatthatindex. SeealsoIndexingelementsofstringsandlists. Multipleindicesmaybespecifiedtorecursivelyaccesselementsinnestedlistsorarrays.Iftherearemoreindicesthannesting levels,theextraindicesareignored.Whenmultipleindicesareused,theymustbeputinalistasshowninthesecondsyntaxgroup.

( s e t' L' ( abc ) ) ( n t h0L ) a ;o rs i m p l y ( L0 )a ( s e t' n a m e s' ( j o h nm a r t h ar o b e r ta l e x ) ) ( j o h nm a r t h ar o b e r ta l e x ) ( n t h2n a m e s ) ;o rs i m p l y ( n a m e s2 ) ( n a m e s1 ) r o b e r t r o b e r t a l e x

;m u l t i p l ei n d i c e s ( s e t' p e r s o n s' ( ( j o h n3 0 )( m a r t h a1 2 0 )( ( j o h nd o e )1 7 ) ) ) ( p e r s o n s11 ) 1 2 0

( n t h' ( 201 )p e r s o n s ) d o e ;o rs i m p l y ( p e r s o n s201 ) d o e

;m u l t i p l ei n d i c e si nav e c t o r ( s e t' v' ( 201 ) ) ( p e r s o n sv ) d o e ( n t hvp e r s o n s ) d o e ;n e g a t i v ei n d i c e s ( p e r s o n s20 ) m a r t h a ;o u t o f b o u n d si n d i c e sc a u s ee r r o r ( p e r s o n s1 0 ) E R R :l i s ti n d e xo u to fb o u n d s ( p e r s o n5 ) E R R :l i s ti n d e xo u to fb o u n d s

ThelistL canbethecontextofthedefaultfunctorL : L .Thisallowslistspassedbyreference:


( s e t' L : L' ( abcdefg ) ) ( d e f i n e( s e c o n dc t x ) ( n t h1c t x ) ) ( r e v e r s eL )( gfedcba ) L : L( gfedcba ) ; ;p a s s i n gt h el i s ti nL : Lb yr e f e r e n c e ( s e c o n dL ) b ; ;p a s s i n gt h el i s ti nL : Lb yv a l u e ( s e c o n dL : L )b

Referencepassingisfasteranduseslessmemoryinbiglistsandshouldbeusedonlistswithmorethanafewhundreditems. Notethattheimplicitindexingversionofn t h isnotbreakingnewLISPsyntaxrulesbutshouldbeunderstoodasalogicalexpansion ofnewLISPsyntaxrulestootherdatatypesthanbuiltinfunctionsorlambdaexpressions.Alistinthefunctorpositionofans expressionassumesselfindexingfunctionalityusingtheindexargumentsfollowing. Theimplicitindexedsyntaxformsarefasterbuttheotherformwithanexplicitn t h maybemorereadableinsomesituations.


n t h worksonarraysjustlikeitdoesonlists: ( s e t' a A r r a y( a r r a y23' ( abcdef ) ) ) ( ( abc )( def ) ) ( n t h1a A r r a y ) ( def ) ( a A r r a y1 ) ( def ) ( n t h' ( 10 )a A r r a y ) ( a A r r a y10 ) ( a A r r a y' ( 10 ) ) d d d

( s e t' v e c' ( 10 ) ) ( a A r r a yv e c )

IntheStringversion,n t h returnsthecharacterfoundatthepositionintindexinstrandreturnsitasastring.
( n t h 0" n e w L I S P " ) ( " n e w L I S P "0 ) ( " n e w L I S P "1 ) " n " " n " " P "

NotethatnthworksoncharacterboundariesratherthanbyteboundarieswhenusingtheUTF8enabledversionofnewLISP.To accessASCIIandbinarystringbuffersonsinglebyteboundariesuseslice. Seealsosetfformodifyingmultidimensionallistsandarraysandpushandpopformodifyinglists.

null?
syntax:(null?exp) Checksifanexpressionevaluateston i l ,theemptylist( ) ,theemptystring" " ,N a N (notanumber),or0 (zero),inwhichcaseit returnst r u e .Inallothercases,n u l l ? returnsn i l .Thepredicaten u l l ? isusefulinconjunctionwiththefunctionsfilterorcleanto checktheoutcomeofothernewLISPoperations.
( s e t' x( s q r t1 ) )N a N;o rn a no nU N I X ( n u l l ?x )t r u e ( m a pn u l l ?' ( 100 . 02" h e l l o "" "( abc )( )t r u e ) ) ( n i lt r u et r u en i ln i lt r u en i lt r u en i l ) ( f i l t e rn u l l ?' ( 1020 . 0" h e l l o "" "( abc )( )n i lt r u e ) ) ( 00" "( )n i l ) ( c l e a nn u l l ?' ( 1020 . 0" h e l l o "" "( abc )( )n i lt r u e ) ) ( 12" h e l l o "( abc )t r u e )

Seealsothepredicatesempty?,nil?andzero?.

number?
syntax:(number?exp)
t r u e isreturnedonlyifexpevaluatestoafloatingpointnumberoranintegerotherwise,n i l isreturned. ( s e t' x1 . 2 3 ) ( s e t' y4 5 6 ) ( n u m b e r ?x ) t r u e ( n u m b e r ?y ) t r u e ( n u m b e r ?" 6 7 8 " ) n i l

Seethefunctionsfloat?andinteger?totestforaspecificnumbertype.

odd?

syntax:(odd?intnumber) Checkstheparityofanintegernumber.Ifthenumberisnotevendivisibleby2 ,ithasoddparity.Whenafloatingpointnumberis passedforintnumber,itwillbeconvertedfirsttoanintegerbycuttingoffitsfractionalpart.


( o d d ?1 2 3 ) t r u e ( o d d ?8 ) n i l ( o d d ?8 . 7 ) n i l

Useeven?tocheckifanintegeriseven,divisibleby2 .

open
syntax:(openstrpathfilestraccessmode[stroption]) Thestrpathfileisafilename,andstraccessmodeisastringspecifyingthefileaccessmode.o p e n returnsaninteger,whichisa filehandletobeusedonsubsequentreadorwriteoperationsonthefile.Onfailure,o p e n returnsn i l .Theaccessmode" w r i t e " createsthefileifitdoesn'texist,orittruncatesanexistingfileto0 (zero)bytesinlength. Thefollowingstringsarelegalaccessmodes:
" r e a d " or" r " forreadonlyaccess " w r i t e " or" w " forwriteonlyaccess " u p d a t e " or" u " forread/writeaccess " a p p e n d " or" a " forappendread/writeaccess

( d e v i c e( o p e n" n e w f i l e . d a t a "" w r i t e " ) ) 5 ( p r i n t" h e l l ow o r l d \ n " ) " h e l l ow o r l d " ( c l o s e( d e v i c e ) ) 5 ( s e t' a F i l e( o p e n" n e w f i l e . d a t a "" r e a d " ) ) ( s e e ka F i l e6 ) ( s e t' i n C h a r( r e a d c h a ra F i l e ) ) ( p r i n ti n C h a r" \ n " ) ( c l o s ea F i l e )

Thefirstexampleuseso p e n tosetthedeviceforprintandwritestheword" h e l l ow o r l d " intothefilen e w f i l e . d a t a .Thesecond examplereadsabytevalueatoffset6inthesamefile(theASCIIvalueof' w ' is119).Notethatusingc l o s e on(device) automaticallyresetsdeviceto0 (zero). Asanadditionalstroption," n o n b l o c k " or" n " canbespecifiedafterthe" r e a d " or" w r i t e " option.OnlyavailableonUnix systems,nonblockingmodecanbeusefulwhenopeningnamedpipesbutisnotrequiredtoperformI/Oonnamedpipes.

or
syntax:(orexp1[exp2...]) Evaluatesexpressionsexpxfromlefttorightuntilfindingaresultthatdoesnotevaluateton i l ortheemptylist( ) .Theresultisthe returnvalueoftheo r expression.
( s e t' x1 0 ) ( o r( >x1 0 0 )( =x1 0 ) ) t r u e ( o r" h e l l o "( >x1 0 0 )( =x1 0 ) ) " h e l l o " ( o r' ( ) ) ( )

( o rt r u e ) ( o r )

t r u e n i l

ostype
syntax:ostype
o s t y p e isabuiltinsystemconstantcontainingthenameoftheoperatingsystemnewLISPisrunningon. o s t y p e " W i n 3 2 "

Oneofthefollowingstringsisreturned:" L i n u x " ," B S D " ," O S X " ," T r u 6 4 U n i x " ," S o l a r i s " ," S u n O S " ," W i n 3 2 " ,o r " O S / 2 " .
o s t y p e canbeusedtowriteplatformindependentcode: ( i f ( =o s t y p e" L i n u x " )( i m p o r t" l i b z . s o " ) ( =o s t y p e" B S D " )( i m p o r t" l i b z . s o " ) ( =o s t y p e" O S X " )( i m p o r t" l i b z . d y l i b " ) . . . ( p r i n t l n" c a n n o ti m p o r tl i b zo nt h i sp l a t f o r m " )

UsesysinfotolearnmoreaboutthecurrentflavorofnewLISPrunning. ForatableofotherbuiltinsystemvariablesandsymbolsseethechapterSystemSymbolsandConstantsintheappendix.

pack
syntax:(packstrformatexp1[exp2...]) syntax:(packstrformatlist) syntax:(packstructexp1[exp2...]) syntax:(packstructlist) Whenthefirstparameterisastring,p a c k packsoneormoreexpressions(exp1toexpn)intoabinaryformatspecifiedintheformat stringstrformat,andreturningthebinarystructureinastringbuffer.Thesymmetricalunpackfunctionisusedforunpacking.The expressionargumentscanalsobegiveninalist.p a c k andu n p a c k areusefulwhenreadingandwritingbinaryfiles(seereadand write)orwhenunpackingbinarystructuresfromreturnvaluesofimportedCfunctionsusingi m p o r t . Whenthefirstparameteristhesymbolofastructdefinition,p a c k usestheformatasspecifiedinstruct.Whilep a c k withstrformat literallypacksasspecified,p a c k withstructwillinsertstructurealigningpadbytesdependingondatatype,orderofelementsand CPUarchitecture.Refertothedescriptionofthestructfunctionformoredetail. Thefollowingcharactersareusedinstrformat: format
c b d u l d

description asigned8bitnumber anunsigned8bitnumber asigned16bitshortnumber anunsigned16bitshortnumber

asigned32bitlongnumber
l u L d L u f l f s n n n > <

anunsigned32bitlongnumber asigned64bitlongnumber anunsigned64bitlongnumber afloatin32bitrepresentation adoublefloatin64bitrepresentation astringofnnullpaddedASCIIcharacters nnullcharacters switchtobigendianbyteorder switchtolittleendianbyteorder

p a c k willconvertallfloatsintointegerswhenpassedtob ,c ,d ,l d ,orl u formats.Itwillalsoconvertintegersintofloatswhen

passingthemtof andl f formats.


( p a c k" ccc "6 56 66 7 ) " A B C " ( u n p a c k" ccc "" A B C " ) ( 6 56 66 7 ) ( p a c k" ccc "012 ) " \ 0 0 0 \ 0 0 1 \ 0 0 2 " ( u n p a c k" ccc "" \ 0 0 0 \ 0 0 1 \ 0 0 2 " ) ( 012 ) ( s e t' s( p a c k" cdu "1 01 2 3 4 55 6 7 8 9 ) ) ( u n p a c k" cdu "s ) ( 1 01 2 3 4 55 6 7 8 9 ) ( s e t' s( p a c k" s 1 0f "" r e s u l t "1 . 2 3 ) ) ( u n p a c k" s 1 0f "s ) ( " r e s u l t \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 "1 . 2 3 0 0 0 0 0 1 9 ) ( p a c k" n 1 0 " )" \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 " ( s e t' s( p a c k" s 3l f "" r e s u l t "1 . 2 3 ) ) ( u n p a c k" s 3f "s ) ( " r e s "1 . 2 3 ) ( s e t' s( p a c k" cn 7c "1 12 2 ) ) ( u n p a c k" cn 7c "s ) ( 1 12 2 ) ) ( u n p a c k" b "( p a c k" b "1 . 0 ) ) ( 2 5 5 ) ( u n p a c k" f "( p a c k" f "1 2 3 ) ) ( 1 2 3 )

Thelasttwostatementsshowhowfloatingpointnumbersareconvertedintointegerswhenrequiredbytheformatspecification. Theexpressionstopackcanalsobegiveninalist:
( s e t' l s t' ( " A "" B "" C " ) ) ( s e t' a d r( p a c k" l u l u l u "l s t ) ) ( m a pg e t s t r i n g( u n p a c k" l u l u l u "a d r ) )

( " A "" B "" C " )

Notethatthelistshouldbereferenceddirectlyinp a c k ,sothepointerspassedbya d r arevalid.a d r wouldbewrittenasc h a r* a d r [ ] intheCprogramminglanguageandrepresentsa32bitpointertoanarrayof32bitstringpointers. The> and< specifierscanbeusedtoswitchbetweenlittleendianandbigendianbyteorderwhenpackingorunpacking:


( p a c k" d "1 ) " \ 0 0 1 \ 0 0 0 " ; ;o nl i t t l ee n d i a nC P U ( p a c k" > d "1 ) " \ 0 0 0 \ 0 0 1 " ; ;f o r c eb i ge n d i a n ( p a c k" l d "1 ) " \ 0 0 1 \ 0 0 0 \ 0 0 0 \ 0 0 0 "; ;o nl i t t l ee n d i a nC P U ( p a c k" < l d "1 ) " \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 1 "; ;f o r c eb i ge n d i a n ( p a c k" > u< u "11 )" \ 0 0 0 \ 0 0 1 \ 0 0 1 \ 0 0 0 "; ;s w i t c ht w i c e

Switchingthebyteorderwillaffectallnumberformatswith16,32,or64bitsizes. Thepackandunpackformatneednotbethesame:

( s e t' s( p a c k" s 3 "" A B C " ) ) ( u n p a c k" ccc "s ) ( 6 56 66 7 )

Theexamplesshowspacesbetweentheformatspecifiers.Thesearenotrequiredbutcanbeusedtoimprovereadability. Seealsotheaddress,getint,getlong,getchar,getstring,andunpackfunctions.

parse
syntax:(parsestrdata[strbreak[intoption]]) Breaksthestringthatresultsfromevaluatingstrdataintostringtokens,whicharethenreturnedinalist.Whennostrbreakis given,p a r s e tokenizesaccordingtonewLISP'sinternalparsingrules.Astringmaybespecifiedinstrbreakfortokenizingonlyat theoccurrenceofastring.Ifanintoptionnumberisspecified,aregularexpressionpatternmaybeusedinstrbreak. Whenstrbreakisnotspecified,themaximumtokensizeis2048forquotedstringsand256foridentifiers.Inthiscase,newLISP usesthesamefastertokenizeritusesforparsingnewLISPsource.Ifstrbreakisspecified,thereisnolimitationonthelengthof tokens.Adifferentalgorithmisusedthatsplitsthesourcestringstrdataatthestringinstrbreak.
( p a r s e" h e l l oh o wa r ey o u " ) ( p a r s e" o n e : t w o : t h r e e "" : " ) ( " h e l l o "" h o w "" a r e "" y o u " ) ( " o n e "" t w o "" t h r e e " )

( p a r s e" o n e t w o t h r e e "" " ) ( " o n e "" t w o "" t h r e e " ) ( p a r s e" o n e t w o t h r e e f o u r "" + "0 ) ( " o n e "" t w o "" t h r e e "" f o u r " ) ( p a r s e" h e l l or e g u l a r e x p r e s s i o n1 ,2 ,3 "{ , \ s * | \ s + }0 ) ( " h e l l o "" r e g u l a r "" e x p r e s s i o n "" 1 "" 2 "" 3 " )

Thelasttwoexamplesshowaregularexpressionasthebreakstringwiththedefaultoption0 (zero).Insteadof{ and} (leftand rightcurlybrackets),doublequotescanbeusedtolimitthepattern.Inthiscase,doublebackslashesmustbeusedinsidethepattern. ThelastpatterncouldbeusedforparsingCSV(CommaSeparatedValues)files.Fortheregularexpressionoptionnumbers,see regex.


p a r s e willreturnemptyfieldsaroundseparatorsasemptystrings: ( p a r s e" 1 , 2 , 3 , "" , " )( " 1 "" 2 "" 3 "" " ) ( p a r s e" 1 , , , 4 "" , " ) ( " 1 "" "" "" 4 " ) ( p a r s e" , "" , " ) ( " "" " ) ( p a r s e" " ) ( ) ( p a r s e" """ ) ( )

Thisbehaviorisneededwhenparsingrecordswithemptyfields. Parsinganemptystringwillalwaysresultinanemptylist. Usetheregexfunctiontobreakstringsupandthedirectory,find,findall,regex,replace,andsearchfunctionsforusingregular expressions.

peek
syntax:(peekinthandle)

Returnsthenumberofbytesreadytobereadonafiledescriptorotherwise,itreturnsn i l ifthefiledescriptorisinvalid.p e e k can alsobeusedtochecks t d i n .ThisfunctionisonlyavailableonUnixlikeoperatingsystems.


( p e e k0 ) ;c h e c k#o fb y t e sr e a d yo ns t d i n

Usethenetpeekfunctiontocheckfornetworksockets,orforthenumberofavailablebytesonthem.OnUnixsystems,netpeek canbeusedtocheckfiledescriptors.Thedifferenceisthatnetpeekalsosetsneterror.

pipe
syntax:(pipe) Createsaninterprocesscommunicationspipeandreturnsther e a d andw r i t e handlestoitwithinalist.
( p i p e ) ( 34 ) ;3f o rr e a d ,4f o rw r i t i n g

Thepipehandlescanbepassedtoachildprocesslaunchedviaprocessortoforkforinterprocesscommunications. Notethatthepipedoesnotblockwhenbeingwrittento,butitdoesblockreadinguntilbytesareavailable.Areadlineblocksuntila newlinecharacterisreceived.Areadblockswhenfewercharactersthanspecifiedareavailablefromapipethathasnothadthe writingendclosedbyallprocesses. Morethanonepipecanbeopenedifrequired. newLISPcanalsousenamedpipes.Seetheopenfunctionforfurtherinformation.

pmt
syntax:(pmtnuminterestnumperiodsnumprincipal[numfuturevalue[inttype]]) Calculatesthepaymentforaloanbasedonaconstantinterestofnuminterestandconstantpaymentsovernumperiodsoftime. numfuturevalueisthevalueoftheloanattheend(typically0 . 0 ).Ifpaymentisattheendoftheperiod,inttypeis0 (zero)orint typeisomittedforpaymentatthebeginningofeachperiod,inttypeis1.
( p m t( d i v0 . 0 71 2 )2 4 01 0 0 0 0 0 ) 7 7 5 . 2 9 8 9 3 5 6

Theaboveexamplecalculatesapaymentof$775.30foraloanof$100,000atayearlyinterestrateof7percent.Itiscalculated monthlyandpaidover20years(20*12=240monthlyperiods).Thisillustratesthetypicalwaypaymentiscalculatedfor mortgages. Seealsothefv,irr,nper,npv,andpvfunctions.

pop!utf8
syntax:(poplist[intindex1[intindex2...]]) syntax:(poplist[listindexes]) syntax:(popstr[intindex[intlength]])

Usingp o p ,elementscanberemovedfromlistsandcharactersfromstrings. Inthefirstsyntax,p o p extractsanelementfromthelistfoundbyevaluatinglist.Ifasecondparameterispresent,theelementatint indexisextractedandreturned.SeealsoIndexingelementsofstringsandlists. Inthesecondversion,indicesarespecifiedinthelistlistindexes.Thisway,p o p workseasilytogetherwithrefandrefall,which returnlistsofindices.


p o p changesthecontentsofthetargetlist.Thepoppedelementisreturned. ( s e t' p L i s t' ( ( fg )abc" h e l l o "de1 0 ) ) ( p o pp L i s t ) ( fg ) ( p o pp L i s t ) a p L i s t ( bc" h e l l o "de1 0 ) ( p o pp L i s t3 ) d ( p o pp L i s t1 0 0 ) 1 0 p L i s t ( bc" h e l l o "e ) ( p o pp L i s t1 ) e p L i s t ( bc" h e l l o " ) ( p o pp L i s t2 ) c p L i s t ( b" h e l l o " ) ( s e t' p L i s t' ( a2( xy( pq )z ) ) ) ( p o pp L i s t120 ) p ; ;u s ei n d i c e si nal i s t ( s e t' p L i s t' ( ab( cd( )e ) ) ) ( p u s h' xp L i s t' ( 220 ) ) ( ab( cd( x )e ) ) p L i s t ( ab( cd( x )e ) ) ( r e f' xp L i s t ) ( 220 ) ( p o pp L i s t' ( 220 ) ) x p o p canalsobeusedonstringswithoneindex: ; ;u s ep o po ns t r i n g s ( s e t' s t r" n e w L I S P " ) ( p o ps t r44 ) " L I S P " s t r " n e w " ( p o ps t r1 ) " e " s t r " n w " ( s e t' s t r" x " ) ( p o ps t r ) " x " ( p o ps t r ) " "

Poppinganemptystringwillreturnanemptystring. Seealsothepushfunction,theinverseoperationtop o p .

popassoc!
syntax:(popassocexpkeylistassoc) syntax:(popassoclistkeyslistassoc) Removesanassociationreferredtobythekeyinexpkeyfromtheassociationlistinlistassocandreturnsthepoppedexpression.
; ;s i m p l ea s s o c i a t i o n s ( s e t' L' ( ( a1 )( b2 )( c3 ) ) ) ( p o p a s s o c' bL )( b2 ) L( ( a1 )( c3 ) ) ; ;n e s t e da s s o c i a t i o n s ( s e t' L' ( ( a( b1 )( c( d2 ) ) ) ) ) ( p o p a s s o c' aL )( a( b1 )( c( d2 ) ) ) L( ) ( s e t' L' ( ( a( b1 )( c( d2 ) ) ) ) ) ( p o p a s s o c' ( ab )L ) ( b1 ) L ( ( a( c( d2 ) ) ) ) ( s e t' L' ( ( a( b1 )( c( d2 ) ) ) ) ) ( p o p a s s o c' ( ac )L ) ( c( d2 ) ) L( ( a( b1 ) ) ) )

Seealsoassocforretrievingassociationsandsetfformodifyingassociationlists.

posturl
syntax:(posturlstrurlstrcontent[strcontenttype[stroption][inttimeout[strheader]]]) SendsanHTTPPOSTrequesttotheURLinstrurl.POSTrequestsareusedtopostinformationcollectedfromwebentryformsto awebsite.Mostofthetime,thefunctionp o s t u r l mimicswhatawebbrowserwoulddowhensendinginformationcollectedin anHTMLformtoaserver,butitcanalsobeusedtouploadfiles(seeanHTTPreference).Thefunctionreturnsthepagereturned fromtheserverinastring. Whenp o s t u r l encountersanerror,itreturnsastringdescriptionoftheerrorbeginningwithE R R : . Thelastparameter,inttimeout,isforanoptionaltimeoutvalue,whichisspecifiedinmilliseconds.Whennoresponsefromthehost isreceivedbeforethetimeouthasexpired,thestringE R R :t i m e o u t isreturned.
; ;s p e c i f yc o n t e n tt y p e ( p o s t u r l" h t t p : / / s o m e s i t e . c o m / f o r m . p l " " n a m e = j o h n D o e & c i t y = N e w % 2 0 Y o r k " " a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d " ) ; ;s p e c i f yc o n t e n tt y p ea n dt i m e o u t ( p o s t u r l" h t t p : / / s o m e s i t e . c o m / f o r m . p l " " n a m e = j o h n D o e & c i t y = N e w % 2 0 Y o r k " " a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d "8 0 0 0 ) ; ;a s s u m e sd e f a u l tc o n t e n tt y p ea n dn ot i m e o u t ( p o s t u r l" h t t p : / / s o m e s i t e . c o m / f o r m . p l " " n a m e = j o h n D o e & c i t y = N e w % 2 0 Y o r k "

Theaboveexampleuploadsausernameandcityusingaspecialformatcalleda p p l i c a t i o n / x w w w f o r m u r l e n c o d e d .p o s t u r l canbeusedtopostothercontenttypessuchasfilesorbinarydata.SeeanHTTPreferenceforothercontenttypespecificationsand dataencodingformats.Whenthecontenttypeparameterisomitted,p o s t u r l assumesa p p l i c a t i o n / x w w w f o r m u r l e n c o d e d asthedefaultcontenttype.

Additionalparameters
Whenstrcontenttypeisspecified,thestroption" h e a d e r " or" l i s t " canbespecifiedasthereturnpage.Iftheinttimeoutoption isspecified,thecustomheaderoptionstrheadercanbespecified,aswell.Seethefunctiongeturlfordetailsonbothofthese options. Seealsothegeturlandputurlfunctions.

pow
syntax:(pownum1num2[num3...]) syntax:(pownum1) Calculatesnum1tothepowerofnum2andsoforth.
( p o w1 0 02 ) 1 0 0 0 0 ( p o w1 0 00 . 5 ) 1 0 ( p o w1 0 00 . 53 ) 1 0 0 0 ( p o w3 ) 9

Whennum1istheonlyargument,p o w assumes2fortheexponent.

prefix
syntax:(prefixsym) Returnsthecontextofasymbolinsym:
( s e t fs' F o o : b a r ) F o o : b a r ( p r e f i xs ) F o o ( c o n t e x t ?( p r e f i xs ) ) t r u e ( t e r ms ) " b a r " ( =s( s y m( t e r ms )( p r e f i xs ) ) ) t r u e > ( c o n t e x t( p r e f i xs ) ) F o o F o o > ;s w i t c h e st oc o n t e x tF o o

Seealsotermtoextractthetermpartofasymbol.

prettyprint
syntax:(prettyprint[intlength[strtab[strfpformat]]) Reformatsexpressionsforprint,save,orsourceandwhenprintinginaninteractiveconsole.Thefirstparameter,intlength,specifies themaximumlinelength,andstrtabspecifiesthestringusedtoindentlines.Thethirdparameterstrfpformatdescribesthedefault formatforprintingfloatingpointnumbers.Allparametersareoptional.p r e t t y p r i n t returnsthecurrentsettingsorthenew settingswhenparametersarespecified.

( p r e t t y p r i n t ) ( 8 0""" % 1 . 1 0 g " ) ;d e f a u l ts e t t i n g ( p r e t t y p r i n t9 0" \ t " ) ( 9 0" \ t " ) ( p r e t t y p r i n t1 0 0 ) ( 1 0 0" \ t " ) ( s i n1 ) 0 . 8 4 1 4 7 0 9 8 4 8 ( p r e t t y p r i n t8 0""" % 1 . 3 f " ) ( s i n1 ) 0 . 8 4 1 ( s e t' x0 . 0 ) x 0 . 0 0 0

Thefirstexamplereportsthedefaultsettingsof80forthemaximumlinelengthandas p a c e characterforindenting.Thesecond examplechangesthelinelengthto90andtheindenttoaTABcharacter.Thethirdexamplechangesthelinelengthonly.Thelast examplechangesthedefaultformatforfloatingpointnumbers.Thisisusefulwhenprintingunformattedfloatingpointnumbers withoutfractionalparts,andthesenumbersshouldstillberecognizableasfloatingpointnumbers.Withoutthecustomformat,x wouldbeprintedas0 indistinguishablefromfloatingpointnumber.Allsituationswhereunformattedfloatingpointnumbersare printed,areaffected. Notethatp r e t t y p r i n t cannotbeusedtopreventlinebreaksfrombeingprinted.Tocompletelysuppressprettyprinting,usethe functionstringtoconverttheexpressiontoarawunformattedstringasfollows:
; ;p r i n tw i t h o u tf o r m a t t i n g ( p r i n t( s t r i n gm y e x p r e s s i o n ) )

primitive?
syntax:(primitive?exp) Evaluatesandtestsifexpisaprimitivesymbolandreturnst r u e orn i l dependingontheresult.
( s e t' v a rd e f i n e ) ( p r i m i t i v e ?v a r ) t r u e

print
syntax:(printexp1[exp2...]) Evaluatesandprintsexp1tothecurrentI/Odevice,whichdefaultstotheconsolewindow.Seethebuiltinfunctiondevicefor detailsonhowtospecifyadifferentI/Odevice. Listexpressionsareindentedbythenestinglevelsoftheiropeningparentheses. Severalspecialcharactersmaybeincludedinstringsencodedwiththeescapecharacter\ : character description
\ n \ r \ t \ n n n \ x n n

thelinefeedcharacter(ASCII10) thecarriagereturncharacter(ASCII13) thetabcharacter(ASCII9) wheren n n isadecimalASCIIcodebetween000and255 wheren n isahexadecimalASCIIcodebetween00andFF

( p r i n t( s e t' r e s( +123 ) ) ) ( p r i n t" t h er e s u l ti s "r e s" \ n " ) " \ 0 6 5 \ 0 6 6 \ 0 6 7 " " A B C "

Tofinishprintingwithalinefeed,useprintln.

println
syntax:(printlnexp1[exp2...]) Evaluatesandprintsexp1tothecurrentI/Odevice,whichdefaultstotheconsolewindow.Alinefeedisprintedattheend.See thebuiltinfunctiondevicefordetailsonhowtospecifyadifferentI/Odevice.p r i n t l n worksexactlylikeprintbutemitsaline feedcharacterattheend. Seealsothewritelineandprintfunctions.

probchi2
syntax:(probchi2numchi2intdf) ReturnstheprobabilityofanobservedChistatisticinnumchi2withnumdfdegreesoffreedomtobeequalorgreaterunderthe nullhypothesis.p r o b c h i 2 isderivedfromtheincompleteGammafunctiongammai.
( p r o b c h i 21 06 ) 0 . 1 2 4 6 5 2 0 1 9 5

Seealsotheinversefunctioncritchi2.

probf
syntax:(probfnumfintdf1intdf2) ReturnstheprobabilityofanobservedFstatisticinnumfwithintdf1andintdf2degreesoffreedomtobeequalorgreaterunder thenullhypothesis.
( p r o b f2 . 7 51 01 2 ) 0 . 0 5 0 1 9 9 0 8 0 4

Seealsotheinversefunctioncritf.

probt
syntax:(probtnumtintdf1) ReturnstheprobabilityofanobservedStudent'ststatisticinnumtwithintdfdegreesoffreedomtobeequalorgreaterunderthe

nullhypothesis.
( p r o b t1 . 7 61 4 ) 0 . 0 5 0 1 1 4 5 4 5 5 1

Seealsotheinversefunctioncritt.

probz
syntax:(probznumz) Returnstheprobabilityofnumz,nottoexceedtheobservedvaluewherenumzisanormaldistributedvaluewithameanof0 . 0 andastandarddeviationof1 . 0 .
( p r o b z0 . 0 ) 0 . 5

Seealsotheinversefunctioncritz.

process
syntax:(processstrcommand) syntax:(processstrcommandintpipeinintpipeout[intwin32option]) syntax:(processstrcommandintpipeinintpipeout[intunixpipeerror]) Inthefirstsyntax,p r o c e s s launchesaprocessspecifiedinstrcommandandimmediatelyreturnswithaprocessIDorn i l ifa processcouldnotbecreated.Thisprocesswillexecutetheprogramspecifiedorimmediatelydieifstrcommandcouldnotbe executed. OnMacOSXandotherUnixes,theapplicationorscriptmustbespecifiedwithitsfullpathname.ThenewprocessinheritstheOS environmentfromtheparentprocess. Commandlineargumentsareparsedoutatspaces.ArgumentscontainingspacesmustbedelimitedusingsinglequotesonMacOS XandotherUnixes.OnWin32,doublequotesareused.Theprocessidreturnedcanbeusedtodestroytherunningprocessusing destroy,iftheprocessdoesnotexitbyitself.
( p r o c e s s" c : / W I N D O W S / s y s t e m 3 2 / n o t e p a d . e x e " ) 1 8 9 4;o nW i n 3 2 ;f i n do u tt h ep a t ho ft h ep r o g r a mt os t a r tu s i n ge x e c , ;i ft h ep a t hi sn o tk n o w n ( p r o c e s s( f i r s t( e x e c" w h i c hx c l o c k " ) ) ) 2 2 6 0 7;o nU n i x

Ifthepathoftheexecutableisunknown,e x e c togetherwiththeUnixw h i c h commandcanbeusedtostartaprogram.Thepid returnedcanbeusedtodestroytheprocess. Inthesecondsyntax,standardinputandoutputofthecreatedprocesscanberedirectedtopipehandles.Whenremappingstandard I/Oofthelaunchedapplicationtoapipe,itispossibletocommunicatewiththeotherapplicationviawritelineandreadlineorwrite andreadstatements:


; ;L i n u x / U n i x ; ;c r e a t ep i p e s ( m a ps e t' ( m y i nb c o u t )( p i p e ) ) ( m a ps e t' ( b c i nm y o u t )( p i p e ) ) ; ;l a u n c hU n i x' b c 'c a l c u l a t o ra p p l i c a t i o n ( p r o c e s s" / u s r / b i n / b c "b c i nb c o u t )7 9 1 6

( w r i t e l i n em y o u t" 3+4 " ) ;b ce x p e c t sal i n e f e e d ( r e a d l i n em y i n ) " 7 " ; ;b cc a nu s eb i g n u m sw i t ha r b i t r a r yp r e c i s i o n ( w r i t e l i n em y o u t" 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5*1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 " ) ( r e a d l i n em y i n ) " 1 5 2 4 1 5 7 8 7 5 3 2 3 8 6 6 9 1 2 0 5 6 2 3 9 9 0 2 5 " ; ;d e s t r o yt h ep r o c e s s ( d e s t r o y7 9 1 6 ) ; ;W i n 3 2 ( m a ps e t' ( m y i nc m d o u t )( p i p e ) ) ( m a ps e t' ( c m d i nm y o u t )( p i p e ) ) ( p r o c e s s" c : / P r o g r a mF i l e s / n e w l i s p / n e w l i s p . e x ec "c m d i nc m d o u t ) 1 2 8 4 ( w r i t e l i n em y o u t" ( +34 ) " ) ( r e a d l i n em y i n )" 7 " ; ;d e s t r o yt h ep r o c e s s ( d e s t r o y1 2 8 4 )

OnWin32versionsofnewLISP,afourthoptionalparameterofintwin32optioncanbespecifiedtocontrolthedisplaystatusofthe application.Thisoptiondefaultsto1 forshowingtheapplication'swindow,0 forhidingit,and2 forshowingitminimizedonthe Windowslaunchbar. OnbothWin32andLinux/Unixsystems,standarderrorwillberedirectedtostandardoutbydefault.OnLinux/Unix,anoptional pipehandleforstandarderroroutputcanbedefinedinintunixpipeerror. Thefunctionpeekcanbeusedtocheckforinformationonthepipehandles:


; ;c r e a t ep i p e s ( m a ps e t' ( m y i nb c o u t )( p i p e ) ) ( m a ps e t' ( b c i nm y o u t )( p i p e ) ) ( m a ps e t' ( e r r i ne r r o u t )( p i p e ) ) ; ;l a u n c hU n i x' b c 'c a l c u l a t o ra p p l i c a t i o n ( p r o c e s s" b c "b c i nb c o u te r r o u t ) ( w r i t em y o u tc o m m a n d ) ; ;w a i tf o rb cs e n d i n gr e s u l to re r r o ri n f o ( w h i l e( a n d( =( p e e km y i n )0 ) ( =( p e e ke r r i n )0 ) )( s l e e p1 0 ) ) ( i f( >( p e e ke r r i n )0 ) ( p r i n t l n( r e a d l i n ee r r i n ) ) ) ( i f( >( p e e km y i n )0 ) ( p r i n t l n( r e a d l i n em y i n ) ) )

NotallinteractiveconsoleapplicationscanhavetheirstandardI/Ochannelsremapped.Sometimesonlyonechannel,inorout,can beremapped.Inthiscase,specify0 (zero)fortheunusedchannel.Thefollowingstatementusesonlythelaunchedapplication's output:


( p r o c e s s" a p p "0a p p o u t )

Normally,twopipesareused:oneforcommunicationstothechildprocessandtheotheroneforcommunicationsfromthechild process. Seealsothepipeandsharefunctionsforinterprocesscommunicationsandthesemaphorefunctionforsynchronizationofseveral processes.SeetheforkfunctionforstartingseparatenewLISPprocessesonLinux/Unix.

promptevent
syntax:(prompteventsymeventhandler|funceventhandler) RefinesthepromptasshownintheinteractivenewLISPshell.Thesymeventhandlerorfunceventhandleriseitherasymbolofa userdefinedfunctionoralambdaexpression:
>( p r o m p t e v e n t( f n( c t x )( s t r i n gc t x" : "( r e a l p a t h )" $" ) ) ) $ p r o m p t e v e n t M A I N : / U s e r s / n e w l i s p $( +34 ) 7 M A I N : / U s e r s / n e w l i s p $

Thecurrentcontextbeforecallingthep r o m p t e v e n t codeispassedasaparametertothefunction.Computeroutputisshownin bold. Theexampleredefinesthe> prompttobethecurrentcontextfollowedbyacolon: ,followedbythedirectoryname,followedby thedollarsymbol.Togetherwiththecommandeventfunctionthiscanbeusedtocreatefullycustomizedshellsorcustomcommand interpreters. Thefunctioninp r o m p t e v e n t mustreturnastringof63charactersmaximum.Notreturningastringwillleavetheprompt unchanged.

protected?
syntax:(protected?sym) Checksifasymbolinsymisprotected.Protectedsymbolsarebuiltinfunctions,contextsymbols,andallsymbolsmadeconstant usingtheconstantfunction:
( p r o t e c t e d ?' p r i n t l n ) ( c o n s t a n t' a V a r1 2 3 ) ( p r o t e c t e d ?' a V a r ) t r u e t r u e

push!utf8
syntax:(pushexplist[intindex1[intindex2...]]) syntax:(pushexplist[listindexes]) syntax:(pushstr1str2[intindex]) Insertsthevalueofexpintothelistlist.Ifintindexispresent,theelementisinsertedatthatindex.Iftheindexisabsent,theelement isinsertedatindex0 (zero),thefirstelement.p u s h isadestructiveoperationthatchangesthecontentsofthetargetlist. Thelistchangedisreturnedasareferenceonwhichotherbuiltinfunctionscanwork.SeealsoIndexingelementsofstringsand lists. Ifmorethanoneintindexispresent,theindicesareusedtoaccessanestedliststructure.Improperindices(thosenotmatchinglist elements)arediscarded.

Thesecondversiontakesalistoflistindexesbutisotherwiseidenticaltothefirst.Inthisway,p u s h workseasilytogetherwithref andrefall,whichreturnlistsofindices. Iflistdoesnotcontainalist,listmustcontainan i l andwillbeinitializedtotheemptylist. Repeatedlyusingp u s h totheendofalistusing1 astheintindexisoptimizedandasfastaspushingtothefrontofalistwithno indexatall.Thiscanbeusedtoefficientlygrowalist.


;i n s e r t i n gi nf r o n t ( s e t' p L i s t' ( bc ) ) ( bc ) ( p u s h' ap L i s t ) ( abc ) p L i s t ( abc ) ;i n s e r ta ti n d e x ( p u s h" h e l l o "p L i s t2 ) ( ab" h e l l o "c ) ;o p t i m i z e da p p e n d i n ga tt h ee n d ( p u s h' zp L i s t1 ) ( ab" h e l l o "cz ) ;i n s e r t i n gl i s t si nl i s t s ( p u s h' ( fg )p L i s t ) ( ( fg )ab" h e l l o "cz ) ;i n s e r t i n ga tn e g a t i v ei n d e x ( p u s h' xp L i s t3 ) ( ( fg )ab" h e l l o "xcz ) ;u s i n gm u l t i p l ei n d i c e s ( p u s h' hp L i s t01 ) ( ( fgh )ab" h e l l o "xcz ) ;u s ei n d i c e si nal i s t ( s e t' p L i s t' ( ab( cd( )e ) ) ) ( p u s h' xp L i s t' ( 220 ) ) ( ab( cd( x )e ) ) ( r e f' xp L i s t ) ( 220 )

( p o pp L i s t' ( 220 ) ) x ;t h et a r g e tl i s ti sap l a c er e f e r e n c e ( s e t' l s t' ( ( a1 )( b2 )( c3 )( d ) ) ) ( p u s h4( a s s o c' dl s t )1 )( d4 ) l s t( ( a1 )( b2 )( c3 )( d4 ) ) ;p u s ho nu n i n i t i a l i z e ds y m b o l a V a r n i l ( p u s h9 9 9a V a r ) ( 9 9 9 ) a V a r ( 9 9 9 ) p u s h andpopcanbecombinedtomodelaqueue: ;p o pa n dp u s haa saq u e u e ( s e t' Q' ( abcde ) ) ( p o p( p u s h' fQ1 ) )a ( p o p( p u s h' gQ1 ) )b Q ( cdefg )

Becausep u s h returnsareferencetothemodifiedlist,p o p canworkonitdirectly. Inthethirdsyntaxp u s h canbeusedtochangestrings.Whenintindexisused,itreferstocharacterpositionsratherthanbyte positions.UTF8charactersmaybemultibytecharacters.


; ;p u s ho ns t r i n g s ( s e t' s t r" a b c d e f g " )

( p u s h" h i j k "s t r1 ) " a b c d e f g h i j k " s t r " a b c d e f g h i j k " ( p u s h" 1 2 3 "s t r ) " 1 2 3 a b c d e f g h i j k " ( p u s h" 4 "s t r3 ) " 1 2 3 4 a b c d e f g h i j k " ( s e t' s t r" \ u 0 3 b 1 \ u 0 3 b 2 \ u 0 3 b 3 " ) " " ( p u s h" * "s t r1 ) " * " ; ;p u s ho nas t r i n gr e f e r e n c e ( s e t' l s t' ( " a b c "" x y z " ) ) ( p u s hx( l s t0 ) )" x a b c " l s t( " x a b c "" x y z " )

Seealsothepopfunction,whichistheinverseoperationtop u s h .

puturl
syntax:(puturlstrurlstrcontent[stroption][inttimeout[strheader]]) TheHTTPPUTprotocolisusedtotransferinformationinstrcontenttoafilespecifiedinstrurl.ThelesserknownHTTPPUT modeisfrequentlyusedfortransferringwebpagesfromHTMLeditorstoWebservers.InordertousePUTmode,thewebserver's softwaremustbeconfiguredcorrectly.OntheApachewebserver,usethe' S c r i p tP U T ' directiveinthesectionwheredirectory accessrightsareconfigured. Ifstrurlstartswithf i l e : / / thenstrcontentiswrittentothelocalfilesystem. Optionally,aninttimeoutvaluecanbespecifiedinmillisecondsasthelastparameter.p u t u r l willreturnE R R :t i m e o u t whenthe hostgivesnoresponseandthetimeoutexpires.Onothererrorconditions,p u t u r l returnsastringstartingwithE R R : andthe descriptionoftheerror.
p u t u r l requestsarealsounderstoodbynewLISPservernodes. ( p u t u r l" h t t p : / / a s i t e . c o m / m y F i l e . t x t "" H it h e r e " ) ( p u t u r l" h t t p : / / a s i t e . c o m / m y F i l e . t x t "" H it h e r e "2 0 0 0 ) ( p u t u r l" h t t p : / / a s i t e . c o m / w e b p a g e . h t m l " ( r e a d f i l e" w e b p a g e . h t m l " ) ) ;w r i t e/ h o m e / j o e / n e w f i l e . t x to nt h el o c a lf i l es y s t e m ( p u t s u r l" f i l e : / / / h o m e / j o e / n e w f i l e . t x t "" H e l l oW o r l d ! " )

Thefirstexamplecreatesafilecalledm y F i l e . t x t onthetargetserverandstoresthetextstring' H it h e r e ' init.Inthesecond example,thelocalfilew e b p a g e . h t m l istransferredtoa s i t e . c o m . OnanApachewebserver,thefollowingcouldbeconfiguredinh t t p d . c o n f .


< d i r e c t o r y/ w w w / h t d o c s > O p t i o n sA l l S c r i p tP U T/ c g i b i n / p u t . c g i < / d i r e c t o r y >

Thescriptp u t . c g i wouldcontaincodetoreceivecontentfromthewebserverviaSTDIN.Thefollowingisaworkingp u t . c g i writteninnewLISPfortheApachewebserver:


# ! / u s r / h o m e / j o h n d o e / b i n / n e w l i s p # # #g e tP U Tm e t h o dd a t af r o mC G IS T D I N

#a n dw r i t ed a t at oaf i l es p e c i f i e d #i n tt h eP U Tr e q u e s t # # ( p r i n t" C o n t e n t T y p e :t e x t / h t m l \ n \ n " ) ( s e t' c n t0 ) ( s e t' r e s u l t" " ) ( i f( =" P U T "( e n v" R E Q U E S T _ M E T H O D " ) ) ( b e g i n ( s e t' l e n( i n t( e n v" C O N T E N T _ L E N G T H " ) ) ) ( w h i l e( <c n tl e n ) ( s e t' n( r e a d( d e v i c e )b u f f e rl e n ) ) ( i f( n o tn ) ( s e t' c n tl e n ) ( b e g i n ( i n cc n tn ) ( w r i t er e s u l tb u f f e r ) ) ) ) ( s e t' p a t h( a p p e n d " / u s r / h o m e / j o h n d o e " ( e n v" P A T H _ T R A N S L A T E D " ) ) ) ) ( w r i t e f i l ep a t hr e s u l t )

( e x i t )

Notethatthescriptappends".txt"tothepathtoavoidtheCGIexecutionofuploadedmaliciousscripts.Notealsothatthetwolines wherethefilepathiscomposedmayworkdifferentlyinyourwebserverenvironment.Checkenvironmentvariablespassedbyyour webserverforcompositionoftherightfilepath.


p u t u r l returnscontentreturnedbythep u t . c g i script.

Additionalparameters
Instroption," h e a d e r " or" l i s t " canbespecifiedforthereturnedpage.Iftheinttimeoutoptionisspecified,thecustomheader optionstrheadercanbespecified,aswell.Seethefunctiongeturlfordetailsonbothoftheseoptions. Seealsothefunctionsgeturlandposturl,whichcanbeusedtouploadfileswhenformattingformdataasm u l t i p a r t / f o r m d a t a .

pv
syntax:(pvnumintnumnpernumpmt[numfv[inttype]]) Calculatesthepresentvalueofaloanwiththeconstantinterestratenuminterestandtheconstantpaymentnumpmtafternumnper numberofpayments.Thefuturevaluenumfvisassumedtobe0 . 0 ifomitted.Ifpaymentisattheendoftheperiod,inttypeis0 (zero)orinttypeisomittedforpaymentatthebeginningofeachperiod,inttypeis1.
( p v( d i v0 . 0 71 2 )2 4 07 7 5 . 3 0 ) 1 0 0 0 0 0 . 1 3 7 3

Intheexample,aloanthatwouldbepaidoff(futurevalue=0 . 0 )in240paymentsof$775.30ataconstantinterestrateof7percent peryearwouldstartoutat$100,000.14. Seealsothefv,irr,nper,npv,andpmtfunctions.

quote
syntax:(quoteexp) Returnsexpwithoutevaluatingit.Thesameeffectcanbeobtainedbyprependinga' (singlequote)toexp.
( q u o t ex ) ( q u o t e1 2 3 ) ( q u o t e( abc ) ) ( =( q u o t ex )' x ) x 1 2 3 ( abc ) t r u e

quote?
syntax:(quote?exp) Evaluatesandtestswhetherexpisquoted.Returnst r u e orn i l dependingontheresult.
( s e t' v a r' ' x ) ' x ( q u o t e ?v a r ) t r u e

Notethatinthes e t statement,' ' x isquotedtwicebecausethefirstquoteislostduringtheevaluationofthes e t assignment.

rand
syntax:(randintrange[intN]) Evaluatestheexpressioninintrangeandgeneratesarandomnumberintherangeof0 (zero)to(intrange1).When0 (zero)is passed,theinternalrandomgeneratorisinitializedusingthecurrentvaluereturnedbytheCt i m e ( ) function.Optionally,asecond parametercanbespecifiedtoreturnalistoflengthintNofrandomnumbers.
( d o t i m e s( x1 0 0 )( p r i n t( r a n d2 ) ) )= > 1 1 1 0 0 0 0 0 1 1 0 1 0 0 1 1 1 1 0 0 1 1 1 1 0 1. . .1 0 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 0 0 0 1 0 0 0 ( r a n d31 0 0 ) ( 201120 )

Thefirstlineintheexampleprintsequallydistributed0 'sand1 's,whilethesecondlineproducesalistof100integerswith0 ,1 ,and 2 equallydistributed.Usetherandomandnormalfunctionstogeneratefloatingpointrandomnumbers,anduseseedtovarythe initialseedforrandomnumbergeneration.

random
syntax:(randomfloatoffsetfloatscaleintn) syntax:(randomfloatoffsetfloatscale) Inthefirstform,r a n d o m returnsalistofintnevenlydistributedfloatingpointnumbersscaled(multiplied)byfloatscale,withan addedoffsetoffloatoffset.Thestartingpointoftheinternalrandomgeneratorcanbeseededusingseed.

( r a n d o m011 0 ) ( 0 . 1 0 8 9 8 9 7 30 . 6 9 8 2 3 7 8 30 . 5 6 4 3 4 8 7 20 . 0 4 1 5 0 7 2 8 90 . 1 6 5 1 6 7 3 3 0 . 8 1 5 4 0 9 1 70 . 6 8 5 5 3 7 8 40 . 7 6 4 7 1 0 6 80 . 8 2 3 1 4 5 8 50 . 9 5 9 2 4 5 6 4 )

Whenusedinthesecondform,r a n d o m returnsasingleevenlydistributednumber:
( r a n d o m1 05 ) 1 1 . 0 9 7 1

Seealsothenormalandrandfunctions.

randomize
syntax:(randomizelist[bool]) Rearrangestheorderofelementsinlistintoarandomorder.
( r a n d o m i z e' ( abcdefg ) ) ( bacgdef ) ( r a n d o m i z e( s e q u e n c e15 ) ) ( 35412 ) r a n d o m i z e willalwaysreturnasequencedifferentfromthepreviousonewithouttheoptionalboolflag.Thismayrequirethe

functiontocalculateseveralsetsofreorderedelements,whichinturnmayleadtodifferentprocessingtimeswithdifferent invocationsofthefunctiononthesameinputlistlength.Toallowfortheoutputtobeequaltotheinput,t r u e oranyexpression evaluatingtonotn i l mustbespecifiedinbool.


r a n d o m i z e usesaninternalpseudorandomsequencegeneratorthatreturnsthesameseriesofresultseachtimenewLISPisstarted.

Usetheseedfunctiontochangethissequence.

read!
syntax:(readintfilesymbufferintsize[strwait]) Readsamaximumofintsizebytesfromafilespecifiedinintfileintoabufferinsymbuffer.Anydatareferencedbythesymbol symbufferpriortothereadingisdeleted.Thehandleinintfileisobtainedfromapreviousopenstatement.Thesymbolsymbuffer containsdataoftypestringafterthereadoperation.symbuffercanalsobeadefaultfunctorspecifiedbyacontextsymbolfor referencepassinginandoutofuserdefinedfunctions.
r e a d isashorterwritingofr e a d b u f f e r .Thelongerformstillworksbutisdeprecatedandshouldbeavoidedinnewcode.

Optionally,astringtobewaitedforcanbespecifiedinstrwait.r e a d willreadamaximumamountofbytesspecifiedinintsizeor returnearlierifstrwaitwasfoundinthedata.Thewaitstringispartofthereturneddataandmustnotcontainbinary0 (zero) characters. Returnsthenumberofbytesreadorn i l whenthewaitstringwasnotfound.Inanycase,thebytesreadareputintothebuffer pointedtobysymbuffer,andthefilepointerofthefilereadismovedforward.Ifnonewbyteshavebeenread,symbufferwill containn i l .


( s e t' h a n d l e( o p e n" a F i l e . e x t "" r e a d " ) ) ( r e a dh a n d l eb u f f2 0 0 )

Reads200bytesintothesymbolb u f f fromthefilea F i l e . e x t .
( r e a dh a n d l eb u f f1 0 0 0" p a s s w o r d : " )

Reads1000bytesoruntilthestringp a s s w o r d : isencountered.Thestringp a s s w o r d : willbepartofthedatareturned.

Seealsothewritefunction.

readchar
syntax:(readchar[intfile]) ReadsabytefromafilespecifiedbythefilehandleinintfileorfromthecurrentI/Odevicee.g.stdinwhennofilehandleis specified.Thefilehandleisobtainedfromapreviousopenoperation.Eachr e a d c h a r advancesthefilepointerbyonebyte.Once theendofthefileisreached,n i l isreturned.
( d e f i n e( s l o w f i l e c o p yf r o m f i l et o f i l e ) ( s e t' i n f i l e( o p e nf r o m f i l e" r e a d " ) ) ( s e t' o u t f i l e( o p e nt o f i l e" w r i t e " ) ) ( w h i l e( s e t' c h r( r e a d c h a ri n f i l e ) ) ( w r i t e c h a ro u t f i l ec h r ) ) ( c l o s ei n f i l e ) ( c l o s eo u t f i l e ) " f i n i s h e d " )

Usereadlineanddevicetoreadwholetextlinesatatime.NotethatnewLISPsuppliesafastbuiltinfunctioncalledcopyfilefor copyingfiles. Seealsothewritecharfunction.

readexpr
syntax:(readexprstrsource[symcontext[experror[intoffset]]])
r e a d e x p r parsesthefirstexpressionsitfindsinstrsourceandreturnsthetranslatedexpressionwithoutevaluatingit.Anoptional

contextinsymcontextspecifiesanamespaceforthetranslatedexpression. Afteracalltor e a d e x p r thesystemvariable$ c o u n t containsthenumberofcharactersscanned. Ifanerroroccurswhentranslatingstrsourcetheexpressioninexperrorisevaluatedandtheresultreturned. intoffsetspecifiesanoptionaloffsetintostrsourcewhereprocessingshouldstart.Whencallingr e a d e x p r repeatedlythisnumber canbeupdatedusing$ c o u n t ,thenumberofcharactersprocessed.


( s e t' c o d e" ;as t a t e m e n t \ n ( d e f i n e( d o u b l ex )( +xx ) ) " ) ( r e a d e x p rc o d e )( d e f i n e( d o u b l ex )( +xx ) ) $ c o u n t4 1 r e a d e x p r behavessimilartoevalstringbutwithouttheevaluationstep: ( r e a d e x p r" ( +34 ) " ) ( +34 )

( e v a l s t r i n g" ( +34 ) " ) 7

Usingr e a d e x p r acustomizedcodereadercanbeprogrammedpreprocessingexpressionsbeforeevaluation. Seealsoreadereventforpreprocessingexpressionseventdriven.

readfile
syntax:(readfilestrfilename) Readsafileinstrfilenameinoneswoopandreturnsastringbuffercontainingthedata. Onfailurethefunctionreturnsn i l .Forerrorinformation,usesyserrorwhenusedonfiles.WhenusedonURLsneterrorgives moreerrorinformation.
( w r i t e f i l e" m y f i l e . e n c " ( e n c r y p t( r e a d f i l e" / h o m e / l i s p / m y F i l e " )" s e c r e t " ) )

Thefilem y f i l e isread,thenencryptedusingthepassword" s e c r e t " beforebeingwrittenbackintoanewfiletitled " m y f i l e . e n c " inthecurrentdirectory.


r e a d f i l e cantakeanh t t p : / / orf i l e : / / URLinstrfilename.Whentheprefixish t t p : / / ,r e a d f i l e worksexactlylikeget

urlandcantakethesameadditionalparameters.
( r e a d f i l e" h t t p : / / a s i t e . c o m / s o m e f i l e . t g z "1 0 0 0 0 )

Thefiles o m e f i l e . t g z isretrievedfromtheremotelocationh t t p : / / a s i t e . c o m .Thefiletransferwilltimeoutafter10secondsif itisnotfinished.Inthismode,r e a d f i l e canalsobeusedtotransferfilesfromremotenewLISPservernodes. Seealsothewritefileandappendfilefunctions.

readkey
syntax:(readkey) Readsakeyfromthekeyboardandreturnsanintegervalue.Fornavigationkeys,morethanoner e a d k e y callmustbemade.For keysrepresentingASCIIcharacters,thereturnvalueisthesameonallOSes,exceptfornavigationkeysandothercontrolsequences likefunctionkeys,inwhichcasethereturnvaluesmayvaryondifferentOSesandconfigurations.
( r e a d k e y ) ( r e a d k e y ) ( r e a d k e y ) ( r e a d k e y ) 9 7 6 5 1 0 1 3 ;a f t e rh i t t i n gt h eAk e y ;a f t e rh i t t i n gt h es h i f t e dAk e y ;a f t e rh i t t i n g[ e n t e r ]o nL i n u x ;a f t e rh i t t i n g[ e n t e r ]o nW i n 3 2

( w h i l e( ! =( s e t' c( r e a d k e y ) )1 )( p r i n t l nc ) )

Thelastexamplecanbeusedtocheckreturnsequencesfromnavigationandfunctionkeys.Tobreakoutoftheloop,pressC t r l A . Notethatr e a d k e y willonlyworkwhennewLISPisrunninginaUnixshellorWin32commandshell.ItwillnotworkintheJava basednewLISPGSorTcl/TkbasednewLISPTkfrontend.ItwillalsonotworkwhenexecutedbynewLISPUnixsharedlibrary ornewLISPWin32DLL(DynamicLinkLibrary).

readline
syntax:(readline[intfile]) ReadsfromthecurrentI/Odeviceastringdelimitedbyalinefeedcharacter(ASCII10).Thereisnolimittothelengthofthestring

thatcanberead.Thelinefeedcharacterisnotpartofthereturnedstring.Thelinealwaysbreaksonalinefeed,whichisthen swallowed.Alinebreaksonacarriagereturn(ASCII13)onlyiffollowedbyalinefeed,inwhichcasebothcharactersare discarded.Acarriagereturnaloneonlybreaksandisswallowedifitisthelastcharacterinthestream. Bydefault,thecurrentdeviceisthekeyboard(device0 ).UsethebuiltinfunctiondevicetospecifyadifferentI/Odevice(e.g.,a file).Optionally,afilehandlecanbespecifiedintheintfileobtainedfromapreviousopenstatement. Thelastbuffercontentsfromareadlineoperationcanberetrievedusingcurrentline. Whenr e a d l i n e isreadingfromafileorfromstdininaCGIprogramorpipe,itwillreturnn i l wheninputisexhausted. Whenusingr e a d l i n e onstdin,linelengthislimitedto2048charactersandperformanceismuchfaster.
( p r i n t" E n t e ran u m : " ) ( s e t' n u m( i n t( r e a d l i n e ) ) ) ( s e t' i n f i l e( o p e n" a f i l e . d a t "" r e a d " ) ) ( w h i l e( r e a d l i n ei n f i l e ) ( w r i t e l i n e ) ) ( c l o s ei n f i l e )

Thefirstexamplereadsinputfromthekeyboardandconvertsittoanumber.Inthesecondexample,afileisreadlinebylineand displayedonthescreen.Thew r i t e l i n e statementtakesadvantageofthefactthattheresultfromthelastr e a d l i n e operationis storedinasysteminternalbuffer.Whenwritelineisusedwithoutargument,itwritesthecontentsofthelastr e a d l i n e bufferto thescreen. Seealsothecurrentlinefunctionforretrievingthisbuffer.

readutf8
syntax:(readutf8intfile) ReadsanUTF8characterfromafilespecifiedbythefilehandleinintfile.Thefilehandleisobtainedfromapreviousopen operation.Eachr e a d u t f 8 advancesthefilepointerbythenumberofbytescontainedintheUTF8character.Oncetheendofthe fileisreached,n i l isreturned. ThefunctionreturnsanintegervaluewhichcanbeconvertedtoadisplayableUTF8characterstringusingthecharfunction.
( s e t' f l e( o p e n" u t f 8 t e x t . t x t "" r e a d " ) ) ( w h i l e( s e t qc h r( r e a d u t f 8f l e ) ) ( p r i n t( c h a rc h r ) ) )

TheexamplereadsafilecontainingUTF8encodedtextanddisplaysittotheterminalscreen.

readerevent
syntax:(readerevent[symeventhandler|funceventhandler]) syntax:(readerevent'nil) AneventhandlercanbespecifiedtohookbetweennewLISP'sreader,translationandevaluationprocess.Thefunctionspecifiedin symeventhandlerorfunceventhandlergetscalledafternewLISPtranslatesanexpressionandbeforeevaluatingit.Theevent handlercandotransformationontheexpressionbeforeitgetsevaluated. Specifyingaquotedn i l fortheeventwilldisableit.

Thefollowingonelinerr e a d e r e v e n t couldbeusedtoenhancetheinteractiveshellwithatracer:
> ( r e a d e r e v e n t( l a m b d a( e x )( p r i n t"= >"e x ) ) ) $ r e a d e r e v e n t >( +123 ) = >( +123 ) 6 >

Theexpressioninterceptedpassesthroughunchanged,butoutputisenhanced. Thefollowingexampleshowsthecoreofasimplemacrorewritepreprocessor.Afullversionisinstalledinthestandardlocationas modulefilem a c r o . l s p .


( c o n t e x t' m a c r o ) ;i n i t i a l i z em a c r ol i s t ( s e t fm a c r o l i s t' ( ) ) ;r e g i s t e r sam a c r o ( d e f i n e m a c r o( m a c r o : m a c r oc a l l pb o d y ) ( p u s h( l i s t( f i r s tc a l l p )' * )m a c r o l i s t1 ) ( e v a l( e x p a n d' ( d e f i n e m a c r oc a l l p( e x p a n d' b o d y ) )' c a l l p' b o d y ) ) ) ;t h ee v e n th a n d l e rt r a n s l a t i n ge x p r e s s i o n s ( d e f i n e( r e w r i t ee x p r ) ( i f( l i s t ?e x p r ) ( d o l i s t( p a t t e r nm a c r o l i s t ) ( i f( m a t c hp a t t e r ne x p r ) ( s e t fe x p r( e v a le x p r ) ) ( s e t r e f a l lp a t t e r ne x p r( e v a l$ i t )m a t c h ) )) ) e x p r ) ;r e g i s t e re v e n th a n d l e r ( r e a d e r e v e n tr e w r i t e ) ( c o n t e x tM A I N )

Thereadereventfunctionwillbecalledaftereachreadingofansexpressionbytheloadorevalstringfunction. Registerafunctionmacroforpreprocessing:
( m a c r o( s q u a r eX )( p o wX2 ) );m u s tu s eu p p e r c a s ev a r s ;u s et h em a c r o ( s q u a r e3 )9

Afterregisteringthemacros q u a r e newLISPwillexpandeachoccurrenceofa( s q u a r e. . . ) toa( p o w. . .2 ) expression. Note,thatvariablesinthemacrodefinitionmustbeuppercase.Themacroregisteringfunctionusesasyntaxformofe x p a n d workingonlyonuppercasevariables. Foramoredetaileddescriptionseethedocumentationform a c r o . l s p .

realpath
syntax:(realpath[strpath]) syntax:(realpathstrexecnametrue) Inthefirstsyntaxr e a l p a t h returnsthefullpathfromtherelativefilepathgiveninstrpath.Ifapathisnotgiven," . " (thecurrent

directory)isassumed.
( r e a l p a t h ) " / u s r / h o m e / f r e d " ;c u r r e n td i r e c t o r y ( r e a l p a t h" . / s o m e f i l e . t x t " ) " / u s r / h o m e / f r e d / s o m e f i l e . t x t "

Inthesecondsyntaxr e a l p a t h returnsthefullpathforanexecutablefoundgiveninstrexename.Thissyntaxreliesonan environmentvariablePATHdefinedonUNIXandWindowssystems.


( r e a l p a t h" m a k e "t r u e )" / u s r / b i n / m a k e "

TheoutputlengthislimitedbytheOS'smaximumallowedpathlength.Ifr e a l p a t h fails(e.g.,becauseofanonexistentpath),n i l isreturned.

receive!
syntax:(receiveintpidsymmessage) syntax:(receive) Inthefirstsyntax,thefunctionisusedformessageexchangebetweenchildprocesseslaunchedwithspawnandtheirparent process.Themessagereceivedreplacesthecontentsinsymmessage. Thefunctionreadsonemessagefromthereceiverqueueofintpidforeachinvocation.Whenthequeueisempty,n i l isreturned.
;s e n d i n gp r o c e s s ( s e n ds p i d" h e l l o " ) t r u e ;r e c e i v i n gp r o c e s s ( r e c e i v ep i dm s g ) t r u e m s g " h e l l o "

Tomaker e c e i v e blockingandwaitforarrivingmessages,usethefollowingform:
;w a i tu n t i lam e s s a g ec a nb er e a d ( u n t i l( r e c e i v ep i dm s g ) )

Thefunctionwillloopuntilamessagecanbereadfromthequeue. Inthesecondsyntax,thefunctionreturnsalistofallchildprocesseswithpendingmessagesfortheparentprocess:
;r e a dp e n d i n gm e s s a g e sf r o mc h i l dp r o c e s s e s ( d o l i s t( p i d( r e c e i v e ) ) ( r e c e i v ep i dm s g ) ( p r i n t l n" r e c e i v e dm e s s a g e :"m s g"f r o m : "p i d ) )

ThelistofchildprocessIDsreturnedby( r e c e i v e ) onlycontainsPIDsofprocesseswhichhaveunreadmessagesintheirsend queues.The( r e c e i v ep i dm s g ) statementnowcanbeissuednonblocking,becauseitalwaysisguaranteedtofindapending messageinachild'smessagequeue. Ther e c e i v e functionisnotavailableonWin32. Foramoredetaileddiscussionofthisfunctionandexamples,seethesendfunction.

ref

syntax:(refexpkeylist[funccompare[true]])
r e f searchesforthekeyexpressionexpkeyinlistandreturnsalistofintegerindicesoranemptylistifexpkeycannotbefound. r e f canworktogetherwithpushandpop,bothofwhichcanalsotakelistsofindices.

Bydefault,r e f checksifexpressionsareequal.Withfunccompare,morecomplexcomparisonfunctionscanbeused.The comparisonfunctioncanbeapreviouslydefinedfunction.Notethatthisfunctionalwaystakestwoarguments,evenifonlythe secondargumentisusedinsidethefunction. Whentheoptionalt r u e parameterispresent,theelementfoundisreturnedinsteadoftheindexvector.


;g e ti n d e xv e c t o r sf o rl i s te l e m e n t s ( s e t' p L i s t' ( ab( cd( x )e ) ) ) ( r e f' xp L i s t ) ( r e f' ( x )p L i s t ) ( 220 ) ( 22 )

;t h ek e ye x p r e s s i o ni si nav a r i a b l e ( s e t' p' ( cd( x )e ) ) ( r e fpp L i s tp ) ( 2 )

;i n d e x i n gu s i n gt h ev e c t o rr e t u r n e df r o mr e f ( s e t' v( r e f' ( x )p L i s t ) )( 22 ) ( p L i s tv )( x ) ;i fn o t h i n gi sf o u n d ,n i li sr e t u r n e d ( r e f' f o op l i s t ) n i l ;n o ts p e c i f y i n gac o m p a r i s o nf u n c t o ra s s u m e s= ( s e t' L' ( ab( cd( e )f ) ) ) ( r e f' eL ) ( r e f' eL= ) ( 220 ) ( 220 )

;ai st h ef i r s ts y m b o lw h e r eei sg r e a t e r ( r e f' eL> ) ( 0 ) ;r e t u r nt h ee l e m e n ti n s t e a do ft h ei n d e x ( r e f' eL>t r u e ) a ;u s ea na n o n y m o u sc o m p a r i s o nf u n c t i o n ( r e f' eL( f n( xy )( o r( =xy )( =y' d ) ) ) ) ( 21 )

( r e f' eL( f n( xy )( o r( =xy )( =y' d ) ) )t r u e )d

Thefollowingexampleshowstheuseofmatchandunifytoformulatesearchesthatareaspowerfulasregularexpressionsarefor strings:
( s e t' L' ( ( l3 )( a1 2 )( k5 )( a1 0 )( z2 2 ) ) ) ;u s em a t c ha sac o m p a r i s o nf u n c t i o n ( r e f' ( a? )Lm a t c h )( 1 ) ;u s eu n i f ya sac o m p a r i s o nf u n c t i o n ( s e t' L' (( ( ab )( cd ) )( ( ee )( fg ) )) ) ( r e f' ( XX )Lu n i f y ) ( 10 )

( r e f' ( Xg )Lu n i f y )

( 11 )

( r e f' ( Xg )Lu n i f yt r u e )( fg )

The' ( XX ) patternwithunifysearchesforalistpairwherethetwoelementsareequal.Theu n i f y pattern' ( Xg ) searchesfora listpairwiththesymbolg asthesecondmember.Thepatternsarequotedtoprotectthemfromevaluation. Passthelistasadefaultfunctor:


( s e t' C : C' ( ab( cd )ef ) ) ( r e f' dC ) ( 21 )

Thisissuitablewhenpassinglistsbyreferenceusingacontext.SeealsothechapterPassingdatabyreference. Seealsotherefallfunction,whichsearchesforalloccurrencesofakeyexpressioninanestedlist.

refall
syntax:(refallexpkeylist[funccompare[true]]) Workssimilarlytoref,butreturnsalistofallindexvectorsfoundforexpkeyinlist. Whentheoptionalt r u e parameterispresent,theelementsfoundisreturnedoftheindexvectors. Bydefault,r e f a l l checksifexpressionsareequal.Withfunccompare,morecomplexcomparisonfunctionscanbeused. Thesystemvariable$ c o u n t countsthenumberofelementsfound.
( s e t' L' ( abc( daf( aha ) )( ka( mna )( x ) ) ) ) ( r e f a l l' aL )( ( 0 )( 31 )( 330 )( 332 )( 41 )( 422 ) ) $ c o u n t6 ;t h ei n d e xv e c t o rr e t u r n e db yr e f a l lc a nb eu s e dt oi n d e xt h el i s t ( L' ( 31 ) )a ;m a p p e di m p l i c i ti n d e x i n go fL ( m a p' L( r e f a l l' aL ) )( aaaaaa ) ;w i t hc o m p a r i s o no p e r a t o r ( s e t' L' ( abc( df( hla ) )( ka( mn )( x ) ) ) ) ;n o ts p e c i f y i n gac o m p a r i s o nf u n c t o ra s s u m e s= ( r e f a l l' cL ) ( r e f a l l' cL= ) ( ( 2 ) ) ( ( 2 ) )

;l o o kf o ra l le l e m e n t sw h e r eci sg r e a t e r ( r e f a l l' cL> ) ( ( 0 )( 1 )( 322 )( 41 ) ) ( r e f a l l' cL>t r u e ) ( abaa ) ;u s ea na n o n y m o u sf u n c t i o nt oc o m p a r e ( r e f a l l' aL( f n( xy )( o r( =xy )( =y' k ) ) ) ) ( ( 0 )( 322 )( 40 )( 41 ) ) ;t h ek e yi sn i lb e c a u s et h ec o m p a r i s o nf u n c t i o no n l yl o o k sa tt h es e c o n da r g u m e n t ( r e f a l ln i lL( f n( xy )( >( l e n g t hy )2 ) ) )

( ( 3 )( 32 )( 4 ) ) ;d e f i n et h ec o m p a r i s o nf u n c t i o n sf i r s t ( d e f i n e( i s l o n g ?xy )( >( l e n g t hy )2 ) );t h exg e t so c c u p i e db y' n i l ( r e f a l ln i lLi s l o n g ? ) ( ( 3 )( 32 )( 4 ) )

( d e f i n e( i s i t o r dxy )( o r( =xy )( =y' d ) ) ) ( s e t' L' ( ab( cd( e )f ) )) ( r e f a l l' eLi s i t o r d ) ( ( 21 )( 220 ) )

Thecomparisonfunctioncanbeapreviouslydefinedfunction.Notethatthecomparisonfunctionalwaystakestwoarguments,even ifonlythesecondargumentisusedinsidethefunction(asintheexampleusingi s l o n g ? ). Usingthematchandunifyfunctions,listsearchescanbeformulatedthatareaspowerfulasregularexpressionsearchesarefor strings.


( s e t' L' ( ( l3 )( a1 2 )( k5 )( a1 0 )( z2 2 ) )) ;l o o kf o ra l lp a i r ss t a r i n gw i t ht h es y m b o la ( r e f a l l' ( a? )Lm a t c h ) ( ( 1 )( 3 ) ) ( r e f a l l' ( a? )Lm a t c ht r u e )( ( a1 2 )( a1 0 ) ) ;l o o kf o ra l lp a i r sw h e r ee l e m e n t sa r ee q u a l ( s e t' L' (( ( ab )( cd ) )( ( ee )( fg ) )( ( z )( z ) ) ) ) ( r e f a l l' ( XX )Lu n i f y ) ( ( 10 )( 2 ) ) ( r e f a l l' ( XX )Lu n i f yt r u e )( ( ee )( ( z )( z ) ) ) ;l o o kf o ra l lp a i r sw h e r et h es e c o n de l e m e n ti st h es y m b o lg ( s e t' L' (( ( xyz )g )( ( ab )( cd ) )( ( ee )( fg ) )) ) ( r e f a l l' ( Xg )Lu n i f y ) ( ( 0 )( 21 ) ) ( r e f a l l' ( Xg )Lu n i f yt r u e )( ( ( xyz )g )( fg ) )

Seealsothereffunction.

regex
syntax:(regexstrpatternstrtext[intoption[intoffset]]) PerformsaPerlCompatibleRegularExpression(PCRE)searchonstrtextwiththepatternspecifiedinstrpattern.Thesame regularexpressionpatternmatchingisalsosupportedinthefunctionsdirectory,find,findall,parse,replace,andsearchwhenusing thesefunctionsonstrings.
r e g e x returnsalistwiththematchedstringsandsubstringsandthebeginningandlengthofeachstringinsidethetext.Ifnomatchis

found,itreturnsn i l .Theoffsetnumberscanbeusedforsubsequentprocessing. Additionallyanintoptioncanbespecifiedtocontrolcertainregularexpressionoptionsexplainedlater.Theadditionalintoffset parametertellsr e g e x tostartsearchingforamatchnotatthebeginningofthestringbutatanoffset. Theoffsetandlengthnumbersinther e g e x resultsaregivenbasedonsinglebytesevenwhenrunningtheUTF8enabledversion ofnewLISP.


r e g e x alsosetsthevariables$ 0 ,$ 1 , and$ 2 totheexpressionandsubexpressionsfound.JustlikeanyothersymbolinnewLISP,

thesevariablesortheirequivalentexpressions( $0 ) ,( $1 ) , and( $2 ) canbeusedinothernewLISPexpressionsforfurther

processing. Functionsusingregularexpressionswillnotresetthe$ 0 ,$ 1. . .$ 1 5 variableston i l whennomatchisfound.


( r e g e x" b + "" a a a a b b b a a a a " ) ( " b b b "43 ) ;c a s e i n s e n s i t i v es e a r c ho p t i o n1 ( r e g e x" b + "" A A A A B B B A A A A "1 ) ( " B B B "43 ) ( r e g e x" [ b B ] + "" A A A A B b B A A A A ") ( " B b B "43 ) ( r e g e x" h t t p : / / ( . * ) : ( . * ) "" h t t p : / / n u e v a t e c . c o m : 8 0 " ) ( " h t t p : / / n u e v a t e c . c o m : 8 0 "02 2" n u e v a t e c . c o m "71 2" 8 0 "2 02 ) $ 0 " h t t p : / / n u e v a t e c . c o m : 8 0 " $ 1 " n u e v a t e c . c o m " $ 2 " 8 0 " ( d o t i m e s( i3 )( p r i n t l n( $i ) ) ) h t t p : / / n u e v a t e c . c o m : 8 0 n u e v a t e c . c o m 8 0 " 8 0 "

Thesecondexampleshowstheusageofextraoptions,whilethethirdexampledemonstratesmorecomplexparsingoftwo subexpressionsthatweremarkedbyparenthesesinthesearchpattern.Inthelastexample,theexpressionandsubexpressionsare retrievedusingthesystemvariables$ 0 to$ 2 ortheirequivalentexpression( $0 ) to( $2 ) . When" " (quotes)areusedtodelimitstringsthatincludeliteralbackslashes,thebackslashmustbedoubledintheregularexpression pattern.Asanalternative,{ } (curlybrackets)or[ t e x t ] and[ / t e x t ] (texttags)canbeusedtodelimittextstrings.Inthesecases, noextrabackslashesarerequired. CharactersescapedbyabackslashinnewLISP(e.g.,thequote\ " or\ n )neednottobedoubledinaregularexpressionpattern, whichitselfisdelimitedbyquotes.
; ;d o u b l eb a c k s l a s hf o rp a r e n t h e s e sa n do t h e rs p e c i a lc h a ri nr e g e x ( r e g e x" \ \ ( a b c \ \ ) "" x y z ( a b c ) x y z " ) ( " ( a b c ) "35 ) ; ;d o u b l eb a c k s l a s hf o rb a c k s l a s h( s p e c i a lc h a ri nr e g e x ) ( r e g e x" \ \ d { 1 , 3 } "" q w e r t y 5 6 7 a s d f g " ) ( " 5 6 7 "63 ) ; ;o n eb a c k s l a s hf o rq u o t e s( s p e c i a lc h a ri nn e w L I S P ) ( r e g e x" \ " "" a b c \ " d e f " ) ( " \ " "31 ) ; ;b r a c k e t sa sd e l i m i t e r s ( r e g e x{ \ ( a b c \ ) }" x y z ( a b c ) x y z " ) ( " ( a b c ) "35 ) ; ;b r a c k e t sa sd e l i m i t e r sa n dq u o t ei np a t t e r n ( r e g e x{ " }" a b c \ " d e f " ) ( " \ " "31 ) ; ;t e x tt a g sa sd e l i m i t e r s ,g o o df o rm u l t i l i n et e x ti nC G I ( r e g e x[ t e x t ] \ ( a b c \ ) [ / t e x t ]" x y z ( a b c ) x y z " ) ( " ( a b c ) "35 ) ( r e g e x[ t e x t ] " [ / t e x t ]" a b c \ " d e f " ) ( " \ " "31 )

Whencurlybracketsortexttagsareusedtodelimitthepatternstringinsteadofquotes,asimplebackslashissufficient.Thepattern andstringarethenpassedinrawformtotheregularexpressionroutines.Whencurlybracketsareusedinsideapatternitself delimitedbycurlybrackets,theinnerbracketsmustbebalanced,asfollows:


; ;b r a c k e t si n s i d eb r a c k e t sa r eb a l a n c e d ( r e g e x{ \ d { 1 , 3 } }" q w e r t y 5 6 7 a s d f g " ) ( " 5 6 7 "63 )

Thefollowingconstantscanbeusedforintoption.Severaloptionscanbecombinedusingabinaryor| (pipe)operator.E.g.( |1 4 ) wouldcombineoptions1 and4 .TheuppercasenamesareusedinthePCREregexdocumentationandcouldbepredefinedin i n i t . l s p .ThelastoptionisanewLISPcustomoptiononlytobeusedinreplaceitcanbecombinedwithPCREoptions. PCREname PCRE_CASELESS PCRE_MULTILINE no 1 2 description treatuppercaselikelowercase limitsearchatanewlinelikePerl's/m

PCRE_DOTALL PCRE_EXTENDED PCRE_ANCHORED

4 8 16

.(dot)alsomatchesnewline ignorewhitespaceexceptinsidecharclass anchoratthestart $matchesatendofstring,notbeforenewline additionalfunctionalitycurrentlynotused firstch,notstartofline^shouldn'tmatch lastchar,notendofline$shouldn'tmatch invertgreedinessofquantifiers emptystringconsideredinvalid

PCRE_DOLLAR_ENDONLY 32 PCRE_EXTRA 64 PCRE_NOTBOL PCRE_NOTEOL PCRE_UNGREEDY PCRE_NOTEMPTY PCRE_UTF8 REPLACE_ONCE PRECOMPILED 128 256 512 1024

2048 patternandstringsasUTF8characters 0x8000 replaceonlyoneoccurrenceonlyforuseinreplace 0x10000 patternisprecompiled,canonlybecombinedwithRREPLACE_ONCE0x8000

ThesettingsofthePCRE_CASELESS,PCRE_MULTILINE,PCRE_DOTALL,andPCRE_EXTENDEDoptionscanbe changedfromwithinthepatternbyasequenceofoptionlettersenclosedbetween"(?"and")".Theoptionlettersare: i forPCRE_CASELESS m forPCRE_MULTILINE s forPCRE_DOTALL x forPCRE_EXTENDED

Notethatregularexpressionsyntaxisverycomplexandfeaturerichwithmanyspecialcharactersandforms.Pleaseconsultabook orthePCREmanualpagesformoredetail.MostPERLbooksorintroductionstoLinuxorUnixalsocontainchaptersaboutregular expressions.Seealsohttp://www.pcre.orgforfurtherreferencesandmanualpages. Regularexpressionpatternscanbeprecompiledforhigherspeedwhenusingchangingrepetitivepatternswithregexcomp.

regexcomp
syntax:(regexcompstrpattern[intoption]) newLISPautomaticallycompilesregularexpressionpatternsandcachesthelastcompilationtospeeduprepetitivepatternsearches. Ifpatternschangefromonetothenext,butarerepeatedoverandoveragain,thenthecachingofthelastpatternisnotsufficient. r e g e x c o m p canbeusedtoprecompilerepetitivepatternstospeedupregularexpressionsearches:
;s l o w e rw i t h o u tp r e c o m p i l a t i o n ( d o l i s t( l i n ep a g e ) ( r e p l a c ep a t t e r n s t r 1l i n er e p l 10 ) ( r e p l a c ep a t t e r n s t r 2l i n er e p l 25 1 2 ) ) ;f a s tw i t hp r e c o m p i l a t i o na n do p t i o n0 x 1 0 0 0 0 ( s e t' p 1( r e g e x c o m pp a t t e r n s t r 1 ) ) ( s e t' p 2( r e g e x c o m pp a t t e r n s t r 25 1 2 ) ) ( d o l i s t( l i n ep a g e ) ( r e p l a c ep 1l i n er e p l 10 x 1 0 0 0 0 ) ( r e p l a c ep 2l i n er e p l 20 x 1 0 0 0 0 ) )

Whenusingprecompiledpatternsinanyofthefunctionsusingregularexpressions,theoptionnumberissetto0 x 1 0 0 0 0 tosignal thatprecompiledpatternsareused.Normalpatternoptionsarespecifiedduringprecompilationwithr e g e x c o m p .The0 x 1 0 0 0 0 optioncanonlybecombinedwith0 x 8 0 0 0 ,theoptionusedtospecifythatonlyonereplacementshouldbemadewhenusing replace. Thefunctionendswithshouldnotbeusedwithcompiledpatterns,asittriestoappendtoanuncompiledpatterninternally.

removedir
syntax:(removedirstrpath) Removesthedirectorywhosepathnameisspecifiedinstrpath.Thedirectorymustbeemptyforr e m o v e d i r tosucceed.Returns n i l onfailure.
( r e m o v e d i r" t e m p " )

Removesthedirectoryt e m p inthecurrentdirectory.

renamefile
syntax:(renamefilestrpatholdstrpathnew) Renamesafileordirectoryentrygiveninthepathnamestrpatholdtothenamegiveninstrpathnew.Returnsn i l ort r u e dependingontheoperation'ssuccess.
( r e n a m e f i l e" d a t a . l i s p "" d a t a . b a c k u p " )

replace!
syntax:(replaceexpkeylistexpreplacement[funccompare]) syntax:(replaceexpkeylist) syntax:(replacestrkeystrdataexpreplacement) syntax:(replacestrpatternstrdataexpreplacementintregexoption)

Listreplacement
Ifthesecondargumentisalist,r e p l a c e replacesallelementsinthelistlistthatareequaltotheexpressioninexpkey.Theelement isreplacedwithexpreplacement.Ifexpreplacementismissing,allinstancesofexpkeywillbedeletedfromlist. Notethatr e p l a c e isdestructive.Itchangesthelistpassedtoitandreturnsthechangedlist.Thenumberofreplacementsmadeis containedinthesystemvariable$ c o u n t whenthefunctionreturns.Duringexecutionsofthereplacementexpression,theanaphoric systemvariable$ i t issettotheexpressiontobereplaced. Optionally,funccomparecanspecifyacomparisonoperatororuserdefinedfunction.Bydefault,funccompareisthe= (equals sign).
; ;l i s tr e p l a c e m e n t

( s e t' a L i s t' ( abcdeabcd ) ) ( r e p l a c e' ba L i s t' B ) ( aBcdeaBcd ) a L i s t ( aBcdeaBcd ) $ c o u n t2 ;n u m b e ro fr e p l a c e m e n t s ; ;l i s tr e p l a c e m e n tw i t hs p e c i a lc o m p a r ef u n c t o r / f u n c t i o n ;r e p l a c ea l ln u m b e r sw h e r e1 0<n u m b e r ( s e t' L' ( 142 2568 9232 4 ) ) ( r e p l a c e1 0L1 0< )( 141 0561 0231 0 ) $ c o u n t3 ;s a m ea s : ( r e p l a c e1 0L1 0( f n( xy )( <xy ) ) )( 141 0561 0231 0 ) ;c h a n g en a m e s t r i n gt os y m b o l ,xi si g n o r e da sn i l ( s e t' A L' ( ( j o h n564 )( " m a r y "347 )( b o b4279 )( " j a n e "3 ) ) ) ( r e p l a c en i lA L( c o n s( s y m( $ i t0 ) )( r e s t$ i t ) ) ( f n( xy )( s t r i n g ?( y0 ) ) ) );p a r a m e t e rx=n i ln o tu s e d ( ( j o h n564 )( m a r y347 )( b o b4279 )( j a n e3 ) ) ;u s e$ c o u n ti nt h er e p l a c e m e n te x p r e s s i o n ( r e p l a c e' a' ( ababab )( l i s t$ c o u n t$ i t )= ) ( ( 1a )b( 2a )b( 3a )b )

Usingthematchandunifyfunctions,listsearchescanbeformulatedthatareaspowerfulasregularexpressionstringsearches:
;c a l c u l a t et h es u mi na l la s s o c i a t i o n sw i t h' m a r y ( s e t' A L' ( ( j o h n564 )( m a r y347 )( b o b4279 )( j a n e3 ) ) ) ( r e p l a c e' ( m a r y* ) A L( l i s t' m a r y( a p p l y+( r e s t$ i t ) ) )m a t c h ) ( ( j o h n564 )( m a r y1 4 )( b o b4279 )( j a n e3 ) ) $ c o u n t1 ;m a k es u mi na l le x p r e s s i o n s ( s e t' A L' ( ( j o h n564 )( m a r y347 )( b o b4279 )( j a n e3 ) ) ) ( r e p l a c e' ( * )A L( l i s t( $ i t0 )( a p p l y+( r e s t$ i t ) ) )m a t c h ) ( ( j o h n1 5 )( m a r y1 4 )( b o b2 2 )( j a n e3 ) ) $ c o u n t4 ;u s i n gu n i f y ,r e p l a c eo n l yi fe l e m e n t sa r ee q u a l ( r e p l a c e' ( XX )' ( ( 31 0 )( 25 )( 44 )( 67 )( 88 ) )( l i s t( $ i t0 )' d o u b l e( $ i t1 ) )u n i f y ) ( ( 31 0 )( 25 )( 4d o u b l e4 )( 67 )( 8d o u b l e8 ) )

Listremoval
Thelastformofr e p l a c e hasonlytwoarguments:theexpressionexpandlist.Thisformremovesallexpsfoundinlist.
; ;r e m o v i n ge l e m e n t sf r o mal i s t ( s e t' l s t' ( abaacdafg ) ) ( r e p l a c e' al s t ) ( bcdfg ) l s t ( bcdfg ) $ c o u n t4

Stringreplacementwithoutregularexpression
Ifallargumentsarestrings,r e p l a c e replacesalloccurrencesofstrkeyinstrdatawiththeevaluatedexpreplacement,returningthe changedstring.Theexpressioninexpreplacementisevaluatedforeveryreplacement.Thenumberofreplacementsmadeis containedinthesystemvariable$ c o u n t .Thisformofr e p l a c e canalsoprocessbinary0 s(zeros).

; ;s t r i n gr e p l a c e m e n t ( s e t' s t r" t h i si s as e n t e n c e " ) ( r e p l a c e" i s a "s t r" i sa " ) " t h i si sas e n t e n c e " $ c o u n t1

Regularexpressionreplacement
Thepresenceofafourthparameterindicatesthataregularexpressionsearchshouldbeperformedwitharegularexpressionpattern specifiedinstrpatternandanoptionnumberspecifiedinintoption(e.g.,1 (one)forcaseinsensitivesearchingor0 (zero)fora standardPerlCompatibleRegularExpression(PCRE)search).Seeregexabovefordetails. Bydefault,r e p l a c e replacesalloccurrencesofasearchstringevenifabeginningoflinespecificationisincludedinthesearch pattern.Aftereachreplace,anewsearchisstartedatanewpositioninstrdata.Settingtheoptionbitto0 x 8 0 0 0 inintoptionwill forcer e p l a c e toreplaceonlythefirstoccurrence.Thechangedstringisreturned.
r e p l a c e withregularexpressionsalsosetstheinternalvariables$ 0 ,$ 1 , and$ 2 withthecontentsoftheexpressionsand

subexpressionsfound.Theanaphoricsystemvariable$ i t issettothesamevalueas$ 0 .Thesecanbeusedtoperformreplacements thatdependonthecontentfoundduringreplacement.Thesymbols$ i t ,$ 0 ,$ 1 , and$ 2 canbeusedinexpressionsjustlikeany othersymbols.Ifthereplacementexpressionevaluatestosomethingotherthanastring,noreplacementismade.Asanalternative, thecontentsofthesevariablescanalsobeaccessedbyusing( $0 ) ,( $1 ) ,( $2 ) , andsoforth.Thismethodallowsindexed access(e.g.,( $i ) ,wherei isaninteger). Afterallreplacementsaremade,thenumberofreplacementsiscontainedinthesystemvariable$ c o u n t .
; ;u s i n gt h eo p t i o np a r a m e t e rt oe m p l o yr e g u l a re x p r e s s i o n s ( s e t' s t r" Z Z Z Z Z x Z Z Z Z y y " ) " Z Z Z Z Z x Z Z Z Z y y " ( r e p l a c e" [ x | y ] "s t r" P P "0 ) " Z Z Z Z Z P P Z Z Z Z P P P P " s t r " Z Z Z Z Z P P Z Z Z Z P P P P " ; ;u s i n gs y s t e mv a r i a b l e sf o rd y n a m i cr e p l a c e m e n t ( s e t' s t r" a x b a y b " ) ( r e p l a c e" ( a ) ( . ) ( b ) "s t r( a p p e n d$ 3$ 2$ 1 )0 ) " b x a b y a " s t r " b x a b y a " ; ;u s i n gt h e' r e p l a c eo n c e 'o p t i o nb i t0 x 8 0 0 0 ( r e p l a c e" a "" a a a "" X "0 ) " X X X " ( r e p l a c e" a "" a a a "" X "0 x 8 0 0 0 ) " X a a " ; ;U R Lt r a n s l a t i o no fh e xc o d e sw i t hd y n a m i cr e p l a c e m e n t ( s e t' s t r" x x x % 4 1 x x x % 4 2 " ) ( r e p l a c e" % ( [ 0 9 A F ] [ 0 9 A F ] ) "s t r ( c h a r( i n t( a p p e n d" 0 x "$ 1 ) ) )1 ) s t r " x x x A x x x B "

$ c o u n t2

Thesetffunctiontogetherwithnth,firstorlastcanalsobeusedtochangeelementsinalist. Seedirectory,find,findall,parse,regex,andsearchforotherfunctionsusingregularexpressions.

reset
syntax:(reset)

syntax:(resettrue) Inthefirstsyntax,r e s e t returnstothetoplevelofevaluation,switchesthetracemodeoff,andswitchestotheMAIN context/namespace.r e s e t restoresthetoplevelvariableenvironmentusingthesavedvariableenvironmentsonthestack.Italso firesanerror"userresetnoerror".Thisbehaviorcanbeusedwhenwritingerrorhandlers.


r e s e t mayreturnmemorythatwasclaimedbynewLISPtotheoperatingsystem.r e s e t walksthroughtheentirecellspace,which

maytakeafewsecondsinaheavilyloadedsystem.
r e s e t occursautomaticallyafteranerrorcondition.

Inthesecondsyntax,r e s e t willstopthecurrentprocessandstartanewcleannewLISPprocesswiththesamecommandline parameters.ThismodewillonlyworkwhennewLISPwasstartedusingitsfullpathname,e.g./ u s r / b i n / n e w l i s p insteadofonly n e w l i s p .ThismodeisnotavailableonWin32.

restutf8
syntax:(restlist) syntax:(restarray) syntax:(reststr) Returnsalloftheitemsinalistorastring,exceptforthefirst.r e s t isequivalenttocdrortailinotherLispdialects.
( r e s t' ( 1234 ) ) ( r e s t' ( ( ab )cd ) ) ( s e t' a L i s t' ( abcde ) ) ( r e s ta L i s t ) ( f i r s t( r e s ta L i s t ) ) ( r e s t( r e s ta L i s t ) ) ( r e s t( f i r s t' ( ( ab )cd ) ) ) ( 234 ) ( cd ) ( abcde ) ( bcde ) b ( de ) ( b )

( s e t' A( a r r a y23( s e q u e n c e16 ) ) ) ( ( 12 )( 34 )( 56 ) ) ( r e s tA ) ( ( 34 )( 56 ) ) ( r e s t' ( ) )( )

Inthesecondversion,r e s t returnsallbutthefirstcharacterofthestringstrinastring.
( r e s t" n e w L I S P " ) " e w L I S P " ( f i r s t( r e s t" n e w L I S P " ) ) " e "

Seealsothefirstandlastfunctions. Notethatanimplicitrestisavailableforlists.SeethechapterImplicitrestandslice. NotethatrestworksoncharacterboundariesratherthanbyteboundarieswhentheUTF8enabledversionofnewLISPisused.

reverse!
syntax:(reverselist) syntax:(reversestring) Inthefirstform,r e v e r s e reversesandreturnsthelist.Notethatr e v e r s e isdestructiveandchangestheoriginallist.

( s e t' l' ( 123456789 ) ) ( r e v e r s el ) ( 987654321 ) l ( 987654321 )

Inthesecondform,r e v e r s e isusedtoreversetheorderofcharactersinastring.
( s e t' s t r" n e w L I S P " ) ( r e v e r s es t r ) " P S I L w e n " s t r " P S I L w e n "

Seealsothesortfunction.

rotate!
syntax:(rotatelist[intcount]) syntax:(rotatestr[intcount]) Rotatesandreturnsthelistorstringinstr.Acountcanbeoptionallyspecifiedinintcounttorotatemorethanoneposition.Ifint countispositive,therotationistotherightifintcountisnegative,therotationistotheleft.Ifnointcountisspecified,r o t a t e rotates1totheright.r o t a t e isadestructivefunctionthatchangesthecontentsoftheoriginallistorstring.
( s e t' l' ( 123456789 ) ) ( r o t a t el ) ( 912345678 ) ( r o t a t el2 ) ( 789123456 ) l ( 789123456 ) ( r o t a t el3 ) ( 123456789 ) ( s e t' s t r" n e w L I S P " ) ( r o t a t es t r ) " P n e w L I S " ( r o t a t es t r3 ) " L I S P n e w " ( r o t a t es t r4 ) " n e w L I S P "

Whenworkingonastring,r o t a t e worksonbyteboundariesratherthancharacterboundaries.

round
syntax:(roundnumber[intdigits]) Roundsthenumberinnumbertothenumberofdigitsgiveninintdigits.Whendecimalsarebeingrounded,intdigitsisnegative.It ispositivewhentheintegerpartofanumberisbeingrounded. Ifintdigitsisomitted,thefunctionroundsto0 decimaldigits.
( r o u n d1 2 3 . 4 92 ) ( r o u n d1 2 3 . 4 91 ) ( r o u n d1 2 3 . 4 90 ) ( r o u n d1 2 3 . 4 9 ) ( r o u n d1 2 3 . 4 91 ) ( r o u n d1 2 3 . 4 92 ) 1 0 0 1 2 0 1 2 3 1 2 3 1 2 3 . 5 1 2 3 . 4 9

Notethatroundingfordisplaypurposesisbetteraccomplishedusingformat.

save
syntax:(savestrfile) syntax:(savestrfilesym1[sym2...]) Inthefirstsyntax,thes a v e functionwritesthecontentsofthenewLISPworkspace(intextualform)tothefilestrfile.s a v e isthe inversefunctionofl o a d .Usingl o a d onfilescreatedwiths a v e causesnewLISPtoreturntothesamestateaswhens a v e was originallyinvoked.Systemsymbolsstartingwiththe$ character(e.g.,$ 0 fromregularexpressionsor$ m a i n a r g s fromthe commandline),symbolsofbuiltinfunctionsandsymbolscontainingn i l arenotsaved. Inthesecondsyntax,symbolscanbesuppliedasarguments.Ifsymnissupplied,onlythedefinitionofthatsymbolissaved.Ifsym nevaluatestoacontext,allsymbolsinthatcontextaresaved.Morethanonesymbolcanbespecified,andsymbolsandcontext symbolscanbemixed.Whencontextsaresaved,systemvariablesandsymbolsstartingwiththe$ characterarenotsaved. Specifyingsystemsymbolsexplicitlycausesthemtobesaved. Eachsymbolissavedbymeansofasetstatementorifthesymbolcontainsalambdaorlambdamacrofunctionbymeansof defineordefinemacrostatements.
s a v e returnst r u e oncompletion. ( s a v e" s a v e . l s p " ) ( s a v e" / h o m e / m y s e l f / m y f u n c . L S P "' m y f u n c ) ( s a v e" f i l e : / / / h o m e / m y s e l f / m y f u n c . L S P "' m y f u n c ) ( s a v e" h t t p : / / a s i t e . c o m : 8 0 8 0 / / h o m e / m y s e l f / m y f u n c . L S P "' m y f u n c ) ( s a v e" m y c o n t e x t . l s p "' m y c o n t e x t ) ; ;m u l t i p l ea r g s ( s a v e" s t u f f . l s p "' a C o n t e x t' m y F u n c' $ m a i n a r g s' A c o n t e x t )

BecauseallcontextsymbolsarepartofthecontextM A I N ,savingM A I N savesallcontexts. SavingtoaURLwillcauseanHTTPPUTrequesttobesenttotheURL.Inthismode,s a v e canalsobeusedtopushprogram sourcetoremotenewLISPservernodes.Notethatadoublebackslashisrequiredwhenpathnamesarespecifiedrelativetotheroot directory.s a v e inH T T P modewillobservea60secondtimeout. Symbolsmadeusingsymthatareincompatiblewiththenormalsyntaxrulesforsymbolsareserializedusingasymstatementinstead ofasetstatement.
s a v e serializescontextsandsymbolsasifthecurrentcontextisM A I N .Regardlessofthecurrentcontext,s a v e willalwaysgenerate

thesameoutput. Seealsothefunctionsload(theinverseoperationofs a v e )andsource,whichsavessymbolsandcontextstoastringinsteadofafile.

search
syntax:(searchintfilestrsearch[boolflag[intoptions]]) Searchesafilespecifiedbyitshandleinintfileforastringinstrsearch.intfilecanbeobtainedfromapreviousopenfile.Afterthe search,thefilepointerispositionedatthebeginningortheendofthesearchedstringorattheendofthefileifnothingisfound. Bydefault,thefilepointerispositionedatthebeginningofthesearchedstring.Ifboolflagevaluatestot r u e ,thenthefilepointeris

positionedattheendofthesearchedstring. Inintoptions,theoptionsflagscanbespecifiedtoperformaPCREregularexpressionsearch.Seethefunctionregexfordetails.If intoptionsisnotspecifiedafaster,plainstringsearchisperformed.s e a r c h returnsthenewfilepositionorn i l ifnothingisfound. Whenusingtheregularexpressionoptionsflag,patternsfoundarestoredinthesystemvariables$ 0 to$ 1 5 .


( s e t' f i l e( o p e n" i n i t . l s p "" r e a d " ) ) ( s e a r c hf i l e" d e f i n e " ) ( p r i n t( r e a d l i n ef i l e )" \ n " ) ( c l o s ef i l e ) ( s e t' f i l e( o p e n" p r o g r a m . c "" r " ) ) ( w h i l e( s e a r c hf i l e" # d e f i n e( . * ) "t r u e0 )( p r i n t l n$ 1 ) ) ( c l o s ef i l e )

Thefilei n i t . l s p isopenedandsearchedforthestringd e f i n e andthelineinwhichthestringoccursisprinted. Thesecondexamplelooksforalllinesinthefilep r o g r a m . c whichstartwiththestring# d e f i n e andprintstherestofthelineafter thestring"#define". Forotherfunctionsusingregularexpressions,seedirectory,find,findall,parse,regex,andreplace.

seed
syntax:(seedintseed) Seedstheinternalrandomgeneratorthatgeneratesnumbersforamb,normal,rand,andrandomwiththenumberspecifiedinint seed.NotethattherandomgeneratorusedinnewLISPistheClibraryfunctionrand().AllrandomizingfunctionsinnewLISPare basedonthisfunction. Notethatthemaximumvalueforintseedislimitedto16or32bits,dependingontheoperatingsystemused.Internally,onlythe32 leastsignificantbitsarepassedtotherandomseedfunctionoftheOS.
( s e e d1 2 3 4 5 ) ( s e e d( t i m e o f d a y ) )

Afterusings e e d withthesamenumber,therandomgeneratorstartsthesamesequenceofnumbers.Thisfacilitatesdebugging whenrandomizeddataareinvolved.Usings e e d ,thesamerandomsequencescanbegeneratedoverandoveragain. Thesecondexampleisusefulforguaranteeingadifferentseedanytimetheprogramstarts.

self
syntax:(self[intindex...]) Thefunctions e l f accessesthetargetobjectofaFOOPmethod.Oneormoreintindexareusedtoaccesstheobjectmembers.s e l f issetbythe:colonoperator. Objectsreferencedwiths e l f aremutable:
( n e wC l a s s' C i r c l e ) ( d e f i n e( C i r c l e : m o v ed xd y )

( i n c( s e l f1 )d x ) ( i n c( s e l f2 )d y ) ) ( s e t' a C i r c l e( C i r c l e123 ) ) ( : m o v ea C i r c l e1 02 0 ) a C i r c l e( C i r c l e1 12 23 ) ;o b j e c t sc a nb ea n o n y m o u s ( s e t' c i r c l e s' ( ( C i r c l e123 )( C i r c l e456 ) ) ) ( : m o v e( c i r c l e s0 )1 02 0 ) ( : m o v e( c i r c l e s1 )1 02 0 ) c i r c l e s( ( C i r c l e1 12 23 )( C i r c l e1 42 56 ) )

SeealsothechapteraboutprogrammingwithFOOP:Functionalobjectorientedprogramming

seek
syntax:(seekintfile[intposition]) Setsthefilepointertothenewpositionintpositioninthefilespecifiedbyintfile.Thenewpositionisexpressedasanoffsetfrom thebeginningofthefile,0 (zero)meaningthebeginningofthefile.Ifnointpositionisspecified,s e e k returnsthecurrentposition inthefile.Ifintfileis0 (zero),onBSD,s e e k willreturnthenumberofcharactersprintedtoSTDOUT,andonLinuxandWin32,it willreturn1 .Onfailure,s e e k returnsn i l .Whenintpositionissetto1 ,s e e k setsthefilepointertotheendofthefile.
s e e k cansetthefilepositionpastthecurrentendofthefile.Subsequentwritingtothispositionwillextendthefileandfillunused

positionswithzero's.Theblocksofzerosarenotactuallyallocatedondisk,sothefiletakesuplessspaceandiscalledasparsefile.
( s e t' f i l e( o p e n" m y f i l e "" r e a d " ) ) 5 ( s e e kf i l e1 0 0 ) 1 0 0 ( s e e kf i l e ) 1 0 0 ( o p e n" n e w l i s p _ m a n u a l . h t m l "" r e a d " ) ( s e e kf i l e1 ) ;s e e kt oE O F 5 9 3 8 1 6 ( s e t' f l e( o p e n" l a r g e f i l e "" r e a d " ) ( s e e kf i l e3 0 0 0 0 0 0 0 0 0 0 ) 3 0 0 0 0 0 0 0 0 0 0

newLISPsupportsfilepositionnumbersupto9,223,372,036,854,775,807.

selectutf8
syntax:(selectlistlistselection) syntax:(selectlist[intindex_i...]) syntax:(selectstringlistselection) syntax:(selectstring[intindex_i...]) Inthefirsttwoforms,s e l e c t picksoneormoreelementsfromlistusingoneormoreindicesspecifiedinlistselectionortheint index_i.
( s e t' l s t' ( abcdefg ) ) ( s e l e c tl s t' ( 03253 ) ) ( adcfd )

( s e l e c tl s t' ( 210 ) ) ( fga ) ( s e l e c tl s t210 ) ( fga )

Inthesecondtwoforms,s e l e c t picksoneormorecharactersfromstringusingoneormoreindicesspecifiedinlistselectionorthe intindex_i.


( s e t' s t r" a b c d e f g " ) ( s e l e c ts t r' ( 03253 ) ) " a d c f d " ( s e l e c ts t r' ( 210 ) ) " f g a " ( s e l e c ts t r210 ) " f g a "

Selectedelementscanberepeatedanddonothavetoappearinorder,althoughthisspeedsupprocessing.Theorderinlistselection orintindex_icanbechangedtorearrangeelements.

semaphore
syntax:(semaphore) syntax:(semaphoreintid) syntax:(semaphoreintidintwait) syntax:(semaphoreintidintsignal) syntax:(semaphoreintid0) Asemaphoreisaninterprocesssynchronizationobjectthatmaintainsacountbetween0 (zero)andsomemaximumvalue.Usefulin controllingaccesstoasharedresource,asemaphoreissettosignaledwhenitscountisgreaterthanzeroandtononsignaledwhen itscountiszero. Asemaphoreiscreatedusingthefirstsyntax.ThisreturnsthesemaphoreID,anintegerusedsubsequentlyasintidwhenthe semaphorefunctioniscalled.Initially,thesemaphorehasavalueofzero,whichrepresentsthenonsignaledstate. Ifcallings e m a p h o r e withanegativevalueinintwaitcausesittobedecrementedbelowzero,thefunctioncallwillblockuntil anotherprocesssignalsthesemaphorewithapositivevalueinintsignal.Callstothesemaphorewithintwaitorintsignal effectivelytrytoincrementordecrementthesemaphorevaluebyapositiveornegativevaluespecifiedinintsignalorintwait. Becausethevalueofasemaphoremustneverfallbelowzero,thefunctioncallwillblockwhenthisisattempted(i.e.,asemaphore withavalueofzerowillblockuntilanotherprocessincreasesthevaluewithapositiveintsignal). Thesecondsyntaxisusedtoinquireaboutthevalueofasemaphorebycallings e m a p h o r e withtheintidonly.Thisformisnot availableonWin32. Supplying0 (zero)asthelastargumentwillreleasesystemresourcesforthesemaphore,whichthenbecomesunavailable.Any pendingwaitsonthissemaphoreinotherchildprocesseswillbereleased. OnWin32,onlyparentandchildprocessescanshareasemaphore.OnLinux/Unix,independentprocessescanshareasemaphore. Onfailurethes e m a p h o r e functionreturnsn i l .syserrorcanbeusedtoretrievetheerrornumberandtextfromtheunderlying operatingsystem. Thefollowingcodeexamplessummarizethedifferentsyntaxforms:
; ;i n i ts e m a p h o r e s ( s e m a p h o r e )

; ;a s s i g nas e m a p h o r et os i d ( s e t' s i d( s e m a p h o r e ) ) ; ;i n q u i r et h es t a t eo fas e m a p h o r e( n o to nW i n 3 2 ) ( s e m a p h o r es i d ) ; ;p u ts i ds e m a p h o r ei nw a i ts t a t e( 1 ) ( s e m a p h o r es i d1 ) ; ;r u ns i ds e m a p h o r ep r e v i o u s l yp u ti nw a i t( a l w a y s1 ) ( s e m a p h o r es i d1 ) ; ;r u ns i ds e m a p h o r ew i t hXt i m e sas k i p( b a c k w a r do rf o r w a r d )o nt h ef u n c t i o n ( s e m a p h o r es i dX ) ; ;r e l e a s es i ds e m a p h o r es y s t e m w i d e( a l w a y s0 ) ( s e m a p h o r es i d0 )

Thefollowingexampleshowssemaphorescontrollingachildprocess:
; ;c o u n t e rp r o c e s so u t p u ti nb o l d ( d e f i n e( c o u n t e rn ) ( p r i n t l n" c o u n t e rs t a r t e d " ) ( d o t i m e s( xn ) ( s e m a p h o r es i d1 ) ( p r i n t l nx ) ) ) ; ;h i te x t r a< e n t e r >t om a k et h ep r o m p tc o m eb a c k ; ;a f t e ro u t p u tt ot h ec o n s o l ef r o mt h ec o u n t e rp r o c e s s >( s e t' s i d( s e m a p h o r e ) ) >( s e m a p h o r es i d ) 0 >( f o r k( c o u n t e r1 0 0 ) ) c o u n t e rs t a r t e d >( s e m a p h o r es i d1 ) 0 >( s e m a p h o r es i d3 ) 1 2 3 >( s e m a p h o r es i d2 ) 4 5 >_

Afterthesemaphoreisacquiredins i d ,ithasavalueof0 (thenonsignaledstate).Whenstartingtheprocessc o u n t e r ,the semaphorewillblockaftertheinitialstartmessageandwillwaitinthesemaphorecall.The1 istryingtodecrementthesemaphore, whichisnotpossiblebecauseitsvalueisalreadyzero.Intheinteractive,mainparentprocess,thesemaphoreissignaledbyraising itsvalueby1 .Thisunblocksthesemaphorecallinthec o u n t e r process,whichcannowdecrementthesemaphorefrom1 to0 and executethep r i n t statement.Whenthesemaphorecallisreachedagain,itwillblockbecausethesemaphoreisalreadyinthewait (0 )state. Subsequentcallstos e m a p h o r e withnumbersgreaterthan1 givethec o u n t e r processanopportunitytodecrementthesemaphore severaltimesbeforeblocking. Morethanoneprocesscanparticipateincontrollingthesemaphore,justasmorethanonesemaphorecanbecreated.Themaximum numberofsemaphoresiscontrolledbyasystemwidekernelsettingonUnixlikeoperatingsystems. Usetheforkfunctiontostartanewprocessandthesharefunctiontoshareinformationbetweenprocesses.Foramore comprehensiveexampleofusings e m a p h o r e tosynchronizeprocesses,seethefilep r o d c o n s . l s p exampleinthee x a m p l e s directoryinthesourcedistribution,aswellastheexamplesandmodulesdistributedwithnewLISP.

send
syntax:(sendintpidexp) syntax:(send) Thes e n d functionenablescommunicationbetweenparentandchildprocessesstartedwithspawn.Parentprocessescansendand receivemessagestoandfromtheirchildprocessesandchildprocessescansendandreceivemessagestoandfromtheirparent process.Aproxytechniqueshownfurtherdownisemployedtocommunicatebetweenchildprocesspeers.s e n d andreceivedo notrequirelocksorsemaphores.Theyworkondualsendandreceivemessagequeues. Processesstartedusingforkorprocesscannotuses e n d andr e c e i v e messagefunctions.Insteadtheyshoulduseeithersharewith semaphoreorpipetocommunicate. Thes e n d functionisnotavailableonWin32. Inthefirstsyntaxs e n d isusedtosendamessagefromaparenttoachildprocessorachildtoaparentprocess. Thesecondsyntaxisonlyusedbyparentprocessestogetalistofallchildprocessesreadytoacceptmessagefromtheparentin theirreceivequeues.Ifachild'sreceivequeueisfull,itwillnotbepartofthelistreturnedbythe( s e n d ) statement. ThecontentofamessagemaybeanynewLISPexpressioneitheratomicorlistexpressions:booleanconstantsn i l andt r u e , integers,floatingpointnumbersorstrings,oranylistexpressioninvalidnewLISPsyntax.Thesizeofamessageisunlimited. Theexpparameterspecifiesthedatatobesenttotherecipientinintpid.Therecipientcanbeeitheraspawnedchildprocessofthe currentprocessortheparentprocess.Ifamessagequeueisfull,itcanbereadfromthereceivingend,butas e n d issuedontheother sideofthequeuewillfailandreturnn i l .
;c h i l dp r o c e s sd i s p a t c h i n gm e s s a g et op a r e n t ( s e t' p p i d( s y s i n f o4 ) );g e tp a r e n tp i d ( s e n dp p i d" h e l l o " );s e n dm e s s a g e

Thetargetedrecipientofthemessageistheparentprocess:
;p a r e n tp r o c e s sr e c e i v i n gm e s s a g ef r o mc h i l d ( r e c e i v ec h i l d p i dm s g )t r u e m s g " h e l l o "

Whenthes e n d queueisfull,s e n d willreturnn i l untilenoughmessagecontentisreadonthereceivingsideofthequeueandthe queueisreadytoacceptnewmessagesfroms e n d statements. Usingtheuntilloopingfunction,themessagestatementscanberepeateduntiltheyreturnavaluenotn i l .Thisway,nonblocking s e n d andr e c e i v e canbemadeblockinguntiltheysucceed:
;b l o c k i n gs e n d e r ( u n t i l( s e n dp i dm s g ) );t r u ea f t e rm e s s a g ei sq u e u e du p ;b l o c k i n gr e c e i v e r ( u n t i l( r e c e i v ep i dm s g ) );t r u ea f t e rm e s s a g ec o u l db er e a d

Thesenderstatementblocksuntilthemessagecouldbedepositedintherecipientsqueue. Ther e c e i v e statementblocksuntilanewmessagecanbefetchedfromthequeue. Astheu n t i l statementsinthisexamplelackbodyexpressions,thelastvalueoftheevaluatedconditionalexpressionisthereturn valueoftheu n t i l loop.

Blockingmessageexchange

Thefollowingcodeshowshowarecipientcanlistenforincomingmessages,andinturnhowasendercanretrytodeposita messageintoaqueue.Theexampleshows5childprocessesconstantlydeliveringstatusdatatoaparentprocesswhichwilldisplay thedata.Afterthreedatasetshavebeenread,theparentwillabortallchildprocessesandexit:


# ! / u s r / b i n / n e w l i s p ;c h i l dp r o c e s st r a n s m i t sr a n d o mn u m b e r s ( d e f i n e( c h i l d p r o c e s s ) ( s e t' p p i d( s y s i n f o4 ) );g e tp a r e n tp i d ( w h i l et r u e ( u n t i l( s e n dp p i d( r a n d1 0 0 ) ) ) ) ) ;p a r e n ts t a r t s5 c h i l dp r o c e s s e s ,l i s t e n sa n dd i s p l a y s ;t h et r u ef l a gi ss p e c i f i e dt oe n a b l es e n d / r e c e i v e ( d o t i m e s( i5 )( s p a w n' r e s u l t( c h i l d p r o c e s s )t r u e ) ) ( f o r( i13 ) ( d o l i s t( c p i d( s y n c ) );i t e r a t et h r up e n d i n gc h i l dP I D s ( u n t i l( r e c e i v ec p i dm s g ) ) ( p r i n t" p i d : "c p i d" > "( f o r m a t" % 2 d "m s g ) ) ) ( p r i n t l n ) ) ( a b o r t );c a n c e lc h i l d p r o c e s s e s ( e x i t )

Runningaboveexampleproducesthefollowingoutput:
p i d : 5 3 1 8 1 > 4 7 p i d : 5 3 1 8 0 > 6 1 p i d : 5 3 1 7 9 > 7 5 p i d : 5 3 1 7 8 > 3 9 p i d : 5 3 1 7 7 > 3 p i d : 5 3 1 8 1 > 5 9 p i d : 5 3 1 8 0 > 1 2 p i d : 5 3 1 7 9 > 2 0 p i d : 5 3 1 7 8 > 7 7 p i d : 5 3 1 7 7 > 4 7 p i d : 5 3 1 8 1 > 6 p i d : 5 3 1 8 0 > 5 6 p i d : 5 3 1 7 9 > 9 6 p i d : 5 3 1 7 8 > 7 8 p i d : 5 3 1 7 7 > 1 8

The( s y n c ) expressionreturnsalistofallchildPIDs,and( u n t i l( r e c e i v ec p i dm s g ) ) isusedtoforceawaituntilstatus messagesarereceivedforeachofthechildprocesses. Atimeoutmechanismcouldbepartofanu n t i l orw h i l e looptostopwaitingaftercertaintimehasexpired. Theexamplesshowmessagesflowingfromachildprocessestoaparentprocess,inthesamefashionmessagescouldflowintothe otherdirectionfromparenttochildprocesses.Inthatcasetheparentprocesswoulduse( s e n d ) toobtainalistofchildprocesses withplaceintheirmessagequeues.

Messagescontainingcodeforevaluation
ThemostpowerfulfeatureofthemessagefunctionsistheabilitytosendanynewLISPexpression,whichthencanbeevaluatedby therecipient.Therecipientusesevaltoevaluatethereceivedexpression.Symbolscontainedintheexpressionareevaluatedinthe receiversenvironment. Thefollowingexampleshowshowaparentprocessactslikeamessageproxy.Theparentreceivesmessagesfromachildprocess AandroutesthemtoasecondchildprocesswithIDB.Ineffectthisimplementsmessagesbetweenchildprocesspeers.The implementationreliesonthefactthattherecipientcanevaluateexpressionscontainedinmessagesreceived.Theseexpressionscan beanyvalidnewLISPstatements:
# ! / u s r / b i n / n e w l i s p ;s e n d e rc h i l dp r o c e s so ft h em e s s a g e ( s e t' A( s p a w n' r e s u l t ( b e g i n ( d o t i m e s( i3 ) ( s e t' p p i d( s y s i n f o4 ) ) / *t h es t a t e m e n ti nm s gw i l lb ee v a l u a t e di nt h ep r o x y* / ( s e t' m s g' ( u n t i l( s e n dB( s t r i n g" g r e e t i n g sf r o m"A ) ) ) ) ( u n t i l( s e n dp p i dm s g ) ) ) ( u n t i l( s e n dp p i d' ( b e g i n ( s l e e p1 0 0 );m a k es u r ea l le l s ei sp r i n t e d ( p r i n t l n" p a r e n te x i t i n g. . . \ n " )

( s e t' f i n i s h e dt r u e ) ) ) ) )t r u e ) ) ;r e c e i v e rc h i l dp r o c e s so ft h em e s s a g e ( s e t' B( s p a w n' r e s u l t ( b e g i n ( s e t' p p i d( s y s i n f o4 ) ) ( w h i l et r u e ( u n t i l( r e c e i v ep p i dm s g ) ) ( p r i n t l nm s g ) ( u n l e s s( =m s g( s t r i n g" g r e e t i n g sf r o m"A ) ) ( p r i n t l n" E R R O Ri np r o x ym e s s a g e :"m s g ) ) ) )t r u e ) ) ( u n t i lf i n i s h e d( i f( r e c e i v eAm s g )( e v a lm s g ) ) );p r o x yl o o p ( a b o r t ) ( e x i t )

ChildprocessA sendsthreemessagestoB .AsthiscannotbedonedirectlyA sendss e n d statementstotheparentforevaluation.The statement:


( u n t i l( s e n dp i d B( s t r i n g" g r e e t i n g sf r o m"A ) ) )

willbeevaluatedintheenvironmentoftheparentprocess.EvensothevariablesA andB areboundton i l inthesenderprocessA , intheparentprocesstheywillbeboundtothecorrectprocessIDnumbers. Aftersendingthethreemessages,thestatement:


( s e t' f i n i s h e dt r u e )

issenttotheparentprocess.Onceevaluated,itwillcausetheu n t i l looptofinish. Formoredetailsons e n d andr e c e i v e andmoreexamplesseetheCodePatternsdocument.

sequence
syntax:(sequencenumstartnumend[numstep]) Generatesasequenceofnumbersfromnumstarttonumendwithanoptionalstepsizeofnumstep.Whennumstepisomitted,the value1 (one)isassumed.Thegeneratednumbersareoftypeinteger(whennooptionalstepsizeisspecified)orfloatingpoint (whentheoptionalstepsizeispresent).
( s e q u e n c e1 05 ) ( 1 098765 ) ( s e q u e n c e010 . 2 ) ( 00 . 20 . 40 . 60 . 81 ) ( s e q u e n c e200 . 3 ) ( 21 . 71 . 41 . 10 . 80 . 50 . 2 )

Notethatthestepsizemustbeapositivenumber,evenifsequencingfromahighertoalowernumber. Usetheseriesfunctiontogenerategeometricsequences.

series
syntax:(seriesnumstartnumfactornumcount) syntax:(seriesexpstartfuncnumcount) Inthefirstsyntax,s e r i e s createsageometricsequencewithnumcountelementsstartingwiththeelementinnumstart.Each subsequentelementismultipliedbynumfactor.Thegeneratednumbersarealwaysfloatingpointnumbers.

Whennumcountislessthan1 ,thens e r i e s returnsanemptylist.


( s e r i e s225 ) ( s e r i e s11 . 26 ) ( s e r i e s1 00 . 94 ) ( s e r i e s001 0 ) ( s e r i e s9 915 ) ( 2481 63 2 ) ( 11 . 21 . 4 41 . 7 2 82 . 0 7 3 62 . 4 8 8 3 2 ) ( 1 098 . 17 . 2 9 ) ( 0000000000 ) ( 9 99 99 99 99 9 )

Inthesecondsyntax,s e r i e s usesafunctionspecifiedinfunctotransformthepreviousexpressionintothenextexpression:
;e m b e dt h ef u n c t i o nP h i :f ( x )=1/( 1+x ) ;s e ea l s oh t t p : / / e n . w i k i p e d i a . o r g / w i k i / G o l d e n _ r a t i o ( s e r i e s1( f n( x )( d i v( a d d1x ) ) )2 0 ) ( 10 . 50 . 6 6 6 6 6 6 60 . 60 . 6 2 50 . 6 1 5 3 8 4 60 . 6 1 9 0 4 70 . 6 1 7 6 4 7 00 . 6 1 8 1 8 1 8 0 . 6 1 7 9 7 7 50 . 6 1 8 0 5 5 50 . 6 1 8 0 2 5 70 . 6 1 8 0 3 7 10 . 6 1 8 0 3 2 70 . 6 1 8 0 3 4 4 0 . 6 1 8 0 3 3 80 . 6 1 8 0 3 4 00 . 6 1 8 0 3 3 90 . 6 1 8 0 3 3 90 . 6 1 8 0 3 3 9 ) ;p r e d e f i n et h ef u n c t i o n ( d e f i n e( o s c i l l a t ex ) ( i f( <x ) ( +( -x )1 ) ( -( +x1 ) ) ) ) ( s e r i e s1o s c i l l a t e2 0 ) ( 1234567891 01 11 21 31 41 51 61 71 81 92 0 ) ;a n yd a t at y p ei sa c c e p t e da sas t a r te x p r e s s i o n ( s e r i e s" a "( f n( c )( c h a r( i n c( c h a rc ) ) ) )5 )( " a "" b "" c "" d "" e " ) ;d e p e n d e n c yo ft h et w op r e v i o u sv a l u e si nt h i sf i b o n a c c ig e n e r a t o r ( l e t( x1 )( s e r i e sx( f n( y )( +x( s w a pyx ) ) )1 0 ) ) ( 123581 32 13 45 58 9 )

Thefirstexampleshowsaseriesconvergingtothegoldenratio,(foranystartingvalue).Thesecondexampleshowshowfunc canbedefinedpreviouslyforbetterreadabilityofthes e r i e s statement. Thes e r i e s functionalsoupdatestheinternallist$ i d x indexvalue,whichcanbeusedinsidefunc. Usethesequencefunctiontogeneratearithmeticsequences.

set!
syntax:(setsym1exp1[sym2exp2...]) Evaluatesbothargumentsandthenassignstheresultofexptothesymbolfoundinsym.Thes e t expressionreturnstheresultofthe assignment.Theassignmentisperformedbycopyingthecontentsoftherightsideintothesymbol.Theoldcontentsofthesymbol aredeleted.Anerrormessageresultswhentryingtochangethecontentsofthesymbolsn i l ,t r u e ,oracontextsymbol.s e t can takemultipleargumentpairs.
( s e t' x1 2 3 ) 1 2 3 ( s e t' x' y ) y ( s e tx" h e l l o " ) " h e l l o " y " h e l l o " ( s e t' a l i s t' ( 123 ) ) ( 123 )

( s e t' x1' y" h e l l o " ) " h e l l o " ;m u l t i p l ea r g u m e n t s x 1 y " h e l l o "

ThesymbolforassignmentcouldbetheresultfromanothernewLISPexpression:
( s e t' l s t' ( xyz ) ) ( xyz ) ( s e t( f i r s tl s t )1 2 3 ) 1 2 3 x 1 2 3

Symbolscanbesettolambdaorlambdamacroexpressions.Thisoperationisequivalenttousingdefineordefinemacro.
( s e t' d o u b l e( l a m b d a( x )( +xx ) ) ) ( l a m b d a( x )( +xx ) )

isequivalentto:
( d e f i n e( d o u b l ex )( +xx ) ) ( l a m b d a( x )( +xx ) )

isequivalentto:
( d e f i n ed o u b l e( l a m b d a( x )( +xx ) ) ) ( l a m b d a( x )( +xx ) )

Usetheconstantfunction(whichworkslikes e t )toprotectthesymbolfromsubsequentalteration.Usingthesetqorsetffunction eliminatestheneedtoquotethevariablesymbol.

setlocale
syntax:(setlocale[strlocale[intcategory]]) Reportsorswitchestoadifferentlocaleonyouroperatingsystemorplatform.Whenusedwithoutarguments,setlocalereportsthe currentlocalebeingused.Whenstrlocaleisspecified,setlocaleswitchestothelocalewithallcategoryoptionsturnedon (L C _ A L L ).Placinganemptystringinstrlocaleswitchestothedefaultlocaleusedonthecurrentplatform.
s e t l o c a l e returnseitherthecurrentlocalestringanddecimalpointstringinalistorn i l iftherequestedchangecouldnotbe

performed.
;r e p o r tc u r r e n tl o c a l e ( s e t l o c a l e ) ;s e td e f a u l tl o c a l eo fy o u rp l a t f o r ma n dc o u n t r y ;r e t u r nv a l u es h o w nw h e ne x e c u t i n go nG e r m a nM S W i n d o w s ( s e t l o c a l e" " ) ( " G e r m a n _ G e r m a n y . 1 2 5 2 "" , " ) ( a d d1 , 2 3 41 , 2 3 4 ) 2 , 4 6 8

Bydefault,newLISPifnotenabledforUTF8startsupwiththePOSIXCdefaultlocale.ThisguaranteesthatnewLISP's behaviorwillbeidenticalonanyplatformlocale.OnUTF8enabledversionsofnewLISPthelocaleofthecurrentplatformis chosen.


;a f t e rn o n U T F 8n e w L I S Ps t a r tu p ( s e t l o c a l e ) ( " C "" . " )

Inintcategory,integernumbersmaybespecifiedascategoryoptionsforfinetuningcertainaspectsofthelocale,suchasnumber display,datedisplay,andsoforth.Thenumbersusedvaryfromsystemtosystem.Theoptionsvalidonyourplatformcanbefound intheCincludefilel o c a l e . h .ThisfiledefinesconstantslikeL C _ A L L ,L C _ N U M E R I C , andL C _ M O N E T A R Y .Whens e t l o c a l e is usedwithouttheoptionnumber,itassumestheL C _ A L L option,whichturnsonalloptionsforthatlocale. Notethatthelocalealsocontrolsthedecimalseparatorinnumbers.ThedefaultClocaleusesthedecimaldot,butmostothersusea decimalcomma. Notethatusings e t l o c a l e doesnotchangethebehaviorofregularexpressionsinnewLISP.TolocalizethebehaviorofPCRE (PerlCompatibleRegularExpressions),newLISPmustbecompiledwithdifferentcharactertables.Seethefile,LOCALIZATION, inthenewLISPsourcedistributionfordetails. SeealsothechapterSwitchingthelocale.

setref!
syntax:(setrefexpkeylistexpreplacement[funccompare]) Searchesforexpkeyinlistandreplacesthefoundelementwithexpreplacement.Thelistcanbenested.Thesystemvariables$ i t containstheexpressionfoundandcanbeusedinexpreplacement.Thefunctionreturnsthenewmodifiedlist.
( s e t' d a t a' ( f r u i t s( a p p l e s1 2 34 4 )( o r a n g e s153 ) ) ) ( s e t r e f' a p p l e sd a t a' A p p l e s ) ( f r u i t s( A p p l e s1 2 34 4 )( o r a n g e s153 ) ) d a t a( f r u i t s( A p p l e s1 2 34 4 )( o r a n g e s153 ) ) ) d a t a couldbethecontextidentifierofadefaultfunctionforpassinglistsbyreference: ( s e t' d b : d b' ( f r u i t s( a p p l e s1 2 34 4 )( o r a n g e s153 ) ) ) ( d e f i n e( u p d a t ec tk e yv a l u e ) ( s e t r e fk e yc tv a l u e ) ) ( u p d a t ed b' a p p l e s' A p p l e s ) ( f r u i t s( A p p l e s1 2 34 4 )( o r a n g e s153 ) ) ( u p d a t ed b' o r a n g e s' O r a n g e s ) ( f r u i t s( A p p l e s1 2 34 4 )( O r a n g e s153 ) ) d b : d b( f r u i t s( A p p l e s1 2 34 4 )( O r a n g e s153 ) )

Forexamplesonhowtousefunccompareseesetrefall Forchangingalloccurrencesofanelementinalistusesetrefall.

setrefall!
syntax:(setrefallexpkeylistexpreplacement[funccompare]) Searchesforexpkeyinlistandreplaceseachinstanceofthefoundelementwithexpreplacement.Thelistcanbenested.The systemvariable$ i t containstheexpressionfoundandcanbeusedinexpreplacement.Thesystemvariable$ c o u n t containsthe numberofreplacementsmade.Thefunctionreturnsthenewmodifiedlist.
( s e t' d a t a' ( ( m o n d a y( a p p l e s2 03 0 )( o r a n g e s249 ) )( t u e s d a y( a p p l e s5 )( o r a n g e s3 21 ) ) ) ) ( s e t r e f a l l' a p p l e sd a t a" A p p l e s " ) ( ( m o n d a y( " A p p l e s "2 03 0 )( o r a n g e s249 ) )( t u e s d a y( " A p p l e s "5 )( o r a n g e s3 21 ) ) )

$ c o u n t2

Usingthedefaultfunctorinthe( l i s tk e y ) patternallowsthelisttobepassedbyreferencetoauserdefinedfunctioncontaininga s e t r e f a l l statement.Thiswouldresultinlessmemoryusageandhigherspeedsinwhendoingreplacementsinlargelists:


( s e t' d b : d b' ( ( m o n d a y( a p p l e s2 03 0 )( o r a n g e s249 ) )( t u e s d a y( a p p l e s5 )( o r a n g e s3 21 ) ) ) ) ( d e f i n e( f o oc t x ) ( s e t r e f a l l' a p p l e sc t x" A p p l e s " ) ) ( f o od b ) ( ( m o n d a y( " A p p l e s "2 03 0 )( o r a n g e s249 ) )( t u e s d a y( " A p p l e s "5 )( o r a n g e s3 21 ) ) )

Whenevaluating( f o od b ) ,thelistind b : d b willbepassedbyreferenceands e t r e f a l l willmakethechangesontheoriginal, notonacopyofd b : d b . Likewithfind,replace,refandrefall,complexsearchescanbeexpressedusingmatchorunifyinfunccompare:


( s e t' d a t a' ( ( m o n d a y( a p p l e s2 03 0 )( o r a n g e s249 ) )( t u e s d a y( a p p l e s5 )( o r a n g e s3 21 ) ) ) ) ( s e t r e f a l l' ( o r a n g e s* )d a t a( l i s t( f i r s t$ i t )( a p p l y+( r e s t$ i t ) ) )m a t c h ) (. . .( o r a n g e s1 5 ). . .( o r a n g e s3 3 ). . .)

Theexamplesumsallnumbersfoundinrecordsstartingwiththesymbolo r a n g e s .Thefounditemsappearin$ i t Seealsosetrefwhichreplacesonlythefirstelementfound.

setqsetf!
syntax:(setqplace1exp1[place2exp2...])
s e t q ands e t f workalikeinnewLISPandsetthecontentsofasymbol,list,arrayorstringorofalist,arrayorstringplace

reference.Likeset,s e t q ands e t f cantakemultipleargumentpairs.Althoughboths e t q ands e t f pointtothesamebuiltin functioninternally,throughoutthismanuals e t q isusedwhensettingasymbolreferenceands e t f isusedwhensettinglistorarray references.


( s e t qx1 2 3 ) 1 2 3 ;m u l t i p l ea r g u m e n t s ( s e t qx1y2z3 ) 3 x 1 y 2 z 3 ;w i t hn t ho ri m p l i c i ti n d i c e s ( s e t qL' ( ab( cd )efg ) ) ( s e t f( L1 )' B ) B ;o rt h es a m e ( s e t f( n t h1L )' B ) L ( aB( cd )efg ) ( s e t f( L20 )' C ) L ( s e t f( L2 )' X ) L C ( aB( Cd )efg ) ( ABXefg )

;w i t ha s s o c ( s e t qL' ( ( a1 )( b2 ) ) ) ( s e t f( a s s o c' bL )' ( b3 ) )( b3 )

( ( a1 )( b3 ) )

;w i t hl o o k u p ( s e t f( l o o k u p' bL )3 0 )3 0 L ( ( a1 )( b3 0 ) ) ;s e v e r a ll i s ta c c e s s o r sc a nb en e s t e d ( s e t qL' ( ( a1 )( b2 ) ) ) ( p u s h' b( s e t f( a s s o c' bl )' ( b4 ) ) )' b )b L ( ( a1 )( bb4 ) ) ) ;o ns t r i n g s ( s e t' s" N e w I S P " ) ( s e t f( s0 )" n " )" n " s" n e w I S P " ( s e t f( s3 )" L I " )" L I " s" n e w L I S P "

Oftenthenewvaluesetisdependentontheoldvalue.s e t f canusetheanaphoricsystemvariable$ i t torefertotheoldvalue insidethes e t f expression:


( s e t qL' ( ( a p p l e s4 )( o r a n g e s1 ) ) ) ( s e t f( L11 )( +$ i t1 ) )2 L ( s e t' s" N e w L I S P " ) ( s e t f( s0 )( l o w e r c a s e$ i t ) )" n " ) s" n e w L I S P " ( ( a p p l e s4 )( o r a n g e s2 ) )

sgn
syntax:(sgnnum) syntax:(sgnnumexp1[exp2[exp3]]) Inthefirstsyntax,thes g n functionisalogicalfunctionthatextractsthesignofarealnumberaccordingtothefollowingrules: x>0 :sgn(x)=1 x<0 :sgn(x)=1 x=0 :sgn(x)=0
( s g n3 . 5 ) 1 ( s g n0 ) 0 ( s g n1 2 3 ) 1

Inthesecondsyntax,theresultofevaluatingoneoftheoptionalexpressionsexp1,exp2,orexp3isreturned,insteadof1 ,0 ,or 1 .Ifexpnismissingforthecasetriggered,thenn i l isreturned.


( s g nx101 ) ( s g nx111 ) ( s g nxn i lt r u et r u e ) ( s g nx( a b sx )0 ) ;w o r k sl i k e( s g nx ) ;1f o rn e g a t i v exa l lo t h e r s1 ;n i lf o rn e g a t i v ee l s et r u e ;( a b sx )f o rx<0 ,0f o rx=0 ,e l s en i l

Anyexpressionorconstantcanbeusedforexp1,exp2,orexp3.

share
syntax:(share) syntax:(shareintaddressorhandle) syntax:(shareintaddressorhandleexpvalue) syntax:(sharenilintaddress) AccessessharedmemoryforcommunicatingbetweenseveralnewLISPprocesses.Whencalledwithoutarguments,s h a r e requests apageofsharedmemoryfromtheoperatingsystem.ThisreturnsamemoryaddressonLinux/UnixandahandleonWin32,which canthenbeassignedtoavariableforlaterreference.ThisfunctionisnotavailableonOS/2. Tosetthecontentsofsharedmemory,usethethirdsyntaxofs h a r e .SupplyasharedmemoryaddressonLinux/Unixorahandle onWin32inintaddressorhandle,alongwithaninteger,float,stringexpressionoranyotherexpression(sincev.10.1.0)supplied inexpvalue.Usingthissyntax,thevaluesuppliedinexpvalueisalsothereturnvalue. Toaccessthecontentsofsharedmemory,usethesecondsyntaxofs h a r e ,supplyingonlythesharedmemoryaddressorhandle. Thereturnvaluewillbeanyconstantorexpression(sincev.10.1.0)writtenpreviouslyintothememory.Ifthememoryhasnotbeen previouslysettoavalue,n i l willbereturned. OnlyavailableonUnixlikeoperatingsystems,thelastsyntaxunmapsasharedmemoryaddress.Notethatusingasharedaddress afterunmappingitwillcrashthesystem. Memorycanbesharedbetweenparentandchildprocesses,butnotbetweenindependentprocesses. Sincev.10.1.0sizeofshareobjectscanexceedthesharedmemorypagesizeoftheoperatingsystem.Forobjectsbiggerthanthe pagesize,newLISPinternallyusesfilesforsharing.Thisrequiresa/ t m p directoryonUnixlikeoperatingsystemandat e m p directoryintherootofthecurrentdiskdriveonWin32systems.OnUnixlikesystemsthisdirectoryispresent,onWin32itmay havetobecreated.
( s e t' m e m( s h a r e ) ) ( s h a r em e m1 2 3 ) 1 2 3 ( s h a r em e m ) 1 2 3 ( s h a r em e m" h e l l ow o r l d " )" h e l l ow o r l d " ( s h a r em e m ) " h e l l ow o r l d " ( s h a r em e mt r u e ) t r u e ( s h a r em e m ) t r u e ( s h a r em e m' ( +1234 ) ) ( +1234 ) ( s h a r em e m ) ( +1234 ) ;e x p r e s s i o n sr e c e i v e dc a nb ee v a l u a t e d( s i n c ev . 1 0 . 1 . 0 ) ( e v a l( s h a r em e m ) ) 1 0 ( s h a r en i lm e m ) t r u e ;u n m a po n l yo nU n i x

Expressionreadfromsharedmemoryandevaluated,willbeevaluatedintherecipient'sprocessenvironment. Notethatsharedmemoryaccessbetweendifferentprocessesshouldbesynchronizedusingasemaphore.Simultaneousaccessto sharedmemorycancrashtherunningprocess. ForamorecomprehensiveexampleofusingsharedmemoryinamultiprocessLinux/Unixapplication,seethefile e x a m p l e / p r o d c o n s . l s p inthenewLISPsourcedistribution.

signal

syntax:(signalintsignalsymeventhandler|funceventhandler) syntax:(signalintsignal"ignore"|"default"|"reset") syntax:(signalintsignal) Setsauserdefinedhandlerinsymeventhandlerforasignalspecifiedinintsignalorsetstoafunctionexpressioninfuncevent handler. Aparameterfollowingintsignalisnotevaluated. Ifnosignalhandlerisspecifiedanyofthestringconstants" i g n o r e " ," d e f a u l t " or" r e s e t " canbespecifiedineitherloweror uppercaseorsimplyusingthefirstletteroftheoptionstring.Whensignalsetupwithanyofthesethreeoptionshasbeensuccessful, t r u e isreturned. Using" i g n o r e " willmakenewLISPignorethesignal.Using" d e f a u l t " willsetthehandlertothedefaulthandlerofthe underlyingplatformOS.The" r e s e t " optionwillrestorethehandlertonewLISPstartupstate. Onstartup,newLISPeitherspecifiesanemptynewLISPhandleroraCtrlChandlerforS I G I N T andaw a i t p i p d ( 1 ,0 , W N O H A N G ) CcallforS I G C H L D . DifferentsignalsareavailableondifferentOSplatformsandLinux/Unixflavors.Thenumberstospecifyinintsignalalsodiffer fromplatformtoplatform.Validvaluescannormallybeextractedfromafilefoundin/ u s r / i n c l u d e / s y s / s i g n a l . h or / u s r / i n c l u d e / s i g n a l . h . SomesignalsmakenewLISPexitevenafterauserdefinedhandlerhasbeenspecifiedandexecuted(e.g.,signalSIGKILL).This behaviormayalsobedifferentondifferentplatforms.
( c o n s t a n t' S I G I N T2 ) ( d e f i n e( c t r l C h a n d l e r )( p r i n t l n" c t r l Ch a sb e e np r e s s e d " ) ) ( s i g n a lS I G I N T' c t r l C h a n d l e r ) ;n o wp r e s sc t r l C ;t h ef o l l o w i n gl i n ew i l la p p e a r ;t h i sw i l lo n l yw o r ki na ni n t e r a c t i v et e r m i n a lw i n d o w ;a n dw i l ln o tw o r ki nt h en e w L I S P G Se d i t o r c t r l Ch a sb e e np r e s s e d ;r e s e tt r e a t m e n to fs i g n a l2t os t a r t u pc o n d i t i o n s ( s i g n a lS I G I N T" r e s e t " )

OnWin32,theaboveexamplewouldexecutethehandlerbeforeexitingnewLISP.OnmostLinux/Unixsystems,newLISPwould stayloadedandthepromptwouldappearafterhittingthe[enter]key. Insteadofspecifyingasymbolcontainingthesignalhandler,afunctioncanbespecifieddirectly.Thesignalnumberispassedasa parameter:


( s i g n a lS I G I N Te x i t ) $ s i g n a l 2 ( s i g n a lS I G I N T( f n( s )( p r i n t l n" s i g n a l"s"o c c u r r e d " ) ) )

NotethatthesignalSIGKILL(9onmostplatforms)willalwaysterminatetheapplicationregardlessofanexistingsignalhandler. Thesignalcouldhavebeensentfromanothershellonthesamecomputer:
k i l lsS I G I N T2 0 3 5

Inthisexample,2 0 3 5 istheprocessIDoftherunningnewLISP. ThesignalcouldalsohavebeensentfromanothernewLISPapplicationusingthefunctiondestroy:


( d e s t r o y2 0 3 5 )t r u e

IfnewLISPreceivesasignalwhileevaluatinganotherfunction,itwillstillacceptthesignalandthehandlerfunctionwillbe executed:
( c o n s t a n t' S I G I N T2 ) ( d e f i n e( c t r l C h a n d l e r )( p r i n t l n" c t r l Ch a sb e e np r e s s e d " ) ) ( s i g n a lS I G I N T' c t r l C h a n d l e r ) ; ;o r ( s i g n a lS I G I N Tc t r l C h a n d l e r ) ( w h i l et r u e( s l e e p3 0 0 )( p r i n t l n" b u s y " ) ) ; ;g e n e r a t e sf o l l o w i n go u t p u t b u s y b u s y b u s y c t r l Ch a sb e e np r e s s e d b u s y b u s y

Specifyingonlyasignalnumberwillreturneitherthenameofthecurrentlydefinedhandlerfunctionorn i l . Theuserdefinedsignalhandlercanpassthesignalnumberasaparameter.
( d e f i n e( s i g n a l h a n d l e rs i g ) ( p r i n t l n" r e c e i v e ds i g n a l :"s i g ) ) ; ;s e ta l ls i g n a l sf r o m1t o8t ot h es a m eh a n d l e r ( f o r( s18 ) ( s i g n a ls' s i g n a l h a n d l e r ) )

Inthisexample,allsignalsfrom1to8aresettothesamehandler.

silent
syntax:(silent[exp1[exp2...]]) Evaluatesoneormoreexpressionsinexp1.s i l e n t issimilartobegin,butitsuppressesconsoleoutputofthereturnvalueand thefollowingprompt.ItisoftenusedwhencommunicatingfromaremoteapplicationwithnewLISP(e.g.,GUIfrontendsorother applicationscontrollingnewLISP),andthereturnvalueisofnointerest. Silentmodeisresetwhenreturningtoaprompt.Thisway,itcanalsobeusedwithoutargumentsinabatchofexpressions.Whenin interactivemode,hit[enter]twiceafterastatementusings i l e n t togetthepromptback.
( s i l e n t( m y f u n c ) ) ;s a m ea sn e x t ( s i l e n t )( m y f u n c ) ;s a m ee f f e c ta sp r e v i o u s

sin
syntax:(sinnumradians) Calculatesthesinefunctionfromnumradiansandreturnstheresult.
( s i n1 ) 0 . 8 4 1 4 7 0 9 8 3 8 ( s e t' p i( m u l2( a c o s0 ) ) ) 3 . 1 4 1 5 9 2 6 5 4

( s i n( d i vp i2 ) )

sinh
syntax:(sinhnumradians) Calculatesthehyperbolicsineofnumradians.Thehyperbolicsineisdefinedmathematicallyas:(exp(x)exp(x))/2.An overflowtoi n f mayoccurifnumradiansistoolarge.
( s i n h1 ) 1 . 1 7 5 2 0 1 1 9 4 ( s i n h1 0 ) 1 1 0 1 3 . 2 3 2 8 7 ( s i n h1 0 0 0 ) i n f ( s u b( t a n h1 )( d i v( s i n h1 )( c o s h1 ) ) )0

sleep
syntax:(sleepnummilliseconds) GivesupCPUtimetootherprocessesfortheamountofmillisecondsspecifiedinnummilliseconds.
( s l e e p1 0 0 0 ) ;s l e e p s1s e c o n d ( s l e e p0 . 5 ) ;s l e e p s5 0 0m i c r os e c o n d s

Onsomeplatforms,s l e e p isonlyavailablewitharesolutionofonesecond.Inthiscase,theparameterintmillisecondswillbe roundedtothenearestfullsecond.

slice
syntax:(slicelistintindex[intlength]) syntax:(slicearrayintindex[intlength]) syntax:(slicestrintindex[intlength]) Inthefirstform,s l i c e copiesasublistfromalist.Theoriginallistisleftunchanged.Thesublistextractedstartsatindexintindex andhasalengthofintlength.Ifintlengthisnegative,s l i c e willtaketheparameterasoffsetcountingfromtheendandcopyupto thatoffset.Iftheparameterisomitted,s l i c e copiesalloftheelementstotheendofthelist. SeealsoIndexingelementsofstringsandlists.
( s l i c e' ( abcdef )32 ) ( s l i c e' ( abcdef )22 ) ( s l i c e' ( abcdef )2 ) ( s l i c e' ( abcdef )43 ) ( de ) ( cd ) ( cdef ) ( cde )

( s e t' A( a r r a y32( s e q u e n c e16 ) ) )( ( 12 )( 34 )( 56 ) ) ( s l i c eA12 )( ( 34 )( 56 ) )

Inthesecondform,apartofthestringinstrisextracted.intindexcontainsthestartindexandintlengthcontainsthelengthofthe substring.Ifintlengthisnotspecified,everythingtotheendofthestringisextracted.s l i c e alsoworksonstringbufferscontaining binarydatalike0 's(zeroes).Itoperatesonbyteboundariesratherthancharacterboundaries.SeealsoIndexingelementsofstrings andlists.

Notethats l i c e alwaysworksonsingle8bitbyteboundariesforoffsetandlengthnumbers,evenwhenrunningtheUTF8 enabledversionofnewLISP.


( s l i c e" H e l l oW o r l d "62 ) ( s l i c e" H e l l oW o r l d "05 ) ( s l i c e" H e l l oW o r l d "6 ) ( s l i c e" n e w L I S P "42 ) " W o " " H e l l o " " W o r l d " " L I "

Notethatanimplicitsliceisavailableforlists.SeethechapterImplicitrestandslice. BeawarethatslicealwaysworksonbyteboundariesratherthancharacterboundariesintheUTF8enabledversionofnewLISP. Asaresult,slicecanbeusedtomanipulatebinarycontent.

sort!
syntax:(sortlist[funccompare]) syntax:(sortarray[funccompare]) Allmembersinlistorarrayaresortedinascendingorder.Anythingmaybesorted,regardlessofthetypes.Whenmembersare themselveslistsorarrays,eachelementisrecursivelycompared.Iftwoexpressionsofdifferenttypesarecompared,thelowertype issortedbeforethehighertypeinthefollowingorder:
A t o m s :n i l ,t r u e ,i n t e g e ro rf l o a t ,s t r i n g ,s y m b o l ,p r i m i t i v e L i s t s :q u o t e de x p r e s s i o n ,l i s t ,l a m b d a ,l a m b d a m a c r o

Thes o r t isdestructive,changingtheorderoftheelementsintheoriginallistorarrayandreturningthesortedlistorarray.Itisa stablebinarymergesortwithapproximatelyO(nlog2n)performancepreservingtheorderofadjacentelementswhichareequal. Whenfunccompareisuseditmustworkwitheither< = or> = operatorstobestable. Anoptionalcomparisonoperator,userdefinedfunction,oranonymousfunctioncanbesupplied.Thefunctororoperatorcanbe givenwithorwithoutaprecedingquote.


( s o r t' ( vfrthnmj ) ) ( fhjmnrtv ) ( s o r t' ( ( 34 )( 21 )( 11 0 ) ) ) ( ( 11 0 )( 21 )( 34 ) ) ( s o r t' ( ( 34 )" h i "2 . 88b ) ) ( 2 . 88" h i "b( 34 ) ) ( s e t' s' ( kals ) ) ( s o r ts ) ( akls ) ( s o r t' ( vfrthnmj )> )( vtrnmjhf ) ( s o r ts< ) ( akls ) ( s o r ts> ) ( slka ) s ( slka ) ; ;d e f i n eac o m p a r i s o nf u n c t i o n ( d e f i n e( c o m pxy ) ( > =( l a s tx )( l a s ty ) ) ) ( s e t' d b' ( ( a3 )( g2 )( c5 ) ) ) ( s o r td bc o m p ) ( ( c5 )( a3 )( g2 ) ) ; ;u s ea na n o n y m o u sf u n c t i o n ( s o r td b( f n( xy )( > =( l a s tx )( l a s ty ) ) ) )

source

syntax:(source) syntax:(sourcesym1[sym2...]) Worksalmostidenticallytosave,exceptsymbolsandcontextsgetserializedtoastringinsteadofbeingwrittentoafile.Multiple variablesymbols,definitions,andcontextscanbespecified.Ifnoargumentisgiven,s o u r c e serializestheentirenewLISP workspace.Whencontextsymbolsareserialized,anysymbolscontainedwithinthatcontextwillbeserialized,aswell.Symbols containingn i l arenotserialized.Systemsymbolsbeginningwiththe$ (dollarsign)characterareonlyserializedwhenmentioned explicitly. Symbolsnotbelongingtothecurrentcontextarewrittenoutwiththeircontextprefix.
( d e f i n e( d o u b l ex )( +xx ) ) ( s o u r c e' d o u b l e ) " ( d e f i n e( d o u b l ex ) \ n ( +xx ) ) \ n \ n "

Aswithsave,theformattingoflinebreaksandleadingspacesortabscanbecontrolledusingtheprettyprintfunction.

spawn
syntax:(spawnsymexp[true]) Launchestheevaluationofexpasachildprocessandimmediatelyreturns.Thesymbolinsymisquotedandreceivestheresultof theevaluationwhenthefunctionsyncisexecuted.s p a w n isusedtostartparallelevaluationofexpressionsinconcurrentprocesses. IfnewLISPisrunningonamulticoreCPU,theunderlyingoperatingsystemwilldistributespawnedprocessesontodifferentcores, therebyevaluatingexpressionsinparallelandspeedingupoverallprocessing. Theoptionalt r u e parametermustbesetifsendorreceiveisusedtocommunicatedwiththechildprocessspawned. Thefunctions p a w n isnotavailableonWin32. Aftersuccessfullystartingachildprocess,thes p a w n expressionreturnstheprocessidoftheforkedprocess.Thefollowing examplesshowshowthecalculationofarangeofprimenumberscanbesplitupinfoursubrangestospeedupthecalculationof thewholerange:
;c a l c u l a t ep r i m e si nar a n g e ( d e f i n e( p r i m e sf r o mt o ) ( l o c a l( p l i s t ) ( f o r( if r o mt o ) ( i f( =1( l e n g t h( f a c t o ri ) ) ) ( p u s hip l i s t1 ) ) ) p l i s t ) ) ;s t a r tc h i l dp r o c e s s e s ( s e t' s t a r t( t i m e o f d a y ) ) ( s p a w n' p 1( p r i m e s11 0 0 0 0 0 0 ) ) ( s p a w n' p 2( p r i m e s1 0 0 0 0 0 12 0 0 0 0 0 0 ) ) ( s p a w n' p 3( p r i m e s2 0 0 0 0 0 13 0 0 0 0 0 0 ) ) ( s p a w n' p 4( p r i m e s3 0 0 0 0 0 14 0 0 0 0 0 0 ) ) ;w a i tf o ram a x i m u mo f6 0s e c o n d sf o ra l lt a s k st of i n i s h ( s y n c6 0 0 0 0 );r e t u r n st r u ei fa l lf i n i s h e di nt i m e ;p 1 ,p 2 ,p 3a n dp 4n o we a c hc o n t a i nal i s t so fp r i m e s ( p r i n t l n" t i m es p a w n :"( -( t i m e o f d a y )s t a r t ) ) ( p r i n t l n" t i m es i m p l e :"( t i m e ( p r i m e s14 0 0 0 0 0 0 ) ) ) ( e x i t )

Ona1.83IntelCore2Duoprocessor,theaboveexamplewillfinishafterabout13seconds.Calculatingallprimesusing( p r i m e s 14 0 0 0 0 0 0 ) wouldtakeabout20seconds.

Thesyncfunctionwillwaitforallchildprocessestofinishandreceivetheevaluationresultsinthesymbolsp 1 top 4 .Whenall resultsarecollected,s y n c willstopwaitingandreturnt r u e .Whenthetimespecifiedwasinsufficient,s y n c willreturnn i l and anothers y n c statementcouldbegiventofurtherwaitandcollectresults.Ashorttimeouttimecanbeusedtodootherprocessing duringwaiting:
( s p a w n' p 1( p r i m e s11 0 0 0 0 0 0 ) ) ( s p a w n' p 2( p r i m e s1 0 0 0 0 0 12 0 0 0 0 0 0 ) ) ( s p a w n' p 3( p r i m e s2 0 0 0 0 0 13 0 0 0 0 0 0 ) ) ( s p a w n' p 4( p r i m e s3 0 0 0 0 0 14 0 0 0 0 0 0 ) ) ;p r i n tad o ta f t e re a c h2s e c o n d so fw a i t i n g ( u n t i l( s y n c2 0 0 0 )( p r i n t l n" . " ) ) s y n c whenusedwithoutanyparameters,willnotwaitbutimmediatelyreturnalistofpendingchildprocesses.Forthep r i m e s

example,thefollowings y n c expressioncouldbeusedtowatchtheprogress:
( s p a w n' p 1( p r i m e s11 0 0 0 0 0 0 ) ) ( s p a w n' p 2( p r i m e s1 0 0 0 0 0 12 0 0 0 0 0 0 ) ) ( s p a w n' p 3( p r i m e s2 0 0 0 0 0 13 0 0 0 0 0 0 ) ) ( s p a w n' p 4( p r i m e s3 0 0 0 0 0 14 0 0 0 0 0 0 ) ) ;s h o wal i s to fp e n d i n gp r o c e s si d sa f t e re a c ht h r e e t e n t h so fas e c o n d ( u n t i l( s y n c3 0 0 )( p r i n t l n( s y n c ) ) )

Aparameterof1 tellss y n c towaitforaverylongtime(~1193hours).Abettersolutionwouldbetowaitforamaximumtime, thenabortallpendingchildprocesses:


( s p a w n' p 1( p r i m e s11 0 0 0 0 0 0 ) ) ( s p a w n' p 2( p r i m e s1 0 0 0 0 0 12 0 0 0 0 0 0 ) ) ( s p a w n' p 3( p r i m e s2 0 0 0 0 0 13 0 0 0 0 0 0 ) ) ( s p a w n' p 4( p r i m e s3 0 0 0 0 0 14 0 0 0 0 0 0 ) ) ;w a i tf o ro n em i n u t e ,t h e na b o r ta n d ;r e p o r tu n f i n i s h e dP I D s ( i f( n o t( s y n c6 0 0 0 0 ) ) ( b e g i n ( p r i n t l n" a b o r t i n gu n f i n i s h e d :"( s y n c ) ) ( a b o r t ) ) ( p r i n t l n" a l lf i n i s h e ds u c c e s s f u l l y " ) )

Thethreefunctionss p a w n ,s y n c anda b o r t arepartoftheCilkAPI.Theoriginalimplementationalsodoessophisticated schedulingandallocationofthreadedtaskstomultipleCPUcores.ThenewLISPimplementationoftheCilkAPIletstheoperating systemoftheunderlyingplatformhandleprocessmanagement.Internally,theAPIisimplementedusingtheUnixlibcfunctions f o r k ( ) ,w a i t p i d ( ) andk i l l ( ) .Intercommunicationsbetweenprocessesandchildprocessesisdoneusingthesendandreceive functions.


s p a w n canbecalledrecursivelyfromspawnedsubtasks: ( d e f i n e( f i b on ) ( l o c a l( f 1f 2 ) ( i f ( <n2 )1 ( b e g i n ( s p a w n' f 1( f i b o( -n1 ) ) ) ( s p a w n' f 2( f i b o( -n2 ) ) ) ( s y n c1 0 0 0 0 ) ( +f 1f 2 ) ) ) ) ) ( f i b o7 ) 2 1

With( f i b o7 ) 41processeswillbegenerated.AlthoughtheabovecodeshowstheworkingoftheCilkAPIinarecursive application,itwouldnotbepractical,astheoverheadrequiredtospawnsubtasksismuchhigherthanthetimesavedthrough parallelization. Sinceversion10.1asendandreceivemessagefunctionsareavailableforcommunicationsbetweenparentandchildprocesses. Usingthesefunctionsanydataorexpressionofanysizecanbetransferred.Additionallymessagedexpressionscanbeevaluatedin

therecipient'senvironment.

sqrt
syntax:(sqrtnum) Calculatesthesquarerootfromtheexpressioninnumandreturnstheresult.
( s q r t1 0 ) 3 . 1 6 2 2 7 7 6 6 ( s q r t2 5 ) 5

startswith
syntax:(startswithstrstrkey[numoption]) syntax:(startswithlist[exp]) Inthefirstversion,s t a r t s w i t h checksifthestringstrstartswithakeystringinstrkeyandreturnst r u e orn i l dependingonthe outcome. Ifaregularexpressionnumberisspecifiedinnumoption,strkeycontainsaregularexpressionpattern.Seeregexforvalidoption numbers.
( s t a r t s w i t h" t h i si su s e f u l "" t h i s " ) ( s t a r t s w i t h" t h i si su s e f u l "" T H I S " ) t r u e n i l

; ;u s er e g u l a re x p r e s s i o n s ( s t a r t s w i t h" t h i si su s e f u l "" T H I S "1 ) t r u e ( s t a r t s w i t h" t h i si su s e f u l "" t h i s | t h a t "0 )t r u e

Inthesecondversion,s t a r t s w i t h checkstoseeifaliststartswiththelistelementinexp.t r u e orn i l isreturneddependingon outcome.


( s t a r t s w i t h' ( 12345 )1 ) t r u e ( s t a r t s w i t h' ( abcde )' b ) n i l ( s t a r t s w i t h' ( ( +34 )bcd )' ( +34 ) ) t r u e

Seealsotheendswithfunction.

stats
syntax:(statslistvector) Thefunctionscalculatesstatisticalvaluesofcentraltendencyanddistributionmomentsofvaluesinlistvector.Thefollowingvalues arereturnedbys t a t s inalist: name description N Numberofvalues mean Meanofvalues avdev Averagedeviationfrommeanvalue

sdev Standarddeviation(populationestimate) var Variance(populationestimate) skew Skewofdistribution kurt Kurtosisofdistribution

Thefollowingexampleusesthelistoutputfromthes t a t s expressionasanargumentfortheformatstatement:
( s e t' d a t a' ( 9 01 0 01 3 01 5 01 8 02 0 02 2 03 0 03 5 04 0 0 ) ) ( p r i n t l n( f o r m a t[ t e x t ] N =% 5 d m e a n =% 8 . 2 f a v d e v =% 8 . 2 f s d e v =% 8 . 2 f v a r =% 8 . 2 f s k e w =% 8 . 2 f k u r t =% 8 . 2 f [ / t e x t ]( s t a t sd a t a ) ) ) ;o u t p u t st h ef o l l o w i n g N = 1 0 m e a n = 2 1 2 . 0 0 a v d e v = 8 4 . 4 0 s d e v = 1 0 6 . 1 2 v a r =1 1 2 6 2 . 2 2 s k e w = 0 . 4 9 k u r t o s i s= 1 . 3 4

string
syntax:(stringexp1[exp2...]) Translatesintoastringanythingthatresultsfromevaluatingexp1.Ifmorethanoneexpressionisspecified,theresultingstrings areconcatenated.
( s t r i n g' h e l l o ) ( s t r i n g1 2 3 4 ) ( s t r i n g' ( +34 ) ) ( s t r i n g( +34 )8 ) ( s t r i n g' h e l l o""1 2 3 ) " h e l l o " " 1 2 3 4 " " ( +34 ) " " 7 8 " " h e l l o1 2 3 "

Ifabufferpassedtos t r i n g contains\ 0 0 0 ,onlythestringuptothefirstterminatingzerowillbecopied:


( s e t' b u f f" A B C \ 0 0 0 \ 0 0 0 \ 0 0 0 " ) " A B C \ 0 0 0 \ 0 0 0 \ 0 0 0 " ( l e n g t hb u f f ) 6 ( s t r i n gb u f f ) " A B C " ( l e n g t h( s t r i n gb u f f ) ) 3

Usetheappendandjoin(allowsthejoiningstringtobespecified)functionstoconcatenatestringscontainingzerobytes.Usethe sourcefunctiontoconvertalambdaexpressionintoitsnewLISPsourcestringrepresentation.

string?

syntax:(string?exp) Evaluatesexpandteststoseeifitisastring.Returnst r u e orn i l dependingontheresult.


( s e t' v a r" h e l l o " ) ( s t r i n g ?v a r ) t r u e

struct
syntax:(structsymbol[strdatatype...]) Thes t r u c t functioncanbeusedtodefineaggregatedatatypesforusagewiththeextendedsyntaxofimport,packandunpack. ThisallowsimportingfunctionswhichtakeClanguagestructdatatypesorpointerstotheseaggregatedatatypes. Thefollowingexampleillustratestheusageofs t r u c t togetherwiththeCdatafunctionsl o c a l t i m e anda s c t i m e .Thel o c a l t i m e functionsworkssimilartothebuiltinnowfunction.Thea s c t i m e functiontakesthenumericaldataoutputbyl o c a l t i m e and formatsthesetoreadabletext.
/ *T h eCf u n c t i o np r o t o t y p e sf o rt h ef u n c t i o n st oi m p o r t* / s t r u c tt m*l o c a l t i m e ( c o n s tt i m e _ t* c l o c k ) ; c h a r*a s c t i m e ( c o n s ts t r u c tt m* t i m e p t r ) ; / *t h et ms t r u c ta g g r e g a t i n gd i f f e r e n tt i m er e l a t e dv a l u e s* / s t r u c tt m{ i n tt m _ s e c ; i n tt m _ m i n ; i n tt m _ h o u r ; i n tt m _ m d a y ; i n tt m _ m o n ; i n tt m _ y e a r ; i n tt m _ w d a y ; i n tt m _ y d a y ; i n tt m _ i s d s t ; l o n gt m _ g m t o f f ; c h a r* t m _ z o n e ; } ; / *s e c o n d sa f t e rt h em i n u t e[ 0 6 0 ]* / / *m i n u t e sa f t e rt h eh o u r[ 0 5 9 ]* / / *h o u r ss i n c em i d n i g h t[ 0 2 3 ]* / / *d a yo ft h em o n t h[ 1 3 1 ]* / / *m o n t h ss i n c eJ a n u a r y[ 0 1 1 ]* / / *y e a r ss i n c e1 9 0 0* / / *d a y ss i n c eS u n d a y[ 0 6 ]* / / *d a y ss i n c eJ a n u a r y1[ 0 3 6 5 ]* / / *D a y l i g h tS a v i n g sT i m ef l a g* / / *o f f s e tf r o mC U Ti ns e c o n d s* / / * * *n o to nW i n d o w s* * * / / *t i m e z o n ea b b r e v i a t i o n* / / * * *n o to nW i n d o w s* * * /

FunctionimportanddefinitionofthestructuredatatypeinnewLISP:
; ;f o rp o i n t e r st os t r u c t sa l w a y su s ev o i d * ; ;a sal i b r a r yu s em s v c r t . d l lo nW i n d o w so rl i b c . s oo nU n i x . ; ;T h et ms t r u c tt y p ei sc o n f i g u r e df o rM a cO S Xa n dL i n u x . ; ;O no t h e rO St h et ms t r u c t u r em a yb ed i f f e r e n t ( i m p o r t" l i b c . d y l i b "" a s c t i m e "" c h a r * "" v o i d * " ) ( i m p o r t" l i b c . d y l i b "" l o c a l t i m e "" v o i d * "" v o i d * " ) ;d e f i n i t i o no ft h es t r u c t ( s t r u c t' t m" i n t "" i n t "" i n t "" i n t "" i n t "" i n t "" i n t "" i n t "" i n t "" l o n g "" c h a r * " ) ; ;u s ei m p o r ta n ds t r u c t ;t o d a y sd a t en u m b e r( s e c o n d sa f t e r1 9 7 0a l s oc a l l e dU n i xe p o c ht i m e ) ( s e t' t o d a y( d a t e v a l u e ) ) 1 3 2 4 1 3 4 9 1 3 ; ;t h et i m ev a l u ei sp a s s e db yi t ' sa d d r e s s ; ;l o c a l t i m er e t i r n sap o i n t e rt oat ms t r u c t ( s e t' p t r( l o c a l t i m e( a d d r e s st o d a y ) ) )2 8 9 6 2 1 9 6 9 6 ;u n p a c kt h et ms t r u c t ( 7 : 1 5 : 1 3o nt h e1 7 t he t c . )

( u n p a c kt mp t r )( 1 31 571 71 11 1 163 5 002 8 8 0 0" P S T " ) ;t r a n s f o r mt or e a d a b l ef o r m ( a s c t i m ep t r )" S a tD e c1 70 7 : 1 5 : 1 32 0 1 1 \ n " ;a l li no n es t a t e m e n td o e sa c t u a l l yn o tu s es t r u c t ,p o i n t e r sa r ep a s s e dd i r e c t l y ( a s c t i m e( l o c a l t i m e( a d d r e s st o d a y ) ) )" S a tD e c1 70 7 : 1 5 : 1 32 0 1 1 " ;s a m ea st h eb u i l t i nd a t ef u n c t i o n ( d a t et o d a y )" S a tD e c1 70 7 : 1 5 : 1 32 0 1 1 "

Caremustbetakentopassvalidaddressestopointerparametersinimportedfunctionsorwhenpassingaddresspointerstounpack. InvalidaddresspointerscancrashnewLISPormakeitunstable.
s t r u c t definitionscanbenested: ;t h ep a i ra g g r e g a t et y p e ( s t r u c t' p a i r" c h a r "" c h a r " )p a i r ;n e s t e ds t r u c tt y p e ( s t r u c t' c o m p" p a i r "" i n t " ) c o m p ;p a c kd a t au s i n gt h ee x t e n d e dp a c ks y n t a x ;n o t et h ei n s e r t i o no fs t r u c t u r ea l i g n m e n tb y t e sa f t e rt h ep a i r ( p a c kc o m p( p a c kp a i r12 )3 )" \ 0 0 1 \ 0 0 2 \ 0 0 0 \ 0 0 0 \ 0 0 3 \ 0 0 0 \ 0 0 0 \ 0 0 0 " ;u n p a c kr e v e r s e st h ep r o c e s s ( u n p a c kc o m p" \ 0 0 1 \ 0 0 2 \ 0 0 0 \ 0 0 0 \ 0 0 3 \ 0 0 0 \ 0 0 0 \ 0 0 0 " )( ( 12 )3 )

Nestedstructuresareunpackedrecursively.

sub
syntax:(subnum1[num2...]) Successivelysubtractstheexpressionsinnum1,num2.s u b performsmixedtypearithmeticandhandlesintegersorfloating points,butitwillalwaysreturnafloatingpointnumber.Ifonlyoneargumentissupplied,itssignisreversed.Anyfloatingpoint calculationwithN a N alsoreturnsN a N .
( s u b1 080 . 2 5 ) 1 . 7 5 ( s u b1 2 3 ) 1 2 3

swap!
syntax:(swapplace1place2) Thecontentsofthetwoplacesplace1andplace2areswapped.Aplacecanbethecontentsofanunquotedsymboloranylistor arrayreferencesexpressedwithnth,first,lastorimplicitindexingorplacesreferencedbyassocorlookup.
s w a p isadestructiveoperationthatchangesthecontentsofthelists,arrays,orsymbolsinvolved. ( s e t' l s t' ( abcdef ) ) ( s w a p( f i r s tl s t )( l a s tl s t ) )a l s t ( fbcdea ) ( s e t' l s t b' ( xyz ) ) ( s w a p( l s t0 )( l s t b1 ) )f

l s t l s t b

( zbcdea ) ( xyf )

( s e t' A( a r r a y23( s e q u e n c e16 ) )( ( 123 )( 456 ) ) ( s w a p( A0 )( A1 ) )( 123 ) A ( ( 456 )( 123 ) ) ( s e t' x1' y2 ) ( s w a pxy ) 1 x 2 y 1 ( s e t' l s t' ( ( a123 )( b1 02 03 0 ) ) ) ( s w a p( l o o k u p' al s t1 )( l o o k u p' bl s t1 ) ) l s t( ( a121 0 )( b32 03 0 ) ) ( s w a p( a s s o c' al s t )( a s s o c' bl s t ) ) l s t ( ( b32 03 0 )( a121 0 ) )

Anytwoplacescanbesweptinthesameordifferentobjects.

sym
syntax:(symstring[symcontext[nilflag]]) syntax:(symnumber[symcontext[nilflag]]) syntax:(symsymbol[symcontext[nilflag]]) Translatesthefirstargumentinstring,number,orsymbolintoasymbolandreturnsit.Iftheoptionalcontextisnotspecifiedinsym context,thecurrentcontextisusedwhendoingsymbollookuporcreation.Symbolswillbecreatediftheydonotalreadyexist. Whenthecontextdoesnotexistandthecontextisspecifiedbyaquotedsymbol,thesymbolalsogetscreated.Ifthecontext specificationisunquoted,thecontextisthespecifiednameorthecontextspecificationisavariablecontainingthecontext.
s y m cancreatesymbolswithinthesymboltablethatarenotlegalsymbolsinnewLISPsourcecode(e.g.,numbersornames

containingspecialcharacterssuchasparentheses,colons,etc.).Thismakess y m usableasafunctionforassociativememoryaccess, muchlikehashtableaccessinotherscriptinglanguages. Asathirdoptionalargument,n i l canbespecifiedtosuppresssymbolcreationifthesymbolisnotfound.Inthiscase,s y m returns n i l ifthesymbollookedupdoesnotexist.Usingthislastform,s y m canbeusedtocheckfortheexistenceofasymbol.


( s y m" s o m e " ) ( s e t( s y m" v a r " )3 4 5 ) v a r ( s y m" a S y m "' M y C T X ) ( s y m" a S y m "M y C T X ) s o m e 3 4 5 3 4 5 M y C T X : a S y m M y C T X : a S y m ;u n q u o t e dc o n t e x t

( s y m" f o o "M y C T Xn i l ) n i l ;' f o od o e sn o te x i s t ( s y m" f o o "M y C T X ) f o o ;' f o oi sc r e a t e d ( s y m" f o o "M y C T Xn i l ) f o o ;f o on o we x i s t s

Becausethefunctions y m returnsthesymbollookeduporcreated,expressionswiths y m canbeembeddeddirectlyinother expressionsthatusesymbolsasarguments.Thefollowingexampleshowstheuseofs y m asahashlikefunctionforassociative memoryaccess,aswellassymbolconfigurationsthatarenotlegalnewLISPsymbols:


; ;u s i n gs y mf o rs i m u l a t i n gh a s ht a b l e s ( s e t( s y m" J o h nD o e "' M y D B )1 . 2 3 4 ) ( s e t( s y m" ( "' M y D B )" p a r e n t h e s i so p e n " ) ( s e t( s y m1 2' M y D B )" t w e l v e " ) ( e v a l( s y m" J o h nD o e "' M y D B ) ) 1 . 2 3 4 ( e v a l( s y m" ( "' M y D B ) ) " p a r e n t h e s i so p e n "

( e v a l( s y m1 2' M y D B ) )

" t w e l v e "

; ;d e l e t eas y m b o lf r o mas y m b o lt a b l eo rh a s h ( d e l e t e( s y m" J o h nD o e "' M y D B ) ) t r u e

Thelaststatementshowshowasymbolcanbeeliminatedusingdelete. Thethirdsyntaxallowssymbolstobeusedinsteadofstringsforthesymbolnameinthetargetcontext.Inthiscase,s y m willextract thenamefromthesymbolanduseitasthenamestringforthesymbolinthetargetcontext:


( s y m' m y V a r' F O O ) F O O : m y V a r ( d e f i n e m a c r o( d e f c o n t e x t ) ( d o l i s t( s( r e s t( a r g s ) ) ) ( s y ms( f i r s t( a r g s ) ) ) ) ) ( d e f c o n t e x tf o oxyz ) ( s y m b o l sf o o ) ( f o o : xf o o : yf o o : z )

Thed e f c o n t e x t macroshowshowthiscouldbeusedtocreateamacrothatcreatescontextsandtheirvariablesinadynamic fashion. Asyntaxofthecontextfunctioncanalsobeusedtocreate,setandevaluatesymbols.

symbol?
syntax:(symbol?exp) Evaluatestheexpexpressionandreturnst r u e ifthevalueisasymbolotherwise,itreturnsn i l .
( s e t' x' y ) y ( s y m b o l ?x ) t r u e ( s y m b o l ?1 2 3 ) n i l ( s y m b o l ?( f i r s t' ( v a rxyz ) ) ) t r u e

Thefirststatementsetsthecontentsofx tothesymboly .Thesecondstatementthenchecksthecontentsofx .Thelastexample checksthefirstelementofalist.

symbols
syntax:(symbols[context]) Returnsasortedlistofallsymbolsinthecurrentcontextwhencalledwithoutanargument.Ifacontextsymbolisspecified,symbols definedinthatcontextarereturned.
( s y m b o l s ) ( s y m b o l s' C T X ) ( s y m b o l sC T X ) ( s e t' c tC T X ) ( s y m b o l sc t ) ;l i s to fa l ls y m b o l si nc u r r e n tc o n t e x t ;l i s to fs y m b o l si nc o n t e x tC T X ;o m i t t i n gt h eq u o t e ;a s s i g n i n gc o n t e x tt oav a r i a b l e ;l i s to fs y m b o l si nc o n t e x tC T X

Thequotecanbeomittedbecausecontextsevaluatetothemselves.

sync
syntax:(syncinttimeout[funcinlet]) syntax:(sync) Wheninttimeoutinmillisecondsisspecified,s y n c waitsforchildprocesseslaunchedwithspawntofinish.Wheneverachild processfinishes,s y n c assignstheevaluationresultofthespawnedsubtasktothesymbolspecifiedinthespawnstatement.The s y n c returnst r u e ifallchildprocesseshavebeenprocessedorn i l ifthetimeoutvaluehasbeenreachedandmorechildprocesses arepending. Ifs y n c additionallyisgivenwithanoptionaluserdefinedinletfunctioninfuncinlet,thisfunctionwillbecalledwiththechild processidasargumentwheneveraspawnedchildprocessreturns.funcinletcancontaineitheralambdaexpressionorasymbol whichdefinesafunction. Withoutanyparameter,s y n c returnsalistofpendingchildprocessPIDs(processidentifiers),forwhichresultshavenotbeen processedyet. Thefunctions y n c isnotavailableonWin32.
;w a i tf o r1 0s e c o n d sa n dp r o c e s sf i n i s h e dc h i l dp r o c e s s e s ( s y n c1 0 0 0 0 ) ;w a i tf o rt h em a x i m u mt i m e( ~1 1 9 3h o u r s ) ( s y n c1 ) ( d e f i n e( r e p o r tp i d ) ( p r i n t l n" p r o c e s s :"p i d"h a sr e t u r n e d " ) ) ;c a l lt h er e p o r tf u n c t i o n ,w h e nac h i l dr e t u r n s ( s y n c1 0 0 0 0r e p o r t );w a i tf o r1 0s e c o n d sm a x ;r e t u r nal i s to fp e n d i n gc h i l dp r o c e s s e s ( s y n c ) ( 2 4 52 4 62 4 72 4 8 ) ;w a i ta n dd os o m e t h i n ge l s e ( u n t i l( t r u e ?( s y n c1 0r e p o r t )) ( p r i n t l n( t i m e o f d a y ) ) )

Whens y n c isgivenwithatimeoutparameter,itwillblockuntiltimeoutoruntilallchildprocesseshavereturned,whichevercomes earlier.Whennoparameterisspecifiedorafunctionisspecified,s y n c returnsimmediately. Thefunctions y n c ispartoftheCilkAPIforsynchronizingchildprocessesandprocessparallelization.Seethereferenceforthe functionspawnforafulldiscussionoftheCilkAPI.

syserror
syntax:(syserror) syntax:(syserrorinterror) syntax:(syserror0 ) ReportsthelasterrorgeneratedbytheunderlyingOSwhichnewLISPisrunningon.Theerrorreportedmaydifferontheplatforms newLISPhasbeencompiledfor.Consulttheplatform'sClibraryinformation.Theerrorisreportedasalistoferrornumberand errortext.

Ifnoerrorhasoccurredorthesystemerrornumberhasbeenreset,n i l isreturned. Wheninterrorisgreater0 (zero)alistofthenumberandtheerrortextisreturned. Toresettheerrorspecify0 astheerrornumber. WheneverafunctioninnewLISPwithinthesystemresourcesareareturnsn i l ,s y s e r r o r canbecheckedfortheunderlying reason.Forfileoperations,s y s e r r o r maybesetfornonexistentfilesorwrongpermissionswhenaccessingtheresource.Another causeoferrorcouldbetheexhaustionofcertainsystemresourceslikefilehandlesorsemaphores.
; ;t r y i n gt oo p e nan o n e x i s t e n tf i l e ( o p e n" x y z "" r " ) n i l ( s y s e r r o r ) ; ;r e s e te r r n o ( s y s e r r o r0 ) ( s y s e r r o r ) ( 2" N os u c hf i l eo rd i r e c t o r y " ) ( 0" U n k n o w ne r r o r :0 " ) n i l

Seealsolasterrorandneterror.

sysinfo
syntax:(sysinfo[intidx]) Callings y s i n f o withoutintidxreturnsalistofinternalresourcestatistics.Tenintegersreportthefollowingstatus: offset description 0 NumberofLispcells 1 2 3 4 5 6 7 8 MaximumnumberofLispcellsconstant Numberofsymbols Evaluation/recursionlevel Environmentstacklevel Maximumcallstackconstant Pidoftheparentprocessor0 PidofrunningnewLISPprocess Versionnumberasanintegerconstant Operatingsystemconstant: linux=1,bsd=2,osx=3,solaris=4,win32=6,os/2=7,cygwin=8,tru64,unix=9,aix=10,android=11 bit11willbesetforffilib(extendedimport/callbackAPI)versions(add1024) bit10willbesetforIPv6versions(add512) bit9willbesetfor64bit(changeableatruntime)versions(add256) bit8willbesetforUTF8versions(add128) bit7willbeaddedforlibraryversions(add64)

Thenumbersfrom0 to9 indicatetheoptionaloffsetinthereturnedlist. Itisrecommendedtouseoffsets0to5toaddressupandincluding"Maximumcallstackconstant"andtousenegativeoffsets1to 4toaccessthelastfourentriesinthesysteminfolist.Futurenewentrieswillbeinsertedafteroffset5.Thiswayoldersourcecode doesnotneedtochange. Whenusingintidx,oneelementofthelistwillbereturned.

( s y s i n f o ) ( 4 2 92 6 8 4 3 5 4 5 64 0 2102 0 4 801 9 4 5 31 0 4 0 61 1 5 5 ) ( s y s i n f o3 ) 1 ( s y s i n f o2 ) 1 0 4 0 6; ;v e r s i o n1 0 . 4 . 6

ThenumberforthemaximumofLispcellscanbechangedviathem commandlineswitch.ForeachmegabyteofLispcell memory,64kmemorycellscanbeallocated.Themaximumcallstackdepthcanbechangedusingthes commandlineswitch.

ttest
syntax:(ttestlistvectornumbervalue) syntax:(ttestlistvectorAlistvectorB[t r u e ]) syntax:(ttestlistvectorAlistvectorBfloatprobability) InthefirstsyntaxthefunctionusesaonesampleStudent'sttesttocomparethemeanvalueoflistvectortothevalueinnumber value:
;o n es a m p l et t e s t ( t t e s t' ( 35425743 )2 . 5 ) ' ( 4 . 1 2 52 . 51 . 5 5 20 . 5 4 92 . 9 6 070 . 0 2 1 )

Thefollowingdataarereturnedinalist: name mean value sdev description meanofdatainvector valuetocompare standarddeviationindatavector

meanerror standarderrorofmean t tbetweenmeanandvalue df p degreesoffreedom twotailedprobabilityoftunderthenullhypothesis

Inaboveexamplethedifferenceofthemeanvalue4 . 1 2 5 from2 . 5 ismoderatelysignificant.Withaprobabilityp = 0 . 0 2 1 ( 2 . 1 % ) thenullhypothesisthatthemeanisnotsignificantlydifferent,canberejected. Inthesecondsyntax,thefunctionperformsattestusingtheStudent'ststatisticforcomparingthemeansvaluesinlistvectorAand listvectorB.Ifthet r u e flagisnotused,bothvectorsinAandBcanbeofdifferentlengthandgroupsrepresentedbyAandBare notrelated. Whentheoptionalflagissettot r u e ,measurementsweretakenfromthesamegrouptwice,e.g.beforeandafteraprocedure. Thefollowingresultsarereturnedinalist: name description meana meanofgroupA meanb meanofgroupB sdeva standarddeviationingroupA sdevb standarddeviationingroupB t df p tbetweenmeanvalues degreesoffreedom twotailedprobabilityoftunderthenullhypothesis

ThefirstexamplestudiestheeffectofdifferentsleeplengthbeforeatestontheSCAT(Sam'sCognitiveAbilityTest):

;S C A T( S a m ' sC o g n i t i v eA b i l i t yT e s t ) ;t w oi n d e p e n d e n ts a m p l et t e s t ( s e t' h o u r s s l e e p 8' ( 57535339 ) ) ( s e t' h o u r s s l e e p 4' ( 81466412 ) ) ( t t e s th o u r s s l e e p 8h o u r s s l e e p 4 ) ( 542 . 1 3 82 . 5 6 30 . 8 4 71 40 . 4 1 1 )

ThedurationofsleepsbeforetheSCATdoesnothaveasignificanteffectwithaprobabilityvalueof0 . 4 1 1 . Inthesecondexample,thesamegroupofpeoplegettestedtwice,beforeandafteratreatmentwithProzacdepressionmedication:
;E f f e c to fa na n t i d e p r e s s a n to nag r o u po fd e p r e s s e dp e o p l e ;t w or e l a t e ds a m p l e st t e s t ( s e t' m o o d p r e' ( 306743214 ) ) ( s e t' m o o d p o s t' ( 51571 0971 18 ) ) ( t t e s tm o o d p r em o o d p o s tt r u e ) ( 3 . 3 3 372 . 2 3 63 . 0 4 13 . 1 4 380 . 0 1 3 7 )

Theeffectoftheantidepressanttreatmentismoderatelysignificantwithap of0 . 0 1 3 7 . Inthethirdsyntax,aformoftheStudent'stcalledWelch'sttestisperformed.Thismethodisusedwhenthevariancesobservedin bothsamplesaresignificantlydifferent.Thethresholdcanbesetusingthefloatprobabilityparameter.Whenthisparameterisused thet t e s t functionwillperformaFtesttocomparethevariancesinthetwodatasamples.IftheprobabilityofthefoundFratiois belowthefloatprobabilityparameter,theWelch'sttestmethodwillbeused.Specifyingthisvalueas1 . 0 effectivelyforcesa Welch'sttest:


;t w oi n d e p e n d e n ts a m p l et t e s tu s i n gt h eW e l c hm e t h o d ( t t e s t' ( 1 0471161824 )' ( 46946893 )1 . 0 ) ( 4 . 46 . 1 2 53 . 2 3 92 . 3 5 71 . 3 0 71 50 . 2 1 1 ) ;t w oi n d e p e n d e n ts a m p l et t e s tu s i n gt h en o r m a lm e t h o d ( t t e s t' ( 1 0471161824 )' ( 46946893 ) ) ( 4 . 46 . 1 2 53 . 2 3 92 . 3 5 71 . 2 6 01 60 . 2 2 6 )

Thereisnosignificantdifferencebetweenthemeansofthetwosamples.TheWelchmethodofthettestisslightlymoresensitivein thiscasethanusingthenormalttestmethod. Smallervaluesthan1 . 0 wouldtriggertheWelch'sttestmethodonlywhenthesignificanceofvariancedifferenceinthesamples reachescertainvalue.

tan
syntax:(tannumradians) Calculatesthetangentfunctionfromnumradiansandreturnstheresult.
( t a n1 ) 1 . 5 5 7 4 0 7 7 2 5 ( s e t' p i( m u l2( a s i n1 ) ) ) 3 . 1 4 1 5 9 2 6 5 4 ( t a n( d i vp i4 ) ) 1

tanh
syntax:(tanhnumradians) Calculatesthehyperbolictangentofnumradians.Thehyperbolictangentisdefinedmathematicallyas:sinh(x)/cosh(x).

( t a n h1 ) 0 . 7 6 1 5 9 4 1 5 6 ( t a n h1 0 ) 0 . 9 9 9 9 9 9 9 9 5 9 ( t a n h1 0 0 0 ) 1 ( =( t a n h1 )( d i v( s i n h1 )( c o s h1 ) ) ) t r u e

term
syntax:(termsymbol) Returnsasastring,thetermpartofasymbolwithoutthecontextprefix.
( s e t' A C T X : v a r1 2 3 ) ( s e t' s m' A C T X : v a r ) ( s t r i n gs m ) " A C T X : v a r " ( t e r ms m ) " v a r " ( s e t' s' f o o : b a r ) ( =s( s y m( t e r ms )( p r e f i xs ) ) )

Seealsoprefixtoextractthenamespaceorcontextprefixfromasymbol.

throw
syntax:(throwexp) Workstogetherwiththecatchfunction.t h r o w forcesthereturnofapreviousc a t c h statementandputstheexpintotheresult symbolofc a t c h .
( d e f i n e( t h r o w t e s t ) ( d o t i m e s( x1 0 0 0 ) ( i f( =x5 0 0 )( t h r o w" i n t e r r u p t e d " ) ) ) ) ( c a t c h( t h r o w t e s t )' r e s u l t ) t r u e r e s u l t " i n t e r r u p t e d " ( c a t c h( t h r o w t e s t ) ) " i n t e r r u p t e d "

Thelastexampleshowsashorterformofcatch,whichreturnsthet h r o w resultdirectly.
t h r o w isusefulforbreakingoutofalooporforearlyreturnfromuserdefinedfunctionsorexpressionblocks.Inthefollowing

example,theb e g i n blockwillreturnX if( f o oX ) ist r u e elseY willbereturned:


( c a t c h( b e g i n ( i f( f o oX )( t h r o wX )Y ) ) ) t h r o w willnotcauseanerrorexception.Usethrowerrortothrowusererrorexceptions.

throwerror
syntax:(throwerrorexp)

Causesauserdefinederrorexceptionwithtextprovidedbyevaluatingexp.
( d e f i n e( f o oxy ) ( i f( =x0 )( t h r o w e r r o r" f i r s ta r g u m e n tc a n n o tb e0 " ) ) ( +xy ) ) ( f o o12 ) 3 ( f o o02 ) ;c a u s e sau s e re r r o re x c e p t i o n E R R :u s e re r r o r:f i r s ta r g u m e n tc a n n o tb e0 c a l l e df r o mu s e r d e f i n e df u n c t i o nf o o

Theusererrorcanbehandledlikeanyothererrorexceptionusinguserdefinederrorhandlersandtheerroreventfunction,orthe formofcatchthatcancaptureerrorexceptions.

time
syntax:(timeexp[intcount) Evaluatestheexpressioninexpandreturnsthetimespentonevaluationinfloatingpointmilliseconds.Dependingontheplatform decimalsofmillisecondsareshownornotshown.
( t i m e( m y p r o gxyz ) ) 4 5 0 . 3 4 0 ( t i m e( m y p r o gxyz )1 0 ) 4 4 2 0 . 0 2 1

Infirsttheexample,450millisecondselapsedwhileevaluating( m y p r o gxyz ) .Thesecondexamplereturnsthetimeforten evaluationsof( m y p r o gxyz ) .Seealsodate,datevalue,timeofday,andnow.

timeofday
syntax:(timeofday) Returnsthetimeinmillisecondssincethestartofthecurrentday. Seealsothedate,datevalue,time,andnowfunctions.

timer
syntax:(timersymeventhandler|funceventhandlernumseconds[intoption]) syntax:(timersymeventhandler|funceventhandler) syntax:(timer) StartsaoneshottimerfiringofftheUnixsignalS I G A L R M ,S I G V T A L R M ,orS I G P R O F afterthetimeinseconds(specifiedinnum seconds)haselapsed.Whenthetimerfires,itcallstheuserdefinedfunctioninsymorfunceventhandler. OnLinux/Unix,anoptional0 ,1 ,or2 canbespecifiedtocontrolhowthetimercounts.Withdefaultoption0 ,realtimeismeasured. Option1 measuresthetimetheCPUspendsprocessingintheprocessowningthetimer.Option2 isacombinationofbothcalled profilingtime.SeetheUnixmanpages e t i t i m e r ( ) fordetails.

Theeventhandlercanstartthetimeragaintoachieveacontinuousflowofevents.Startingwithversion8.5.9,secondscanbe definedasfloatingpointnumberswithafractionalpart(e.g.,0 . 2 5 for250milliseconds). Defining0 (zero)astimeshutstherunningtimerdownandpreventsitfromfiring. Whencalledwithsymorfunceventhandler,t i m e r returnstheelapsedtimeofthetimerinprogress.Thiscanbeusedtoprogram timelinesorschedules.


t i m e r calledwithoutargumentsreturnsthesymbolofthecurrenteventhandler. ( d e f i n e( t i c k e r ) ( p r i n t l n( d a t e ) )( t i m e r' t i c k e r1 . 0 ) ) >( t i c k e r ) T u eA p r1 22 0 : 4 4 : 4 82 0 0 5 t i c k e r >T u eA p r1 22 0 : 4 4 : 4 92 0 0 5 T u eA p r1 22 0 : 4 4 : 5 02 0 0 5 T u eA p r1 22 0 : 4 4 : 5 12 0 0 5 T u eA p r1 22 0 : 4 4 : 5 22 0 0 5 ;f i r s te x e c u t i o no ft i c k e r ;r e t u r nv a l u ef r o mt i c k e r ;f i r s tt i m e re v e n t ;s e c o n dt i m e re v e n t. . .

Theexampleshowsaneventhandler,t i c k e r ,whichstartsthetimeragainaftereachevent. Notethatatimercannotinterruptanongoingbuiltinfunction.ThetimerinterruptgetsregisteredbynewLISP,butatimerhandler cannotrununtiloneexpressionisevaluatedandthenextonestarts.TointerruptanongoingI/Ooperationwitht i m e r ,usethe followingpattern,whichcallsnetselecttotestifasocketisreadyforreading:


d e f i n e( i n t e r r u p t ) ( s e t' t i m e o u tt r u e ) ) ( s e t' l i s t e n( n e t l i s t e n3 0 0 0 1 ) ) ( s e t' s o c k e t( n e t a c c e p tl i s t e n ) ) ( t i m e r' i n t e r r u p t1 0 ) ; ;o rs p e c i f y i n gt h ef u n c t i o nd i r e c t l y ( t i m e r( f n( )( s e t' t i m e o u tt r u e ) )1 0 ) ( u n t i l( o rt i m e o u td o n e ) ( i f( n e t s e l e c ts o c k e t" r e a d "1 0 0 0 0 0 ) ( b e g i n ( n e t r e c e i v es o c k e tb u f f e r1 0 2 4 ) ( s e t' d o n et r u e ) ) ) ) ( i ft i m e o u t ( p r i n t l n" t i m e o u t " ) ( p r i n t l nb u f f e r ) ) ( e x i t )

Inthisexample,theu n t i l loopwillrununtilsomethingcanbereadfroms o c k e t ,oruntiltensecondshavepassedandthe t i m e o u t variableisset.

titlecaseutf8
syntax:(titlecasestr[bool]) Returnsacopyofthestringinstrwiththefirstcharacterconvertedtouppercase.Whentheoptionalboolparameterevaluatestoany valueotherthann i l ,therestofthestringisconvertedtolowercase.
( t i t l e c a s e" h e l l o " ) " H e l l o " ( t i t l e c a s e" h E L L O "t r u e ) " H e l l o "

( t i t l e c a s e" h E L L O " )

" H E L L O "

Seealsothelowercaseanduppercasefunctions.

trace
syntax:(trace[bool]) Tracingisswitchedonwhenboolevaluatestoanythingotherthann i l .Whennoargumentissupplied,t r a c e evaluatestot r u e or n i l dependingonthecurrenttracemode.Iftracemodeisswitchedon,newLISPgoesintodebuggingmodeafterenteringthenext userdefinedfunction,displayingthefunctionandhighlightingthecurrentexpressionuponentryandexit. Highlightingisdonebybracketingtheexpressionbetweentwo#(numbersign)characters.Thiscanbechangedtoadifferent characterusingtracehighlight.Uponexitfromtheexpression,theresultofitsevaluationisalsoreported. Ifanexpressionoccursmorethanonceinafunction,thefirstoccurrenceoftheexecutingfunctionwillalwaysbehighlighted (bracketed). newLISPexecutionstopswithapromptlineateachentryandexitofanexpression.
[ >2 ]s | t e pn | e x tc | o n tq | u i t>

Attheprompt,ans ,n ,c ,orq canbeenteredtostepintoormerelyexecutethenextexpression.Anyexpressioncanbeenteredat thepromptforevaluation.Enteringthenameofavariable,forexample,wouldevaluatetoitscontents.Inthisway,avariable's contentscanbecheckedduringdebuggingorsettodifferentvalues.


; ;s w i t c h e sn e w L I S Pi n t od e b u g g i n gm o d e ( t r a c et r u e ) t r u e ; ;t h ed e b u g g e rw i l ls h o we a c hs t e p ( m y f u n cabc ) ; ;s w i t c h e dn e w L I S Po u to fd e b u g g i n gm o d e ( t r a c en i l ) n i l

TosetbreakpointswherenewLISPshouldinterruptnormalexecutionandgointodebuggingmode,put( t r a c et r u e ) statements intothenewLISPcodewhereexecutionshouldswitchonthedebugger. Usethedebugfunctionasashortcutfortheaboveexample.

tracehighlight
syntax:(tracehighlightstrprestrpost[strheaderstrfooter]) Setsthecharactersorstringofcharactersusedtoencloseexpressionsduringtrace.Bydefault,the#(numbersign)isusedtoenclose theexpressionhighlightedintracemode.Thiscanbechangedtodifferentcharactersorstringsofuptosevencharacters.Ifthe consolewindowacceptsterminalcontrolcharacters,thiscanbeusedtodisplaytheexpressioninadifferentcolor,bold,reverse,and soforth. Twomorestringscanoptionallybespecifiedforstrheaderandstrfooter,whichcontroltheseparatorandprompt.Amaximumof 15charactersisallowedfortheheaderand31forthefooter.
; ;a c t i v ee x p r e s s i o n sa r ee n c l o s e di n> >a n d< < ( t r a c e h i g h l i g h t" > > "" < < " )

; ;' b r i g h t 'c o l o ro naV T 1 0 0o rs i m i l a rt e r m i n a lw i n d o w ( t r a c e h i g h l i g h t" \ 0 2 7 [ 1 m "" \ 0 2 7 [ 0 m " )

Thefirstexamplereplacesthedefault# (numbersign)witha> > and< < .ThesecondexampleworksonmostLinuxshells.Itmay not,however,workinconsolewindowsunderWin32orCYGWIN,dependingontheconfigurationoftheterminal.

transpose
syntax:(transposematrix) Transposesamatrixbyreversingtherowsandcolumns.Anykindoflistmatrixcanbetransposed.Matricesaremaderectangular byfillinginn i l formissingelements,omittingelementswhereappropriate,orexpandingatomsinrowsintolists.Matrix dimensionsarecalculatedusingthenumberofrowsintheoriginalmatrixforcolumnsandthenumberofelementsinthefirstrowas numberofrowsforthetransposedmatrix. Thematrixtotransposecancontainanydatatype. Thedimensionsofamatrixaredefinedbythenumberofrowsandthenumberofelementsinthefirstrow.Amatrixcaneitherbea nestedlistoranarray.
( s e t' A' ( ( 123 )( 456 ) ) ) ( t r a n s p o s eA ) ( ( 14 )( 25 )( 36 ) ) ( t r a n s p o s e( l i s t( s e q u e n c e15 ) ) ) ( ( 1 )( 2 )( 3 )( 4 )( 5 ) ) ;a n yd a t at y p ei sa l l o w e di nt h em a t r i x ( t r a n s p o s e' ( ( ab )( cd )( ef ) ) ) ( ( ace )( bdf ) ) ;a r r a y sc a nb et r a n s p o s e dt o o ( s e t' A( a r r a y23( s e q u e n c e16 ) ) ) ( s e t' M( t r a n s p o s eA ) ) M( ( 14 )( 25 )( 36 ) )

Thenumberofcolumnsinamatrixisdefinedbythenumberofelementsinthefirstrowofthematrix.Ifotherrowshavefewer elements,t r a n s p o s e willassumen i l forthosemissingelements.Superfluouselementsinarowwillbeignored.


( s e t' A' ( ( 123 )( 45 )( 789 ) ) ) ( t r a n s p o s eA ) ( ( 147 )( 258 )( 3n i l9 ) )

Ifarowisanyotherdatatypebesidesalist,thetranspositiontreatsitlikeanentirerowofelementsofthatdatatype:
( s e t' A' ( ( 123 )X( 789 ) ) ) ( t r a n s p o s eA ) ( ( 1X7 )( 2X8 )( 3X9 ) )

Alloperationsshownhereonlistscanalsobeperformedonarrays. Seealsothematrixoperationsdet,invert,matandmultiply.

trimutf8
syntax:(trimstr[strchar]) syntax:(trimstrstrleftcharstrrightchar)

Thefirstsyntaxtrimsthestringstrfrombothsides,strippingtheleadingandtrailingcharactersasgiveninstrchar.Ifstrchar containsnocharacter,thespacecharacterisassumed.t r i m returnsthenewstring. Thesecondsyntaxcaneithertrimdifferentcharactersfrombothsidesortrimonlyonesideifanemptystringisspecifiedforthe other.


( t r i m" h e l l o " ) ( t r i m" h e l l o "" " ) ( t r i m" 0 0 0 1 2 3 4 0 "" 0 "" " ) ( t r i m" 1 2 3 4 0 0 0 "" "" 0 " ) ( t r i m" h e l l o = = = = = "" "" = " ) " h e l l o " " h e l l o " " 1 2 3 4 0 " " 1 2 3 4 " " h e l l o "

true?
syntax:(true?exp) Iftheexpressioninexpevaluatestoanythingotherthann i l ortheemptylist( ) ,t r u e ? returnst r u e otherwise,itreturnsn i l .
( m a pt r u e ?' ( x1" h i "( abc )n i l( ) ) ) ( t r u et r u et r u et r u en i ln i l ) ( t r u e ?n i l ) n i l ( t r u e ?' ( ) ) n i l t r u e ? behaveslikeifandrejectstheemptylist( ) .

unicode
syntax:(unicodestrutf8) ConvertsASCII/UTF8characterstringsinstrtoUCS4encodedUnicodeof4byteintegerspercharacter.Thestringisterminated witha4byteinteger0 .ThisfunctionisonlyavailableonUTF8enabledversionsofnewLISP.
( u n i c o d e" n e w " ) " n \ 0 0 0 \ 0 0 0 \ 0 0 0 e \ 0 0 0 \ 0 0 0 \ 0 0 0 w \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 " ( u t f 8( u n i c o d e" n e w " ) ) " n e w "

OnbigendianCPUarchitectures,thebyteorderwillbereversedfromhightolow.Theu n i c o d e andutf8functionsaretheinverse ofeachother.ThesefunctionsareonlynecessaryifUCS4Unicodeisinuse.MostsystemsuseUTF8encodingonly.

unify
syntax:(unifyexp1exp2[listenv]) Evaluatesandmatchesexp1andexp2.Expressionsmatchiftheyareequalorifoneoftheexpressionsisanunboundvariable (whichwouldthenbeboundtotheotherexpression).Ifexpressionsarelists,theyarematchedbycomparingsubexpressions. Unboundvariablesstartwithanuppercasecharactertodistinguishthemfromsymbols.u n i f y returnsn i l whentheunification processfails,oritreturnsalistofvariableassociationsonsuccess.Whennovariableswerebound,butthematchisstillsuccessful, u n i f y returnsanemptylist.newLISPusesamodifiedJ.AlanRobinsonunificationalgorithmwithcorrectlyappliedoccurscheck. SeealsoPeterNorvig'spaperaboutacommonunificationalgorithmbug,whichisnotpresentinthisimplementation.

Sinceversion10.4.0theunderscoresymbol_ (ASCII95)matchesanyatom,listorunboundvariableandneverbinds. Likematch,u n i f y isfrequentlyemployedasaparameterfunctorinfind,ref,refallandreplace.


( u n i f y' A' A ) ( ) ;t a u t o l o g y ( u n i f y' A1 2 3 ) ( ( A1 2 3 ) ) ;Ab o u n dt o1 2 3 ( u n i f y' ( AB )' ( xy ) ) ( ( Ax )( By ) ) ;Ab o u n dt ox ,Bb o u n dt oy ( u n i f y' ( AB )' ( Ba b c ) ) ( ( Aa b c )( Ba b c ) ) ;Bi sa l i a sf o rA ( u n i f y' a b c' x y z ) n i l ;f a i l sb e c a u s es y m b o l sa r ed i f f e r e n t ( u n i f y' ( AA )' ( 1 2 34 5 6 ) ) n i l ;f a i l sb e c a u s eAc a n n o tb eb o u n dt od i f f e r e n tv a l u e s ( u n i f y' ( fA )' ( fB ) ) ( ( AB ) ) ;Aa n dBa r ea l i a s e s ( u n i f y' ( fA )' ( gB ) ) n i l ;f a i l sb e c a u s eh e a d so ft e r m sa r ed i f f e r e n t ( u n i f y' ( fA )' ( fAB ) ) n i l ;f a i l sb e c a u s et e r m sa r eo fd i f f e r e n ta r i t y ( u n i f y' ( f( gA ) )' ( fB ) ) ( ( B( gA ) ) ) ;Bb o u n dt o( gA ) ( u n i f y' ( f( gA )A )' ( fBx y z ) ) ( ( B( gx y z ) )( Ax y z ) ) ;Bb o u n dt o( gx y z )At ox y z ( u n i f y' ( fA )' A ) n i l ;f a i l sb e c a u s eo fi n f i n i t eu n i f i c a t i o n( f ( f ( f ) ) ) ( u n i f y' ( Ax y zA )' ( a b cXX ) ) n i l;i n d i r e c ta l i a sAt oXd o e s n ' tm a t c hb o u n dt e r m s ( u n i f y' ( pXYa )' ( pYXX ) ) ' ( ( Ya )( Xa ) ) ) ;Xa l i a sYa n db i n d i n gt o' a ( u n i f y' ( q( pXY )( pYX ) )' ( qZZ ) ) ( ( YX )( Z( pXX ) ) ) ;i n d i r e c ta l i a s ( u n i f y' ( Ab_ )' ( xGz ) )( ( Ax )( Gb ) );_m a t c h e sa t o mz ( u n i f y' ( Abc_ )' ( xG_z ) )( ( Ax )( Gb ) );_n e v e rb i n d s ,m a t c h e sca n dz ( u n i f y' ( Ab_ )' ( xG( xyz ) ) )( ( Ax )( Gb ) );_m a t c h e sl i s t( xyz ) ; ;s o m ee x a m p l e st a k e nf r o mh t t p : / / e n . w i k i p e d i a . o r g / w i k i / U n i f i c a t i o n u n i f y cantakeanoptionalbindingorassociationlistinlistenv.Thisisusefulwhenchainingu n i f y expressionsandtheresultsof

previousu n i f y bindingsmustbeincluded:
( u n i f y' ( fX )' ( f1 2 3 ) ) ( ( X1 2 3 ) ) ( u n i f y' ( AB )' ( XA )' ( ( X1 2 3 ) ) ) ( ( X1 2 3 )( A1 2 3 )( B1 2 3 ) )

Inthepreviousexample,X wasboundto1 2 3 earlierandisincludedinthesecondstatementtoprebindX .

Useu n i f y withe x p a n d
NotethatvariablesarenotactuallyboundasanewLISPassignment.Rather,anassociationlistisreturnedshowingthelogical binding.Aspecialsyntaxofexpandcanbeusedtoactuallyreplaceboundvariableswiththeirterms:
( s e t' b i n d i n g s( u n i f y' ( f( gA )A )' ( fBx y z ) ) ) ( ( B( gx y z ) )( Ax y z ) ) ( e x p a n d' ( f( gA )A )b i n d i n g s ) ( f( gx y z )x y z ) ;o ri no n es t a t e m e n t ( e x p a n d' ( f( gA )A )( u n i f y' ( f( gA )A )' ( fBx y z ) ) ) ( f( gx y z )x y z )

Useu n i f y withb i n d fordestructuring


Thefunctionbindcanbeusedtosetunifiedvariables:

( b i n d( u n i f y' ( f( gA )A )' ( fBx y z ) ) ) Ax y z B( gx y z )

Thiscanbeusedfordestructuring:
( s e t' s t r u c t u r e' ( ( o n e" t w o " )3( f o u r( xyz ) ) ) ) ( s e t' p a t t e r n' ( ( AB )C( DE ) ) ) ( b i n d( u n i f yp a t t e r ns t r u c t u r e ) ) Ao n e B" t w o " C3 Df o u r E( xyz ) u n i f y returnsanassociationlistandb i n d bindstheassociations.

Modelpropositionallogicwithu n i f y
Thefollowingexampleshowshowpropositionallogiccanbemodeledusingu n i f y andexpand:
;i fs o m e b o d yi sh u m a n ,h ei sm o r t a l>( Xh u m a n ): -( Xm o r t a l ) ;s o c r a t e si sh u m a n>( s o c r a t e sh u m a n ) ;i ss o c r a t e sm o r t a l ?>? ( s o c r a t e sm o r t a l ) ( e x p a n d' ( Xm o r t a l ) ( u n i f y' ( Xh u m a n )' ( s o c r a t e sh u m a n ) ) ) ( s o c r a t e sm o r t a l )

Thefollowingisamorecomplexexampleshowingasmall,workingPROLOG(ProgramminginLogic)implementation.
; ;as m a l lP R O L O Gi m p l e m e n t a t i o n ( s e t' f a c t s' ( ( s o c r a t e sp h i l o s o p h e r ) ( s o c r a t e sg r e e k ) ( s o c r a t e sh u m a n ) ( e i n s t e i ng e r m a n ) ( e i n s t e i n( s t u d i e dp h y s i c s ) ) ( e i n s t e i nh u m a n ) ) ) ( s e t' r u l e s' ( ( ( Xm o r t a l )< -( Xh u m a n ) ) ( ( X( k n o w sp h y s i c s ) )< -( Xp h y s i c i s t ) ) ( ( Xp h y s i c i s t )< -( X( s t u d i e dp h y s i c s ) ) ) ) ) ( d e f i n e( q u e r yt r m ) ( o r ( i f( f i n dt r mf a c t s )t r u e )( c a t c h( p r o v e r u l et r m ) ) ) ) ( d e f i n e( p r o v e r u l et r m ) ( d o l i s t( rr u l e s ) ( i f( l i s t ?( s e t' e( u n i f yt r m( f i r s tr ) ) ) ) ( i f( q u e r y( e x p a n d( l a s tr )e ) ) ( t h r o wt r u e ) ) ) ) n i l ) ;t r yi t >( q u e r y' ( s o c r a t e sh u m a n ) ) t r u e >( q u e r y' ( s o c r a t e s( k n o w sp h y s i c s ) ) ) n i l >( q u e r y' ( e i n s t e i n( k n o w sp h y s i c s ) ) ) t r u e

Theprogramhandlesadatabaseoff a c t s andadatabaseofsimpleAisafactifBisafactr u l e s .Afactisproventrueifiteither canbefoundinthef a c t s databaseorifitcanbeprovenusingarule.Rulescanbenested:forexample,toprovethatsomebody ( k n o w sp h y s i c s ) ,itmustbeprovedtruethatsomebodyisap h y s i c i s t .Butsomebodyisonlyaphysicistifthatpersons t u d i e d p h y s i c s .The< symbolseparatingtheleftandrighttermsoftherulesisnotrequiredandisonlyaddedtomaketherulesdatabase morereadable. Thisimplementationdoesnothandlemultipletermsintherightpremisepartoftherules,butitdoeshandlebacktrackingofthe r u l e s databasetotryoutdifferentmatches.Itdoesnothandlebacktrackinginmultiplepremisesoftherule.Forexample,ifinthe followingruleA i fBa n dCa n dD ,thepremisesB andC succeedandD fails,abacktrackingmechanismmightneedtogoback andreunifytheB orA termswithdifferentfactsorrulestomakeD succeed. Theabovealgorithmcouldbewrittendifferentlybyomittingexpandfromthedefinitionofp r o v e r u l e andbypassingthe environment,e ,asanargumenttotheu n i f y andq u e r y functions. Alearningofprovenfactscanbeimplementedbyappendingthemtothef a c t s databaseoncetheyareproven.Thiswouldspeed upsubsequentqueries. LargerPROLOGimplementationsalsoallowtheevaluationoftermsinrules.Thismakesitpossibletoimplementfunctionsfor doingotherworkwhileprocessingruleterms.p r o v e r u l e couldaccomplishthistestingforthesymbole v a l ineachruleterm.

union
syntax:(unionlist1list2[list3...])
u n i o n returnsauniquecollectionlistofdistinctelementsfoundintwoormorelists. ( u n i o n' ( 131443 )' ( 21564 ) ) ( 134256 )

Liketheothersetfunctionsdifference,intersectandunique,u n i o n maintainstheorderofelementsasfoundintheoriginallists.

unique
syntax:(uniquelist) Returnsauniqueversionoflistwithallduplicatesremoved.
( u n i q u e' ( 23446787 ) ) ( 234678 )

Notethatthelistdoesnotneedtobesorted,butasortedlistmakesu n i q u e performfaster. Othersetfunctionsaredifference,intersectandunion.

unless
syntax:(unlessexpconditionbody) Thestatementsinbodyareonlyevaluatedifexpconditionevaluateston i l ortheemptylist( ) .Theresultofthelastexpressionin bodyisreturnedorn i l ortheemptylist( ) ifbodywasnotexecuted.

Becauseu n l e s s doesnothaveanelseconditionasinif,thestatementsinbodyneednottobegroupedwithbegin:
( u n l e s s( s t a r t s w i t h( r e a d l i n e )" q u i t " ) ( p r o c e s s( c u r r e n t l i n e ) ) . . . ( f i n i s h ) )

Seealsothefunctionwhen.

unpack
syntax:(unpackstrformatstraddrpacked) syntax:(unpackstrformatnumaddrpacked) syntax:(unpackstructnumaddrpacked) syntax:(unpackstructstraddrpacked) Whenthefirstparameterisastring,u n p a c k unpacksabinarystructureinstraddrpackedorpointedtobynumaddrpackedinto newLISPvariablesusingtheformatinstrformat.u n p a c k isthereverseoperationofp a c k .Usingnumaddrpackedfacilitatesthe unpackingofstructuresreturnedfromimported,sharedlibraryfunctions. Ifthenumberspecifiedinnumaddrpackedisnotavalidmemoryaddress,asystembuserrororsegfaultcanoccurandcrash newLISPorleaveitinanunstablestate. Whenthefirstparameteristhesymbolofastructdefinition,u n p a c k usestheformatasspecifiedinstruct.Whileu n p a c k withstr formatliterallyunpacksasspecified,u n p a c k withstructwillskipstructurealigningpadbytesdependingondatatype,orderof elementsandCPUarchitecture.Refertothedescriptionofthestructfunctionformoredetail. Thefollowingcharactersmaydefineaformat: format
c b d u l d l u L d L u f l f s n n n > <

description asigned8bitnumber anunsigned8bitnumber asigned16bitshortnumber anunsigned16bitshortnumber asigned32bitlongnumber anunsigned32bitlongnumber asigned64bitlongnumber anunsigned64bitlongnumber afloatin32bitrepresentation adoublefloatin64bitrepresentation astringofnnullpaddedASCIIcharacters nnullcharacters switchestobigendianbyteorder switchestolittleendianbyteorder

( p a c k" ccc "6 56 66 7 ) " A B C " ( u n p a c k" ccc "" A B C " ) ( 6 56 66 7 ) ( s e t' s( p a c k" cdu "1 01 2 3 4 55 6 7 8 9 ) )

( u n p a c k" cdu "s ) ( 1 01 2 3 4 55 6 7 8 9 ) ( s e t' s( p a c k" s 1 0f "" r e s u l t "1 . 2 3 ) ) ( u n p a c k" s 1 0f "s ) ( " r e s u l t \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 "1 . 2 3 0 0 0 0 0 1 9 ) ( s e t' s( p a c k" s 3l f "" r e s u l t "1 . 2 3 ) ) ( u n p a c k" s 3f "s ) ( " r e s "1 . 2 3 ) ( s e t' s( p a c k" cn 7c "1 12 2 ) ) ( u n p a c k" cn 7c "s ) ( 1 12 2 ) )

The> and< specifierscanbeusedtoswitchbetweenlittleendianandbigendianbyteorderwhenpackingorunpacking:


; ;o nal i t t l ee n d i a ns y s t e m( e . g . ,I n t e lC P U s ) ( s e t' b u f f( p a c k" d "1 ) ) " \ 0 0 1 \ 0 0 0 " ( u n p a c k" d "b u f f ) ( 1 ) ( u n p a c k" > d "b u f f ) ( 2 5 6 )

Switchingthebyteorderwillaffectallnumberformatswith16,32,or64bitsizes. Thep a c k andu n p a c k formatneednotbethesame,asinthefollowingexample:


( s e t' s( p a c k" s 3 "" A B C " ) ) ( u n p a c k" ccc "s ) ( 6 56 66 7 )

Theexamplesshowspacesbetweentheformatspecifiers.Althoughnotrequired,theycanimprovereadability. Ifthebuffer'ssizeatamemoryaddressissmallerthantheformattingstringspecifies,someformattingcharactersmaybeleftunused. Seealsotheaddress,getint,getlong,getchar,getstring,andpackfunctions.

until
syntax:(untilexpcondition[body]) Evaluatestheconditioninexpcondition.Iftheresultisn i l ortheemptylist( ) ,theexpressionsinbodyareevaluated.Evaluationis repeateduntiltheexpconditionresultsinavalueotherthann i l ortheemptylist.Theresultofthelastexpressionevaluatedinbody isthereturnvalueoftheu n t i l expression.Ifbodyisempty,theresultoflastexpconditionisreturned.u n t i l workslike(while (not)).
u n t i l alsoupdatesthesystemiteratorsymbol$ i d x . ( d e v i c e( o p e n" s o m e f i l e . t x t "" r e a d " ) ) ( s e t' l i n e c o u n t0 ) ( u n t i l( n o t( r e a d l i n e ) )( i n cl i n e c o u n t ) ) ( c l o s e( d e v i c e ) ) ( p r i n t" t h ef i l eh a s"l i n e c o u n t"l i n e s \ n " )

Usethedountilfunctiontotesttheconditionafterevaluationofthebodyexpressions.

uppercaseutf8
syntax:(uppercasestr) Returnsacopyofthestringinstrconvertedtouppercase.Internationalcharactersareconvertedcorrectly.

( u p p e r c a s e" h e l l ow o r l d " ) " H E L L OW O R L D "

Seealsothelowercaseandtitlecasefunctions.

utf8
syntax:(utf8strunicode) ConvertsaUCS4,4byte,Unicodeencodedstring(str)intoUTF8.ThisfunctionisonlyavailableonUTF8enabledversionsof newLISP.
( u n i c o d e" n e w " ) " n \ 0 0 0 \ 0 0 0 \ 0 0 0 e \ 0 0 0 \ 0 0 0 \ 0 0 0 w \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 \ 0 0 0 " ( u t f 8( u n i c o d e" n e w " ) ) " n e w "

Theu t f 8 functioncanalsobeusedtotestforthepresenceofUTF8enablednewLISP:
( i fu t f 8( d o u t f 8 v e r s i o n o f c o d e )( d o a s c i i v e r s i o n o f c o d e ) )

OnbigendianCPUarchitectures,thebyteorderwillbereversedfromhighesttolowest.Theu t f 8 andunicodefunctionsarethe inverseofeachother.ThesefunctionsareonlynecessaryifUCS4Unicodeisinuse.MostsystemsuseUTF8Unicodeencoding only.

utf8len
syntax:(utf8lenstr) ReturnsthenumberofcharactersinaUTF8encodedstring.UTF8characterscanbeencodedinmorethanone8bitbyte. u t f 8 l e n returnsthenumberofUTF8charactersinastring.ThisfunctionisonlyavailableonUTF8enabledversionsof newLISP.
( u t f 8 l e n" " ) ( l e n g t h" " ) 1 2 3 6

Seealsotheunicodeandutf8functions.AboveChinesetextfromUTF8Sampler.

uuid
syntax:(uuid[strnode]) ConstructsandreturnsaUUID(UniversallyUniqueIDentifier).Withoutanodespecinstrnode,atype4UUIDrandomgenerated bytenumberisreturned.Whentheoptionalstrnodeparameterisused,atype1UUIDisreturned.Thestringinstrnodespecifiesa validMAC(MediaAccessCode)fromanetworkadapterinstalledonthenodeorarandomnodeID.WhenarandomnodeIDis specified,theleastsignificantbitofthefirstnodebyteshouldbesetto1toavoidclasheswithrealMACidentifiers.UUIDsoftype 1withnodeIDaregeneratedfromatimestampandotherdata.SeeRFC4122fordetailsonUUIDgeneration.
; ;t y p e4U U I Df o ra n ys y s t e m ( u u i d ) " 4 9 3 A A D 6 1 2 6 6 F 4 8 A 9 B 9 9 A 3 3 9 4 1 B E E 3 6 0 7 "

; ;t y p e1U U I Dp r e f e r r e df o rd i s t r i b u t e ds y s t e m s ; ;c o n f i g u r en o d eI Df o re t h e r0 0 : 1 4 : 5 1 : 0 a : e 0 : b c ( s e t' i d( p a c k" c c c c c c "0 x 0 00 x 1 40 x 5 10 x 0 a0 x e 00 x b c ) ) ( u u i d i d ) " 0 7 4 9 1 6 1 C 2 E C 2 1 1 D B B B B 2 0 0 1 4 5 1 0 A E 0 B C "

Eachinvocationoftheu u i d functionwillyieldanewuniqueUUID.TheUUIDsaregeneratedwithoutsystemwidesharedstable store(seeRFC4122).IfthesystemgeneratingtheUUIDsisdistributedoverseveralnodes,thentype1generationshouldbeused withadifferentnodeIDoneachnode.Forseveralprocessesonthesamenode,validUUIDsareguaranteedevenifrequestedatthe sametime.ThisisbecausetheprocessIDofthegeneratingnewLISPprocessispartoftheseedfortherandomnumbergenerator. Whentype4IDsareusedonadistributedsystem,twoidenticalUUID'sarestillhighlyunlikelyandimpossiblefortype1IDsif realMACaddressesareused.

waitpid
syntax:(waitpidintpid[intoptions|n i l ]) Waitsforachildprocessspecifiedinintpidtoend.Thechildprocesswaspreviouslystartedwithprocessorfork.Whenthechild processspecifiedinintpidends,alistofpidandstatusvalueisreturned.Thestatusvaluedescribesthereasonforterminationofthe childprocess.TheinterpretationofthereturnedstatusvaluediffersbetweenLinuxandotherflavorsofUnix.Consultthe Linux/Unixmanpagesforthew a i t p i d command(withoutthehyphenusedinnewLISP)forfurtherinformation. When1 isspecifiedforintpid,pidandstatusinformationofanychildprocessstartedbytheparentarereturned.When0 is specified,w a i t p i d onlywatcheschildprocessesinthesameprocessgroupasthecallingprocess.Anyothernegativevalueforint pidreportschildprocessesinthesameprocessgroupasspecifiedwithanegativesigninintpid. Anoptioncanbespecifiedinintoption.SeeLinux/Unixdocumentationfordetailsonintegervaluesforintoptions.Asan alternative,n i l canbespecified.Thisoptioncausesw a i t p i d tobenonblocking,returningrightawaywitha0 inthepidofthe listreturned.Thisoptionusedtogetherwithanintpidparameterof1 canbeusedtocontinuouslyloopandactonreturnedchild processes. ThisfunctionisonlyavailableonMacOSX,LinuxandotherUnixlikeoperatingsystems.
( s e t' p i d( f o r k( m y p r o c e s s ) ) )8 5 9 6 ( s e t' r e t( w a i t p i dp i d ) ) ( 8 5 9 60 );c h i l dh a se x i t e d ( p r i n t l n" p r o c e s s :"p i d"h a sf i n i s h e dw i t hs t a t u s :"( l a s tr e t ) )

Theprocessm y p r o c e s s isstarted,thenthemainprogramblocksinthew a i t p i d calluntilm y p r o c e s s hasfinished.

when
syntax:(whenexpconditionbody) Thestatementsinbodyareonlyevaluatedifexpconditionevaluatestoanythingnotn i l andnottheemptylist( ) .Theresultofthe lastexpressioninbodyisreturnedorn i l ortheemptylist( ) ifbodywasnotexecuted. Becausew h e n doesnothaveanelseconditionasinif,thestatementsinbodyneednottobegroupedwithbegin:
( w h e n( r e a d l i n e ) ( s e t' r e s u l t( a n a l y z e( c u r r e n t l i n e ) ) )

( r e p o r tr e s u l t ) ( f i n i s h )

Seealsothefunctionunlessworkinglike( w h e n( n o t. . . ). . . ) .

while
syntax:(whileexpconditionbody) Evaluatestheconditioninexpcondition.Iftheresultisnotn i l ortheemptylist( ) ,theexpressionsinbodyareevaluated. Evaluationisrepeateduntilanexpconditionresultsinn i l ortheemptylist( ) .Theresultofthebody'slastevaluatedexpressionis thereturnvalueofthew h i l e expression.
w h i l e alsoupdatesthesystemiteratorsymbol$ i d x . ( d e v i c e( o p e n" s o m e f i l e . t x t "" r e a d " ) ) ( s e t' l i n e c o u n t0 ) ( w h i l e( r e a d l i n e )( i n cl i n e c o u n t ) ) ( c l o s e( d e v i c e ) ) ( p r i n t" t h ef i l eh a s"l i n e c o u n t"l i n e s \ n " )

Usethedowhilefunctiontoevaluatetheconditionafterevaluatingthebodyofexpressions.

write!
syntax:(writeintfilestrbuffer[intsize]) syntax:(writestrstrbuffer[intsize]) Thefunctionw r i t e writesintsizebytesfromabufferinstrbuffertoafilespecifiedinintfile,previouslyobtainedfromafileo p e n operation.Ifintsizeisnotspecified,alldatainsymbufferorstrbufferiswritten.w r i t e returnsthenumberofbyteswrittenorn i l onfailure.
w r i t e isashorterwritingofw r i t e b u f f e r .Thelongerformstillworksbutisdeprecatedandshouldbeavoidedinnewcode. ( s e t' h a n d l e( o p e n" m y f i l e . e x t "" w r i t e " ) ) ( w r i t eh a n d l ed a t a1 0 0 ) ( w r i t eh a n d l e" aq u i c km e s s a g e \ n " )

Thecodeintheexamplewrites100bytestothefilem y f i l e . e x t fromthecontentsind a t a . Inthesecondsyntax,w r i t e canbeusedfordestructivestringappending:


( s e t' s t r" " ) ( w r i t es t r" h e l l ow o r l d " ) s t r " h e l l ow o r l d "

Seealsothereadfunction.

writechar

syntax:(writecharintfileintbyte1[intbyte2...]) Writesabytespecifiedinintbytetoafilespecifiedbythefilehandleinintfile.Thefilehandleisobtainedfromapreviouso p e n operation.Eachw r i t e c h a r advancesthefilepointerbyone8bitbyte.


w r i t e c h a r returnsthenumberofbyteswritten. ( d e f i n e( s l o w f i l e c o p yf r o m f i l et o f i l e ) ( s e t' i n f i l e( o p e nf r o m f i l e" r e a d " ) ) ( s e t' o u t f i l e( o p e nt o f i l e" w r i t e " ) ) ( w h i l e( s e t' c h r( r e a d c h a ri n f i l e ) ) ( w r i t e c h a ro u t f i l ec h r ) ) ( c l o s ei n f i l e ) ( c l o s eo u t f i l e ) " f i n i s h e d " )

Usetheprintanddevicefunctionstowritelargerportionsofdataatatime.NotethatnewLISPalreadysuppliesafasterbuiltin functioncalledcopyfile. Seealsothereadcharfunction.

writefile
syntax:(writefilestrfilenamestrbuffer) Writesafileinstrfilenamewithcontentsinstrbufferinoneswoopandreturnsthenumberofbyteswritten. Onfailurethefunctionreturnsn i l .Forerrorinformation,usesyserrorwhenusedonfiles.WhenusedonURLsneterrorgives moreerrorinformation.
( w r i t e f i l e" m y f i l e . e n c " ( e n c r y p t( r e a d f i l e" / h o m e / l i s p / m y F i l e " )" s e c r e t " ) )

Thefilem y f i l e isread,encryptedusingthepasswords e c r e t ,andwrittenbackintothenewfilem y f i l e . e n c inthecurrent directory.


w r i t e f i l e cantakeanh t t p : / / orf i l e : / / URLinstrfilename.Whentheprefixh t t p : / / isused,w r i t e f i l e worksexactly

likeputurlandcantakethesameadditionalparameters:
( w r i t e f i l e" h t t p : / / a s i t e . c o m / m e s s a g e . t x t "" T h i si sam e s s a g e ")

Thefilem e s s a g e . t x t iscreatedandwrittenataremotelocation,h t t p : / / a s i t e . c o m ,withthecontentsofstrbuffer.Inthismode, w r i t e f i l e canalsobeusedtotransferfilestoremotenewLISPservernodes. Seealsotheappendfileandreadfilefunctions.

writeline!
syntax:(writeline[intfile[str]]) syntax:(writelinestrout[str]]) Thestringinstrandthelineterminationcharacter(s)arewrittentothedevicespecifiedinintfile.Whenthestringargumentis omittedw r i t e l i n e writesthecontentsofthelastreadlinetointfileIfthefirstargumentisomittedtoothenitwritestotostandard out(STDOUT)ortowhateverdeviceissetbydevice.

Inthesecondsyntaxlinesareappendedtoastringinstrout.
w r i t e l i n e returnsthenumberofbyteswritten. ( s e t' o u t f i l e( o p e n" m y f i l e "" w r i t e " ) ) ( w r i t e l i n eo u t f i l e" h e l l ot h e r e " ) ( c l o s eo u t f i l e ) ( s e t' m y F i l e( o p e n" i n i t . l s p "" r e a d " ) ( w h i l e( r e a d l i n em y F i l e )( w r i t e l i n e ) ) ( s e t' s t r" " ) ( w r i t e l i n es t r" h e l l o " ) ( w r i t e l i n es t r" w o r l d " ) s t r " h e l l o \ n w o r l d \ n "

Thefirstexampleopens/createsafile,writesalinetoit,andclosesthefile.Thesecondexampleshowstheusageofw r i t e l i n e withoutarguments.Thecontentsofi n i t . l s p arewrittentotheconsolescreen. Seealsothefunctionwriteforwritingtoadevicewithoutthelineterminatingcharacter.

xferevent
syntax:(xfereventsymeventhandler|funceventhandler) RegistersafunctioninsymbolsymeventhandlerorinlambdafunctionfunceventhandlertomonitorHTTPbytetransfersinitiated bygeturl,posturlorputurlorinitiatedbyfilefunctionswhichcantakeURLslikeload,save,readfile,writefileandappendfile. E.g.wheneverablockofdatarequestedwithgeturlarrives,thefunctioninsymorfuncwillbecalledwiththenumberofbytes transferred.Likewisewhensendingdatawithposturloranyoftheotherdatasendingfunctions,symorfuncwillbecalledwiththe numberofbytestransferredforeachblockofdatatransferred.
( x f e r e v e n t( f n( n )( p r i n t l n" > "n ) ) ) ( l e n g t h( g e t u r l" h t t p : / / n e w l i s p . o r g " ) ) > 7 3 > 7 9 9 > 1 4 5 2 > 3 5 1 > 1 0 9 3 > 3 5 2 > 2 1 1 > 8 8 5 > 5 6 4 > 8 8 4 > 5 6 1 > 7 5 > 8 1 2 > 6 3 8 > 1 4 5 2 > 8 0 1 > 5 > 9 2 7 1 1 9 3 5

Thecomputeroutputisshowninbold.Wheneverablockofdataisreceiveditsbytesizeisprinted.Insteadofdefiningthehandler functiondirectorywithalambdafunctioninfunc,asymbolcontainingafunctiondefinitioncouldhavebeenused:
( d e f i n e( r e p o r tn )( p r i n t l n" > "n ) ) ( x f e r e v e n t' r e p o r t )

ThiscanbeusedtomonitortheprogressoflongerlastingbytetransfersinHTTPuploadsordownloads.

xmlerror
syntax:(xmlerror) Returnsalistoferrorinformationfromthelastxmlparseoperationotherwise,returnsn i l ifnoerroroccurred.Thefirstelement containstextdescribingtheerror,andthesecondelementisanumberindicatingthelastscanpositioninthesourceXMLtext, startingat0 (zero).
( x m l p a r s e" < a t a g > h e l l o < / a t a g > < f i n " ) n i l ( x m l e r r o r ) ( " e x p e c t e dc l o s i n gt a g :> "1 8 )

xmlparse
syntax:(xmlparsestringxml[intoptions[symcontext[funccallback]]]) ParsesastringcontainingXML1.0compliant,wellformedXML.x m l p a r s e doesnotperformDTDvalidation.ItskipsDTDs (DocumentTypeDeclarations)andprocessinginstructions.NodesoftypeELEMENT,TEXT,CDATA,andCOMMENTare parsed,andanewLISPliststructureisreturned.Whenanelementnodedoesnothaveattributesorchildnodes,itinsteadcontains anemptylist.Attributesarereturnedasassociationlists,whichcanbeaccessedusingassoc.Whenx m l p a r s e failsdueto malformedXML,n i l isreturnedandxmlerrorcanbeusedtoaccesserrorinformation.
( s e t' x m l " < p e r s o nn a m e = ' J o h nD o e 't e l = ' 5 5 5 1 2 1 2 ' > n i c eg u y < / p e r s o n > " ) ( x m l p a r s ex m l ) ( ( " E L E M E N T "" p e r s o n " ( ( " n a m e "" J o h nD o e " ) ( " t e l "" 5 5 5 1 2 1 2 " ) ) ( ( " T E X T "" n i c eg u y " ) ) ) )

Modifyingthetranslationprocess.
Optionally,theintoptionsparametercanbespecifiedtosuppresswhitespace,emptyattributelists,andcomments.Itcanalsobe usedtotransformtagsfromstringsintosymbols.Anotherfunction,xmltypetags,servesfortranslatingtheXMLtags.The followingoptionnumberscanbeused: option description 1 suppresswhitespacetexttags 2 4 8 16 suppressemptyattributelists suppresscommenttags translatestringtagsintosymbols addSXML(SexpressionXML)attributetags(@...)

Optionscanbecombinedbyaddingthenumbers(e.g.,3 wouldcombinetheoptionsforsuppressingwhitespacetexttags/infoand emptyattributelists). Thefollowingexamplesshowhowthedifferentoptionscanbeused:

XMLsource:
< ? x m lv e r s i o n = " 1 . 0 "? > < D A T A B A S En a m e = " e x a m p l e . x m l " > < ! T h i si sad a t a b a s eo ff r u i t s > < F R U I T > < N A M E > a p p l e < / N A M E > < C O L O R > r e d < / C O L O R > < P R I C E > 0 . 8 0 < / P R I C E > < / F R U I T > < F R U I T > < N A M E > o r a n g e < / N A M E > < C O L O R > o r a n g e < / C O L O R > < P R I C E > 1 . 0 0 < / P R I C E > < / F R U I T > < F R U I T > < N A M E > b a n a n a < / N A M E > < C O L O R > y e l l o w < / C O L O R > < P R I C E > 0 . 6 0 < / P R I C E > < / F R U I T > < / D A T A B A S E >

Parsingwithoutanyoptions:
( x m l p a r s e( r e a d f i l e" e x a m p l e . x m l " ) ) ( ( " E L E M E N T "" D A T A B A S E "( ( " n a m e "" e x a m p l e . x m l " ) )( ( " T E X T "" \ r \ n \ t " ) ( " C O M M E N T "" T h i si sad a t a b a s eo ff r u i t s " ) ( " T E X T "" \ r \ n \ t " ) ( " E L E M E N T "" F R U I T "( )( ( " T E X T "" \ r \ n \ t \ t " )( " E L E M E N T "" N A M E "( ) ( ( " T E X T "" a p p l e " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" C O L O R "( )( ( " T E X T "" r e d " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" P R I C E "( )( ( " T E X T "" 0 . 8 0 " ) ) ) ( " T E X T "" \ r \ n \ t " ) ) ) ( " T E X T "" \ r \ n \ r \ n \ t " ) ( " E L E M E N T "" F R U I T "( )( ( " T E X T "" \ r \ n \ t \ t " )( " E L E M E N T "" N A M E "( ) ( ( " T E X T "" o r a n g e " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" C O L O R "( )( ( " T E X T "" o r a n g e " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" P R I C E "( )( ( " T E X T "" 1 . 0 0 " ) ) ) ( " T E X T "" \ r \ n \ t " ) ) ) ( " T E X T "" \ r \ n \ r \ n \ t " ) ( " E L E M E N T "" F R U I T "( )( ( " T E X T "" \ r \ n \ t \ t " )( " E L E M E N T "" N A M E "( ) ( ( " T E X T "" b a n a n a " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" C O L O R "( )( ( " T E X T "" y e l l o w " ) ) ) ( " T E X T "" \ r \ n \ t \ t " ) ( " E L E M E N T "" P R I C E "( )( ( " T E X T "" 0 . 6 0 " ) ) ) ( " T E X T "" \ r \ n \ t " ) ) ) ( " T E X T "" \ r \ n " ) ) ) )

TheT E X T elementscontainingonlywhitespacemaketheoutputveryconfusing.Asthedatabaseine x a m p l e . x m l onlycontains data,wecansuppresswhitespace,emptyattributelistsandcommentswithoption( +124 ) :

FilteringwhitespaceTEXT,COMMENTtags,andemptyattributelists:
( x m l p a r s e( r e a d f i l e" e x a m p l e . x m l " )( +124 ) ) ( ( " E L E M E N T "" D A T A B A S E "( ( " n a m e "" e x a m p l e . x m l " ) )( ( " E L E M E N T "" F R U I T "( ( " E L E M E N T "" N A M E "( ( " T E X T "" a p p l e " ) ) ) ( " E L E M E N T "" C O L O R "( ( " T E X T "" r e d " ) ) ) ( " E L E M E N T "" P R I C E "( ( " T E X T "" 0 . 8 0 " ) ) ) ) ) ( " E L E M E N T "" F R U I T "( ( " E L E M E N T "" N A M E "( ( " T E X T "" o r a n g e " ) ) ) ( " E L E M E N T "" C O L O R "( ( " T E X T "" o r a n g e " ) ) ) ( " E L E M E N T "" P R I C E "( ( " T E X T "" 1 . 0 0 " ) ) ) ) )

( " E L E M E N T "" F R U I T "( ( " E L E M E N T "" N A M E "( ( " T E X T "" b a n a n a " ) ) ) ( " E L E M E N T "" C O L O R "( ( " T E X T "" y e l l o w " ) ) ) ( " E L E M E N T "" P R I C E "( ( " T E X T "" 0 . 6 0 " ) ) ) ) ) ) ) )

Theresultingoutputlooksmuchmorereadable,butitcanstillbeimprovedbyusingsymbolsinsteadofstringsforthetags "FRUIT","NAME","COLOR",and"PRICE",aswellasbysuppressingtheXMLtypetags"ELEMENT"and"TEXT" completelyusingthexmltypetagsdirective.

SuppressingXMLtypetagswithxmltypetagsandtranslatingstringtagsintosymboltags:
; ;s u p p r e s sa l lX M Lt y p et a g sf o rT E X Ta n dE L E M E N T ; ;i n s t e a do f" C D A T A " ,u s ec d a t aa n di n s t e a do f" C O M M E N T " ,u s e! ( x m l t y p e t a g sn i l' c d a t a' ! -n i l ) ; ;t u r no na l lo p t i o n sf o rs u p p r e s s i n gw h i t e s p a c ea n de m p t y ; ;a t t r i b u t e s ,t r a n s l a t et a g st os y m b o l s ( x m l p a r s e( r e a d f i l e" e x a m p l e . x m l " )( +128 ) ) ( ( D A T A B A S E( ( " n a m e "" e x a m p l e . x m l " ) ) ( ! -" T h i si sad a t a b a s eo ff r u i t s " ) ( F R U I T( N A M E" a p p l e " )( C O L O R" r e d " )( P R I C E" 0 . 8 0 " ) ) ( F R U I T( N A M E" o r a n g e " )( C O L O R" o r a n g e " )( P R I C E" 1 . 0 0 " ) ) ( F R U I T( N A M E" b a n a n a " )( C O L O R" y e l l o w " )( P R I C E" 0 . 6 0 " ) ) ) )

Whentagsaretranslatedintosymbolsbyusingoption8 ,acontextcanbespecifiedinsymcontext.Ifnocontextisspecified,all symbolswillbecreatedinsidethecurrentcontext.


( x m l t y p e t a g sn i ln i ln i ln i l ) ( x m l p a r s e" < m s g > H e l l oW o r l d < / m s g > "( +12481 6 )' C T X ) ( ( C T X : m s g" H e l l oW o r l d " ) )

Specifyingn i l fortheXMLtypetagsTEXTandELEMENTmakesthemdisappear.Atthesametime,parenthesesofthechild nodelistareremovedsothatchildnodesnowappearasmembersofthelist,startingwiththetagsymboltranslatedfromthestring tags"FRUIT","NAME",etcetera.

ParsingintoSXML(SexpressionsXML)format:
UsingxmltypetagstosuppressallXMLtypetagsalongwiththeoptionnumbers1 ,2 ,4 ,8 ,and1 6 SXMLformattedoutput canbegenerated:
( x m l t y p e t a g sn i ln i ln i ln i l ) ( x m l p a r s e( r e a d f i l e" e x a m p l e . x m l " )( +12481 6 ) ) ( ( D A T A B A S E( @( n a m e" e x a m p l e . x m l " ) ) ( F R U I T( N A M E" a p p l e " )( C O L O R" r e d " )( P R I C E" 0 . 8 0 " ) ) ( F R U I T( N A M E" o r a n g e " )( C O L O R" o r a n g e " )( P R I C E" 1 . 0 0 " ) ) ( F R U I T( N A M E" b a n a n a " )( C O L O R" y e l l o w " )( P R I C E" 0 . 6 0 " ) ) ) )

IftheoriginalXMLtagscontainanamespacepartseparatedbya: ,thatcolonwillbetranslatedintoa. dotintheresulting newLISPsymbol. Notethatusingoptionnumber1 6 causesan@ (atsymbol)tobeaddedtoattributelists. SeealsothexmltypetagsfunctionforfurtherinformationonXMLparsing.

Parsingintoaspecifiedcontext
WhenparsingXMLexpressions,XMLtagsaretranslatedintonewLISPsymbols,whenoption8isspecified.Thesymcontext optionspecifiesthetargetcontextforthesymbolcreation:
( x m l t y p e t a g sn i ln i ln i ln i l ) ( x m l p a r s e( r e a d f i l e" e x a m p l e . x m l " )( +12481 6 )' C T X ) ( ( C T X : D A T A B A S E( @( C T X : n a m e" e x a m p l e . x m l " ) ) ( C T X : F R U I T( C T X : N A M E" a p p l e " )( C T X : C O L O R" r e d " )( C T X : P R I C E" 0 . 8 0 " ) )

( C T X : F R U I T( C T X : N A M E" o r a n g e " )( C T X : C O L O R" o r a n g e " )( C T X : P R I C E" 1 . 0 0 " ) ) ( C T X : F R U I T( C T X : N A M E" b a n a n a " )( C T X : C O L O R" y e l l o w " )( C T X : P R I C E" 0 . 6 0 " ) ) ) )

Ifthecontextdoesnotexist,itwillbecreated.Ifitexists,thequotecanbeomittedorthecontextcanbereferredtobyavariable.

Usingacallbackfunction
Normally,x m l p a r s e willnotreturnuntilallparsinghasfinished.Usingthefunccallbackoption,x m l p a r s e willcallbackafter eachtagclosingwiththegeneratedSexpressionandastartpositionandlengthinthesourceXML:
; ;d e m oc a l l b a c kf e a t u r e ( d e f i n e( x m l c a l l b a c ks e x p rs t a r ts i z e ) ( i f( o r( =( s e x p r0 )' N A M E )( =( s e x p r0 )' C O L O R )( =( s e x p r0 )' P R I C E ) ) ( b e g i n ( p r i n t" p a r s e de x p r e s s i o n : "s e x p r ) ( p r i n t l n" ,s o u r c e : "( s t a r ts i z ee x a m p l e x m l ) ) ) ) ) ( x m l t y p e t a g sn i l' c d a t a' ! -n i l ) ( x m l p a r s e ( r e a d f i l e" e x a m p l e . x m l " )( +128 )M A I Nx m l c a l l b a c k )

Thefollowingoutputwillbegeneratedbythecallbackfunctionx m l c a l l b a c k :
p a r s e de x p r e s s i o n : ( N A M E" a p p l e " ) ,s o u r c e : < N A M E > a p p l e < / N A M E > p a r s e de x p r e s s i o n : ( C O L O R" r e d " ) ,s o u r c e : < C O L O R > r e d < / C O L O R > p a r s e de x p r e s s i o n : ( P R I C E" 0 . 8 0 " ) ,s o u r c e : < P R I C E > 0 . 8 0 < / P R I C E > p a r s e de x p r e s s i o n : ( N A M E" o r a n g e " ) ,s o u r c e : < N A M E > o r a n g e < / N A M E > p a r s e de x p r e s s i o n : ( C O L O R" o r a n g e " ) ,s o u r c e : < C O L O R > o r a n g e < / C O L O R > p a r s e de x p r e s s i o n : ( P R I C E" 1 . 0 0 " ) ,s o u r c e : < P R I C E > 1 . 0 0 < / P R I C E > p a r s e de x p r e s s i o n : ( N A M E" b a n a n a " ) ,s o u r c e : < N A M E > b a n a n a < / N A M E > p a r s e de x p r e s s i o n : ( C O L O R" y e l l o w " ) ,s o u r c e : < C O L O R > y e l l o w < / C O L O R > p a r s e de x p r e s s i o n : ( P R I C E" 0 . 6 0 " ) ,s o u r c e : < P R I C E > 0 . 6 0 < / P R I C E >

Theexamplecallbackhandlerfunctionfiltersthetagsofinterestandprocessesthemastheyoccur.

xmltypetags
syntax:(xmltypetags[exptexttagexpcdatatagexpcommenttagexpelementtags]) CansuppresscompletelyorreplacetheXMLtypetags"TEXT","CDATA","COMMENT",and"ELEMENT"withsomething elsespecifiedintheparameters. Notethatx m l t y p e t a g s onlysuppressesortranslatesthetagsthemselvesbutdoesnotsuppressormodifythetaggedinformation. Thelatterwouldbedoneusingoptionnumbersinxmlparse. Usingx m l t y p e t a g s withoutargumentsreturnsthecurrenttypetags:
( x m l t y p e t a g s ) ( " T E X T "" C D A T A "" C O M M E N T "" E L E M E N T " ) ( x m l t y p e t a g sn i l' c d a t a' ! -n i l )

Thefirstexamplejustshowsthecurrentlyusedtypetags.Thesecondexamplespecifiessuppressionofthe"TEXT"and "ELEMENT"tagsandshowsc d a t a and! insteadof"CDATA"and"COMMENT".

zero?

syntax:(zero?exp) Checkstheevaluationofexptoseeifitequals0 (zero).


( s e t' v a l u e1 . 2 ) ( s e t' v a r0 ) ( z e r o ?v a l u e ) n i l ( z e r o ?v a r ) t r u e ( m a pz e r o ?' ( 00 . 03 . 44 ) ) ( t r u et r u en i ln i l ) ( m a pz e r o ?' ( n i lt r u e00 . 0" "( ) ) ) ( n i ln i lt r u et r u en i ln i l ) z e r o ? willreturnn i l ondatatypesotherthannumbers.

()

newLISPAPPENDIX Errorcodes
description notenoughmemory environmentstackoverflow callstackoverflow problemaccessingfile notanexpression missingparenthesis stringtokentoolong missingargument numberorstringexpected valueexpected stringexpected symbolexpected contextexpected symbolorcontextexpected listexpected listorarrayexpected listorsymbolexpected listorstringexpected listornumberexpected arrayexpected array,listorstringexpected lambdaexpected no 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

lambdamacroexpected invalidfunction invalidlambdaexpression invalidmacroexpression invalidletparameterlist problemsavingfile divisionbyzero matrixexpected wrongdimensions matrixissingular syntaxinregularexpression throwwithoutcatch problemloadinglibrary importfunctionnotfound symbolisprotected errornumbertoohigh regularexpression missingendoftext[/text]

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

mismatchinnumberofarguments 41 probleminformatstring 42 datatypeandformatdon'tmatch 43 invalidparameter invalidparameter:0.0 invalidparameter:NaN invalidUTF8string illegalparametertype symbolnotinMAINcontext symbolnotincurrentcontext targetcannotbeMAIN listindexoutofbounds arrayindexoutofbounds stringindexoutofbounds nestingleveltoodeep listreferencechanged invalidsyntax usererror userreset receivedSIGINT functionisnotreentrant localsymbolisprotected noreferencefound listisempty I/Oerror workingdirectorynotfound invalidPID cannotopensocketpair 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

cannotforkprocess nocommchannelfound

69 70

ErrorcodesextendedFFI
description invalidFFItype FFIstructexpected no 72 73 FFIpreparationfailed 71

TCP/IPandUDPErrorCodes
no description 1 Cannotopensocket 2 DNSresolutionfailed 3 Notavalidservice 4 Connectionfailed 5 Acceptfailed 6 Connectionclosed 7 Connectionbroken 8 Socketsend()failed 9 Socketrecv()failed 10 Cannotbindsocket 11 Toomanysocketsinnetselect 12 Listenfailed 13 BadlyformedIP 14 Selectfailed 15 Peekfailed 16 Notavalidsocket 17 Cannotunblocksocket 18 Operationtimedout 19 HTTPbadformedURL 20 HTTPfileoperationfailed 21 HTTPtransferfailed 22 HTTPinvalidresponsefromserver 23 HTTPnoresponsefromserver 24 HTTPdocumentempty 25 HTTPerrorinheader 26 HTTPerrorinchunkedformat

SystemSymbolsandConstants
Variableschangedbythesystem
newLISPmaintainsseveralinternalsymbolvariables.Allofthemareglobalandcanbeusedbytheprogrammer.Somehavewrite protection,othersareusersettable.Somewillchangewhenusedinasubexpressionoftheenclosingexpressionusingit.Othersare safewhenusingreentrantinnestedfunctionsorexpressions. Allsymbolsstartingwiththe$ characterwillnotbeserializedwhenusingthesaveorsourcefunctions. variablename
$ 0-$ 1 5 $ a r g s $ c o u n t

purpose

protected reentrant no yes no yes

Usedprimarilyinregularexpressions.$ 0 isalsousedtorecordthelaststateorcountof no executionofsomefunctions. Containsthelistparametersnotboundtolocalvariables.Normallythefunctionargsis yes usedtoretrievethecontentsofthisvariable. Thecountofelementsmatchingwhenusingfindall,replace,refallandsetrefallor thecountofcharactersprocessedbyreadexpr. yes

Thefunctiondolistmaintainsthisasalistindexoroffset.Thefunctionsmap,series, while,until,dowhileanddountilmaintainthisvariableasaniterationcounterstarting yes with0(zero)forthefirstiteration. Theanaphoric$ i t referstotheresultinsideanexecutingexpression,i.e.inself referentialassignments.$ i t isonlyavailableinsidethefunctionexpressionsettingit, $ i t yes andissetton i l onexitofthatexpression.Thefollowingfunctionsuseit:hashes,find all,replace,setref,setrefallandsetfsetq. ContainsthelistofcommandlineargumentspassedbytheOStonewLISPwhenit $ m a i n a r g s yes wasstarted.Normallythefunctionmainargsisusedtoretrievethecontents.
$ i d x

no

n/a

Predefinedvariablesandfunctions.
Thesearepresetsymbolconstants.Twoofthemareusedasnamespacetemplates,onetwowriteplatformindependentcode. name purpose protected reentrant n/a

IsthepredefinedgeneralFOOPclassconstructorwhichcanbeusedtogetherwithn e w to createnewFOOPclasses,e.g:( n e wC l a s s' R e c t a n g l e ) wouldcreateaclassandobject C l a s s no constructorforauserclassR e c t a n g l e .SeetheFOOPclassesandconstructorschapterinthe usersmanualfordetails. ContainsastringidentifyingtheOSPlatformforwhichtherunningnewLISPversionhas o s t y p e yes beencompiled.Seethereferencesectionfordetails Isapredefinednamespacetoserveasahashlikedictionary.Insteadofwriting( d e f i n e T r e e F o o : F o o ) tocreateaF o o dictionary,theexpression( n e wT r e e' F o o ) canbeusedaswell. no SeethechapterHashfunctionsanddictionariesfoedetails.
m o d u l e

n/a n/a n/a

Isapredefinedfunctiontoloadmodules.Insteadofusingl o a d togetherwiththeN E W L I S P D I R no environmentvariable,them o d u l e functionloadsautomaticallyfrom$ N E W L I S P D I R / m o d u l e s / .

ThesymbolsC l a s s ,T r e e andm o d u l e arepredefinedasfollows:


;b u i l t i nt e m p l a t ef o rF O O Pc o n s t r u c t o r s ;u s a g e :( n e wC l a s s' M y C l a s s ) ( d e f i n e( C l a s s : C l a s s ) ( c o n s( c o n t e x t )( a r g s ) ) ) ;b u i l t i nt e m p l a t ef o rh a s h e s ;u s a g e :( n e wT r e e' M y H a s h ) ( d e f i n eT r e e : T r e e )

;l o a dm o d u l e sf r o ms t a n d a r dp a t h ;u s a g e( m o d u l e" m y m o d u l e . l s p " ) ( d e f i n e( m o d u l e$ x ) ( l o a d( a p p e n d( e n v" N E W L I S P D I R " )" / m o d u l e s / "$ x ) ) ) ( g l o b a l' m o d u l e )

Thesesymbolsarenotprotectedandcanberedefinedbytheuser.The$ x variableisbuiltinandprotectedagainstdeletion.This$ x variableisalsousedincurryexpressions.

()

GNUFreeDocumentationLicense
Version1.2,November2002 Copyright(C)2000,2001,2002FreeSoftwareFoundation,Inc.59TemplePlace,Suite330,Boston,MA021111307USA Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,butchangingitisnotallowed.

0.PREAMBLE ThepurposeofthisLicenseistomakeamanual,textbook,orotherfunctionalandusefuldocument"free"inthesenseoffreedom: toassureeveryonetheeffectivefreedomtocopyandredistributeit,withorwithoutmodifyingit,eithercommerciallyor noncommercially.Secondarily,thisLicensepreservesfortheauthorandpublisherawaytogetcreditfortheirwork,whilenot beingconsideredresponsibleformodificationsmadebyothers. ThisLicenseisakindof"copyleft",whichmeansthatderivativeworksofthedocumentmustthemselvesbefreeinthesamesense. ItcomplementstheGNUGeneralPublicLicense,whichisacopyleftlicensedesignedforfreesoftware. WehavedesignedthisLicenseinordertouseitformanualsforfreesoftware,becausefreesoftwareneedsfreedocumentation:a freeprogramshouldcomewithmanualsprovidingthesamefreedomsthatthesoftwaredoes.ButthisLicenseisnotlimitedto softwaremanualsitcanbeusedforanytextualwork,regardlessofsubjectmatterorwhetheritispublishedasaprintedbook.We recommendthisLicenseprincipallyforworkswhosepurposeisinstructionorreference. 1.APPLICABILITYANDDEFINITIONS ThisLicenseappliestoanymanualorotherwork,inanymedium,thatcontainsanoticeplacedbythecopyrightholdersayingit canbedistributedunderthetermsofthisLicense.Suchanoticegrantsaworldwide,royaltyfreelicense,unlimitedinduration,to usethatworkundertheconditionsstatedherein.The"Document",below,referstoanysuchmanualorwork.Anymemberofthe publicisalicensee,andisaddressedas"you".Youacceptthelicenseifyoucopy,modifyordistributetheworkinawayrequiring permissionundercopyrightlaw. A"ModifiedVersion"oftheDocumentmeansanyworkcontainingtheDocumentoraportionofit,eithercopiedverbatim,orwith modificationsand/ortranslatedintoanotherlanguage. A"SecondarySection"isanamedappendixorafrontmattersectionoftheDocumentthatdealsexclusivelywiththerelationshipof thepublishersorauthorsoftheDocumenttotheDocument'soverallsubject(ortorelatedmatters)andcontainsnothingthatcould falldirectlywithinthatoverallsubject.(Thus,iftheDocumentisinpartatextbookofmathematics,aSecondarySectionmaynot explainanymathematics.)Therelationshipcouldbeamatterofhistoricalconnectionwiththesubjectorwithrelatedmatters,orof legal,commercial,philosophical,ethicalorpoliticalpositionregardingthem.

The"InvariantSections"arecertainSecondarySectionswhosetitlesaredesignated,asbeingthoseofInvariantSections,inthe noticethatsaysthattheDocumentisreleasedunderthisLicense.IfasectiondoesnotfittheabovedefinitionofSecondarythenitis notallowedtobedesignatedasInvariant.TheDocumentmaycontainzeroInvariantSections.IftheDocumentdoesnotidentify anyInvariantSectionsthentherearenone. The"CoverTexts"arecertainshortpassagesoftextthatarelisted,asFrontCoverTextsorBackCoverTexts,inthenoticethat saysthattheDocumentisreleasedunderthisLicense.AFrontCoverTextmaybeatmost5words,andaBackCoverTextmaybe atmost25words. A"Transparent"copyoftheDocumentmeansamachinereadablecopy,representedinaformatwhosespecificationisavailableto thegeneralpublic,thatissuitableforrevisingthedocumentstraightforwardlywithgenerictexteditorsor(forimagescomposedof pixels)genericpaintprogramsor(fordrawings)somewidelyavailabledrawingeditor,andthatissuitableforinputtotext formattersorforautomatictranslationtoavarietyofformatssuitableforinputtotextformatters.Acopymadeinanotherwise Transparentfileformatwhosemarkup,orabsenceofmarkup,hasbeenarrangedtothwartordiscouragesubsequentmodification byreadersisnotTransparent.AnimageformatisnotTransparentifusedforanysubstantialamountoftext.Acopythatisnot "Transparent"iscalled"Opaque". ExamplesofsuitableformatsforTransparentcopiesincludeplainASCIIwithoutmarkup,Texinfoinputformat,LaTeXinput format,SGMLorXMLusingapubliclyavailableDTD,andstandardconformingsimpleHTML,PostScriptorPDFdesignedfor humanmodification.ExamplesoftransparentimageformatsincludePNG,XCFandJPG.Opaqueformatsincludeproprietary formatsthatcanbereadandeditedonlybyproprietarywordprocessors,SGMLorXMLforwhichtheDTDand/orprocessing toolsarenotgenerallyavailable,andthemachinegeneratedHTML,PostScriptorPDFproducedbysomewordprocessorsfor outputpurposesonly. The"TitlePage"means,foraprintedbook,thetitlepageitself,plussuchfollowingpagesasareneededtohold,legibly,the materialthisLicenserequirestoappearinthetitlepage.Forworksinformatswhichdonothaveanytitlepageassuch,"TitlePage" meansthetextnearthemostprominentappearanceofthework'stitle,precedingthebeginningofthebodyofthetext. Asection"EntitledXYZ"meansanamedsubunitoftheDocumentwhosetitleeitherispreciselyXYZorcontainsXYZin parenthesesfollowingtextthattranslatesXYZinanotherlanguage.(HereXYZstandsforaspecificsectionnamementioned below,suchas"Acknowledgements","Dedications","Endorsements",or"History".)To"PreservetheTitle"ofsuchasection whenyoumodifytheDocumentmeansthatitremainsasection"EntitledXYZ"accordingtothisdefinition. TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicenseappliestotheDocument.These WarrantyDisclaimersareconsideredtobeincludedbyreferenceinthisLicense,butonlyasregardsdisclaimingwarranties:any otherimplicationthattheseWarrantyDisclaimersmayhaveisvoidandhasnoeffectonthemeaningofthisLicense. 2.VERBATIMCOPYING YoumaycopyanddistributetheDocumentinanymedium,eithercommerciallyornoncommercially,providedthatthisLicense, thecopyrightnotices,andthelicensenoticesayingthisLicenseappliestotheDocumentarereproducedinallcopies,andthatyou addnootherconditionswhatsoevertothoseofthisLicense.Youmaynotusetechnicalmeasurestoobstructorcontrolthereading orfurthercopyingofthecopiesyoumakeordistribute.However,youmayacceptcompensationinexchangeforcopies.Ifyou distributealargeenoughnumberofcopiesyoumustalsofollowtheconditionsinsection3. Youmayalsolendcopies,underthesameconditionsstatedabove,andyoumaypubliclydisplaycopies. 3.COPYINGINQUANTITY Ifyoupublishprintedcopies(orcopiesinmediathatcommonlyhaveprintedcovers)oftheDocument,numberingmorethan100, andtheDocument'slicensenoticerequiresCoverTexts,youmustenclosethecopiesincoversthatcarry,clearlyandlegibly,all theseCoverTexts:FrontCoverTextsonthefrontcover,andBackCoverTextsonthebackcover.Bothcoversmustalsoclearly andlegiblyidentifyyouasthepublisherofthesecopies.Thefrontcovermustpresentthefulltitlewithallwordsofthetitleequally prominentandvisible.Youmayaddothermaterialonthecoversinaddition.Copyingwithchangeslimitedtothecovers,aslongas theypreservethetitleoftheDocumentandsatisfytheseconditions,canbetreatedasverbatimcopyinginotherrespects. Iftherequiredtextsforeithercoveraretoovoluminoustofitlegibly,youshouldputthefirstoneslisted(asmanyasfitreasonably)

ontheactualcover,andcontinuetherestontoadjacentpages. IfyoupublishordistributeOpaquecopiesoftheDocumentnumberingmorethan100,youmusteitherincludeamachinereadable TransparentcopyalongwitheachOpaquecopy,orstateinorwitheachOpaquecopyacomputernetworklocationfromwhichthe generalnetworkusingpublichasaccesstodownloadusingpublicstandardnetworkprotocolsacompleteTransparentcopyofthe Document,freeofaddedmaterial.Ifyouusethelatteroption,youmusttakereasonablyprudentsteps,whenyoubegindistribution ofOpaquecopiesinquantity,toensurethatthisTransparentcopywillremainthusaccessibleatthestatedlocationuntilatleastone yearafterthelasttimeyoudistributeanOpaquecopy(directlyorthroughyouragentsorretailers)ofthateditiontothepublic. Itisrequested,butnotrequired,thatyoucontacttheauthorsoftheDocumentwellbeforeredistributinganylargenumberofcopies, togivethemachancetoprovideyouwithanupdatedversionoftheDocument. 4.MODIFICATIONS YoumaycopyanddistributeaModifiedVersionoftheDocumentundertheconditionsofsections2and3above,providedthat youreleasetheModifiedVersionunderpreciselythisLicense,withtheModifiedVersionfillingtheroleoftheDocument,thus licensingdistributionandmodificationoftheModifiedVersiontowhoeverpossessesacopyofit.Inaddition,youmustdothese thingsintheModifiedVersion: A.UseintheTitlePage(andonthecovers,ifany)atitledistinctfromthatoftheDocument,andfromthoseof previousversions(whichshould,iftherewereany,belistedintheHistorysectionoftheDocument).Youmayusethe sametitleasapreviousversioniftheoriginalpublisherofthatversiongivespermission. B.ListontheTitlePage,asauthors,oneormorepersonsorentitiesresponsibleforauthorshipofthemodificationsin theModifiedVersion,togetherwithatleastfiveoftheprincipalauthorsoftheDocument(allofitsprincipalauthors,if ithasfewerthanfive),unlesstheyreleaseyoufromthisrequirement. C.StateontheTitlepagethenameofthepublisheroftheModifiedVersion,asthepublisher. D.PreserveallthecopyrightnoticesoftheDocument. E.Addanappropriatecopyrightnoticeforyourmodificationsadjacenttotheothercopyrightnotices. F.Include,immediatelyafterthecopyrightnotices,alicensenoticegivingthepublicpermissiontousetheModified VersionunderthetermsofthisLicense,intheformshownintheAddendumbelow. G.PreserveinthatlicensenoticethefulllistsofInvariantSectionsandrequiredCoverTextsgivenintheDocument's licensenotice. H.IncludeanunalteredcopyofthisLicense. I.PreservethesectionEntitled"History",PreserveitsTitle,andaddtoitanitemstatingatleastthetitle,year,new authors,andpublisheroftheModifiedVersionasgivenontheTitlePage.IfthereisnosectionEntitled"History"in theDocument,createonestatingthetitle,year,authors,andpublisheroftheDocumentasgivenonitsTitlePage,then addanitemdescribingtheModifiedVersionasstatedintheprevioussentence. J.Preservethenetworklocation,ifany,givenintheDocumentforpublicaccesstoaTransparentcopyofthe Document,andlikewisethenetworklocationsgivenintheDocumentforpreviousversionsitwasbasedon.These maybeplacedinthe"History"section.Youmayomitanetworklocationforaworkthatwaspublishedatleastfour yearsbeforetheDocumentitself,oriftheoriginalpublisheroftheversionitreferstogivespermission. K.ForanysectionEntitled"Acknowledgements"or"Dedications",PreservetheTitleofthesection,andpreservein thesectionallthesubstanceandtoneofeachofthecontributoracknowledgementsand/ordedicationsgiventherein. L.PreservealltheInvariantSectionsoftheDocument,unalteredintheirtextandintheirtitles.Sectionnumbersorthe equivalentarenotconsideredpartofthesectiontitles. M.DeleteanysectionEntitled"Endorsements".SuchasectionmaynotbeincludedintheModifiedVersion.

N.DonotretitleanyexistingsectiontobeEntitled"Endorsements"ortoconflictintitlewithanyInvariantSection. O.PreserveanyWarrantyDisclaimers. IftheModifiedVersionincludesnewfrontmattersectionsorappendicesthatqualifyasSecondarySectionsandcontainnomaterial copiedfromtheDocument,youmayatyouroptiondesignatesomeorallofthesesectionsasinvariant.Todothis,addtheirtitlesto thelistofInvariantSectionsintheModifiedVersion'slicensenotice.Thesetitlesmustbedistinctfromanyothersectiontitles. YoumayaddasectionEntitled"Endorsements",provideditcontainsnothingbutendorsementsofyourModifiedVersionby variouspartiesforexample,statementsofpeerrevieworthatthetexthasbeenapprovedbyanorganizationastheauthoritative definitionofastandard. YoumayaddapassageofuptofivewordsasaFrontCoverText,andapassageofupto25wordsasaBackCoverText,tothe endofthelistofCoverTextsintheModifiedVersion.OnlyonepassageofFrontCoverTextandoneofBackCoverTextmaybe addedby(orthrougharrangementsmadeby)anyoneentity.IftheDocumentalreadyincludesacovertextforthesamecover, previouslyaddedbyyouorbyarrangementmadebythesameentityyouareactingonbehalfof,youmaynotaddanotherbutyou mayreplacetheoldone,onexplicitpermissionfromthepreviouspublisherthataddedtheoldone. Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicensegivepermissiontousetheirnamesforpublicityfororto assertorimplyendorsementofanyModifiedVersion. 5.COMBININGDOCUMENTS YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,underthetermsdefinedinsection4abovefor modifiedversions,providedthatyouincludeinthecombinationalloftheInvariantSectionsofalloftheoriginaldocuments, unmodified,andlistthemallasInvariantSectionsofyourcombinedworkinitslicensenotice,andthatyoupreservealltheir WarrantyDisclaimers. ThecombinedworkneedonlycontainonecopyofthisLicense,andmultipleidenticalInvariantSectionsmaybereplacedwitha singlecopy.IftherearemultipleInvariantSectionswiththesamenamebutdifferentcontents,makethetitleofeachsuchsection uniquebyaddingattheendofit,inparentheses,thenameoftheoriginalauthororpublisherofthatsectionifknown,orelsea uniquenumber.MakethesameadjustmenttothesectiontitlesinthelistofInvariantSectionsinthelicensenoticeofthecombined work. Inthecombination,youmustcombineanysectionsEntitled"History"inthevariousoriginaldocuments,formingonesection Entitled"History"likewisecombineanysectionsEntitled"Acknowledgements",andanysectionsEntitled"Dedications".You mustdeleteallsectionsEntitled"Endorsements." 6.COLLECTIONSOFDOCUMENTS YoumaymakeacollectionconsistingoftheDocumentandotherdocumentsreleasedunderthisLicense,andreplacetheindividual copiesofthisLicenseinthevariousdocumentswithasinglecopythatisincludedinthecollection,providedthatyoufollowthe rulesofthisLicenseforverbatimcopyingofeachofthedocumentsinallotherrespects. Youmayextractasingledocumentfromsuchacollection,anddistributeitindividuallyunderthisLicense,providedyouinserta copyofthisLicenseintotheextracteddocument,andfollowthisLicenseinallotherrespectsregardingverbatimcopyingofthat document. 7.AGGREGATIONWITHINDEPENDENTWORKS AcompilationoftheDocumentoritsderivativeswithotherseparateandindependentdocumentsorworks,inoronavolumeofa storageordistributionmedium,iscalledan"aggregate"ifthecopyrightresultingfromthecompilationisnotusedtolimitthelegal rightsofthecompilation'susersbeyondwhattheindividualworkspermit.WhentheDocumentisincludedinanaggregate,this LicensedoesnotapplytotheotherworksintheaggregatewhicharenotthemselvesderivativeworksoftheDocument. IftheCoverTextrequirementofsection3isapplicabletothesecopiesoftheDocument,theniftheDocumentislessthanonehalf oftheentireaggregate,theDocument'sCoverTextsmaybeplacedoncoversthatbrackettheDocumentwithintheaggregate,or

theelectronicequivalentofcoversiftheDocumentisinelectronicform.Otherwisetheymustappearonprintedcoversthatbracket thewholeaggregate. 8.TRANSLATION Translationisconsideredakindofmodification,soyoumaydistributetranslationsoftheDocumentunderthetermsofsection4. ReplacingInvariantSectionswithtranslationsrequiresspecialpermissionfromtheircopyrightholders,butyoumayinclude translationsofsomeorallInvariantSectionsinadditiontotheoriginalversionsoftheseInvariantSections.Youmayincludea translationofthisLicense,andallthelicensenoticesintheDocument,andanyWarrantyDisclaimers,providedthatyoualso includetheoriginalEnglishversionofthisLicenseandtheoriginalversionsofthosenoticesanddisclaimers.Incaseofa disagreementbetweenthetranslationandtheoriginalversionofthisLicenseoranoticeordisclaimer,theoriginalversionwill prevail. IfasectionintheDocumentisEntitled"Acknowledgements","Dedications",or"History",therequirement(section4)toPreserve itsTitle(section1)willtypicallyrequirechangingtheactualtitle. 9.TERMINATION Youmaynotcopy,modify,sublicense,ordistributetheDocumentexceptasexpresslyprovidedforunderthisLicense.Anyother attempttocopy,modify,sublicenseordistributetheDocumentisvoid,andwillautomaticallyterminateyourrightsunderthis License.However,partieswhohavereceivedcopies,orrights,fromyouunderthisLicensewillnothavetheirlicensesterminated solongassuchpartiesremaininfullcompliance. 10.FUTUREREVISIONSOFTHISLICENSE TheFreeSoftwareFoundationmaypublishnew,revisedversionsoftheGNUFreeDocumentationLicensefromtimetotime. Suchnewversionswillbesimilarinspirittothepresentversion,butmaydifferindetailtoaddressnewproblemsorconcerns.See http://www.gnu.org/copyleft/. EachversionoftheLicenseisgivenadistinguishingversionnumber.IftheDocumentspecifiesthataparticularnumberedversion ofthisLicense"oranylaterversion"appliestoit,youhavetheoptionoffollowingthetermsandconditionseitherofthatspecified versionorofanylaterversionthathasbeenpublished(notasadraft)bytheFreeSoftwareFoundation.IftheDocumentdoesnot specifyaversionnumberofthisLicense,youmaychooseanyversioneverpublished(notasadraft)bytheFreeSoftware Foundation.

GNUGENERALPUBLICLICENSE
Version3,29June2007 Copyright(C)2007FreeSoftwareFoundation,Inc.http://fsf.org/Everyoneispermittedtocopyanddistributeverbatimcopiesof thislicensedocument,butchangingitisnotallowed. Preamble TheGNUGeneralPublicLicenseisafree,copyleftlicenseforsoftwareandotherkindsofworks. Thelicensesformostsoftwareandotherpracticalworksaredesignedtotakeawayyourfreedomtoshareandchangetheworks. Bycontrast,theGNUGeneralPublicLicenseisintendedtoguaranteeyourfreedomtoshareandchangeallversionsofaprogram

tomakesureitremainsfreesoftwareforallitsusers.We,theFreeSoftwareFoundation,usetheGNUGeneralPublicLicensefor mostofoursoftwareitappliesalsotoanyotherworkreleasedthiswaybyitsauthors.Youcanapplyittoyourprograms,too. Whenwespeakoffreesoftware,wearereferringtofreedom,notprice.OurGeneralPublicLicensesaredesignedtomakesurethat youhavethefreedomtodistributecopiesoffreesoftware(andchargeforthemifyouwish),thatyoureceivesourcecodeorcanget itifyouwantit,thatyoucanchangethesoftwareorusepiecesofitinnewfreeprograms,andthatyouknowyoucandothese things. Toprotectyourrights,weneedtopreventothersfromdenyingyoutheserightsoraskingyoutosurrendertherights.Therefore,you havecertainresponsibilitiesifyoudistributecopiesofthesoftware,orifyoumodifyit:responsibilitiestorespectthefreedomof others. Forexample,ifyoudistributecopiesofsuchaprogram,whethergratisorforafee,youmustpassontotherecipientsthesame freedomsthatyoureceived.Youmustmakesurethatthey,too,receiveorcangetthesourcecode.Andyoumustshowthemthese termssotheyknowtheirrights. DevelopersthatusetheGNUGPLprotectyourrightswithtwosteps: (1)assertcopyrightonthesoftware,and(2)offeryouthisLicensegivingyoulegalpermissiontocopy,distributeand/ormodifyit. Forthedevelopers'andauthors'protection,theGPLclearlyexplainsthatthereisnowarrantyforthisfreesoftware.Forbothusers' andauthors'sake,theGPLrequiresthatmodifiedversionsbemarkedaschanged,sothattheirproblemswillnotbeattributed erroneouslytoauthorsofpreviousversions. Somedevicesaredesignedtodenyusersaccesstoinstallorrunmodifiedversionsofthesoftwareinsidethem,althoughthe manufacturercandoso.Thisisfundamentallyincompatiblewiththeaimofprotectingusers'freedomtochangethesoftware.The systematicpatternofsuchabuseoccursintheareaofproductsforindividualstouse,whichispreciselywhereitismost unacceptable.Therefore,wehavedesignedthisversionoftheGPLtoprohibitthepracticeforthoseproducts.Ifsuchproblemsarise substantiallyinotherdomains,westandreadytoextendthisprovisiontothosedomainsinfutureversionsoftheGPL,asneededto protectthefreedomofusers. Finally,everyprogramisthreatenedconstantlybysoftwarepatents.Statesshouldnotallowpatentstorestrictdevelopmentanduse ofsoftwareongeneralpurposecomputers,butinthosethatdo,wewishtoavoidthespecialdangerthatpatentsappliedtoafree programcouldmakeiteffectivelyproprietary.Topreventthis,theGPLassuresthatpatentscannotbeusedtorendertheprogram nonfree. Theprecisetermsandconditionsforcopying,distributionandmodificationfollow. TERMSANDCONDITIONS 0.Definitions. "ThisLicense"referstoversion3oftheGNUGeneralPublicLicense. "Copyright"alsomeanscopyrightlikelawsthatapplytootherkindsofworks,suchassemiconductormasks. "TheProgram"referstoanycopyrightableworklicensedunderthisLicense.Eachlicenseeisaddressedas"you"."Licensees"and "recipients"maybeindividualsororganizations. To"modify"aworkmeanstocopyfromoradaptallorpartoftheworkinafashionrequiringcopyrightpermission,otherthanthe makingofanexactcopy.Theresultingworkiscalleda"modifiedversion"oftheearlierworkorawork"basedon"theearlier work. A"coveredwork"meanseithertheunmodifiedProgramoraworkbasedontheProgram. To"propagate"aworkmeanstodoanythingwithitthat,withoutpermission,wouldmakeyoudirectlyorsecondarilyliablefor infringementunderapplicablecopyrightlaw,exceptexecutingitonacomputerormodifyingaprivatecopy.Propagationincludes copying,distribution(withorwithoutmodification),makingavailabletothepublic,andinsomecountriesotheractivitiesaswell.

To"convey"aworkmeansanykindofpropagationthatenablesotherpartiestomakeorreceivecopies.Mereinteractionwitha userthroughacomputernetwork,withnotransferofacopy,isnotconveying. Aninteractiveuserinterfacedisplays"AppropriateLegalNotices"totheextentthatitincludesaconvenientandprominentlyvisible featurethat(1)displaysanappropriatecopyrightnotice,and(2)tellstheuserthatthereisnowarrantyforthework(excepttothe extentthatwarrantiesareprovided),thatlicenseesmayconveytheworkunderthisLicense,andhowtoviewacopyofthis License.Iftheinterfacepresentsalistofusercommandsoroptions,suchasamenu,aprominentiteminthelistmeetsthiscriterion. 1.SourceCode. The"sourcecode"foraworkmeansthepreferredformoftheworkformakingmodificationstoit."Objectcode"meansanynon sourceformofawork. A"StandardInterface"meansaninterfacethateitherisanofficialstandarddefinedbyarecognizedstandardsbody,or,inthecase ofinterfacesspecifiedforaparticularprogramminglanguage,onethatiswidelyusedamongdevelopersworkinginthatlanguage. The"SystemLibraries"ofanexecutableworkincludeanything,otherthantheworkasawhole,that(a)isincludedinthenormal formofpackagingaMajorComponent,butwhichisnotpartofthatMajorComponent,and(b)servesonlytoenableuseofthe workwiththatMajorComponent,ortoimplementaStandardInterfaceforwhichanimplementationisavailabletothepublicin sourcecodeform.A"MajorComponent",inthiscontext,meansamajoressentialcomponent(kernel,windowsystem,andsoon) ofthespecificoperatingsystem(ifany)onwhichtheexecutableworkruns,oracompilerusedtoproducethework,oranobject codeinterpreterusedtorunit. The"CorrespondingSource"foraworkinobjectcodeformmeansallthesourcecodeneededtogenerate,install,and(foran executablework)runtheobjectcodeandtomodifythework,includingscriptstocontrolthoseactivities.However,itdoesnot includethework'sSystemLibraries,orgeneralpurposetoolsorgenerallyavailablefreeprogramswhichareusedunmodifiedin performingthoseactivitiesbutwhicharenotpartofthework.Forexample,CorrespondingSourceincludesinterfacedefinitionfiles associatedwithsourcefilesforthework,andthesourcecodeforsharedlibrariesanddynamicallylinkedsubprogramsthatthework isspecificallydesignedtorequire,suchasbyintimatedatacommunicationorcontrolflowbetweenthosesubprogramsandother partsofthework. TheCorrespondingSourceneednotincludeanythingthatuserscanregenerateautomaticallyfromotherpartsoftheCorresponding Source. TheCorrespondingSourceforaworkinsourcecodeformisthatsamework. 2.BasicPermissions. AllrightsgrantedunderthisLicensearegrantedforthetermofcopyrightontheProgram,andareirrevocableprovidedthestated conditionsaremet.ThisLicenseexplicitlyaffirmsyourunlimitedpermissiontoruntheunmodifiedProgram.Theoutputfrom runningacoveredworkiscoveredbythisLicenseonlyiftheoutput,givenitscontent,constitutesacoveredwork.ThisLicense acknowledgesyourrightsoffairuseorotherequivalent,asprovidedbycopyrightlaw. Youmaymake,runandpropagatecoveredworksthatyoudonotconvey,withoutconditionssolongasyourlicenseotherwise remainsinforce.Youmayconveycoveredworkstoothersforthesolepurposeofhavingthemmakemodificationsexclusivelyfor you,orprovideyouwithfacilitiesforrunningthoseworks,providedthatyoucomplywiththetermsofthisLicenseinconveyingall materialforwhichyoudonotcontrolcopyright.Thosethusmakingorrunningthecoveredworksforyoumustdosoexclusively onyourbehalf,underyourdirectionandcontrol,ontermsthatprohibitthemfrommakinganycopiesofyourcopyrightedmaterial outsidetheirrelationshipwithyou. Conveyingunderanyothercircumstancesispermittedsolelyundertheconditionsstatedbelow.Sublicensingisnotallowedsection 10makesitunnecessary. 3.ProtectingUsers'LegalRightsFromAntiCircumventionLaw. Nocoveredworkshallbedeemedpartofaneffectivetechnologicalmeasureunderanyapplicablelawfulfillingobligationsunder article11oftheWIPOcopyrighttreatyadoptedon20December1996,orsimilarlawsprohibitingorrestrictingcircumventionof

suchmeasures. Whenyouconveyacoveredwork,youwaiveanylegalpowertoforbidcircumventionoftechnologicalmeasurestotheextentsuch circumventioniseffectedbyexercisingrightsunderthisLicensewithrespecttothecoveredwork,andyoudisclaimanyintentionto limitoperationormodificationoftheworkasameansofenforcing,againstthework'susers,yourorthirdparties'legalrightsto forbidcircumventionoftechnologicalmeasures. 4.ConveyingVerbatimCopies. YoumayconveyverbatimcopiesoftheProgram'ssourcecodeasyoureceiveit,inanymedium,providedthatyouconspicuously andappropriatelypublishoneachcopyanappropriatecopyrightnoticekeepintactallnoticesstatingthatthisLicenseandanynon permissivetermsaddedinaccordwithsection7applytothecodekeepintactallnoticesoftheabsenceofanywarrantyandgive allrecipientsacopyofthisLicensealongwiththeProgram. Youmaychargeanypriceornopriceforeachcopythatyouconvey,andyoumayoffersupportorwarrantyprotectionforafee. 5.ConveyingModifiedSourceVersions. YoumayconveyaworkbasedontheProgram,orthemodificationstoproduceitfromtheProgram,intheformofsourcecode underthetermsofsection4,providedthatyoualsomeetalloftheseconditions: a)Theworkmustcarryprominentnoticesstatingthatyoumodifiedit,andgivingarelevantdate. b)TheworkmustcarryprominentnoticesstatingthatitisreleasedunderthisLicenseandanyconditionsaddedunder section7.Thisrequirementmodifiestherequirementinsection4to"keepintactallnotices". c)Youmustlicensetheentirework,asawhole,underthisLicensetoanyonewhocomesintopossessionofacopy. ThisLicensewillthereforeapply,alongwithanyapplicablesection7additionalterms,tothewholeofthework,and allitsparts,regardlessofhowtheyarepackaged.ThisLicensegivesnopermissiontolicensetheworkinanyother way,butitdoesnotinvalidatesuchpermissionifyouhaveseparatelyreceivedit. d)Iftheworkhasinteractiveuserinterfaces,eachmustdisplayAppropriateLegalNoticeshowever,iftheProgram hasinteractiveinterfacesthatdonotdisplayAppropriateLegalNotices,yourworkneednotmakethemdoso. Acompilationofacoveredworkwithotherseparateandindependentworks,whicharenotbytheirnatureextensionsofthe coveredwork,andwhicharenotcombinedwithitsuchastoformalargerprogram,inoronavolumeofastorageordistribution medium,iscalledan"aggregate"ifthecompilationanditsresultingcopyrightarenotusedtolimittheaccessorlegalrightsofthe compilation'susersbeyondwhattheindividualworkspermit.Inclusionofacoveredworkinanaggregatedoesnotcausethis Licensetoapplytotheotherpartsoftheaggregate. 6.ConveyingNonSourceForms. Youmayconveyacoveredworkinobjectcodeformunderthetermsofsections4and5,providedthatyoualsoconveythe machinereadableCorrespondingSourceunderthetermsofthisLicense,inoneoftheseways: a)Conveytheobjectcodein,orembodiedin,aphysicalproduct(includingaphysicaldistributionmedium), accompaniedbytheCorrespondingSourcefixedonadurablephysicalmediumcustomarilyusedforsoftware interchange. b)Conveytheobjectcodein,orembodiedin,aphysicalproduct(includingaphysicaldistributionmedium), accompaniedbyawrittenoffer,validforatleastthreeyearsandvalidforaslongasyouoffersparepartsorcustomer supportforthatproductmodel,togiveanyonewhopossessestheobjectcodeeither(1)acopyoftheCorresponding SourceforallthesoftwareintheproductthatiscoveredbythisLicense,onadurablephysicalmediumcustomarily usedforsoftwareinterchange,forapricenomorethanyourreasonablecostofphysicallyperformingthisconveyingof source,or(2)accesstocopytheCorrespondingSourcefromanetworkserveratnocharge. c)ConveyindividualcopiesoftheobjectcodewithacopyofthewrittenoffertoprovidetheCorrespondingSource.

Thisalternativeisallowedonlyoccasionallyandnoncommercially,andonlyifyoureceivedtheobjectcodewithsuch anoffer,inaccordwithsubsection6b. d)Conveytheobjectcodebyofferingaccessfromadesignatedplace(gratisorforacharge),andofferequivalent accesstotheCorrespondingSourceinthesamewaythroughthesameplaceatnofurthercharge.Youneednotrequire recipientstocopytheCorrespondingSourcealongwiththeobjectcode.Iftheplacetocopytheobjectcodeisa networkserver,theCorrespondingSourcemaybeonadifferentserver(operatedbyyouorathirdparty)thatsupports equivalentcopyingfacilities,providedyoumaintaincleardirectionsnexttotheobjectcodesayingwheretofindthe CorrespondingSource.RegardlessofwhatserverhoststheCorrespondingSource,youremainobligatedtoensurethat itisavailableforaslongasneededtosatisfytheserequirements. e)Conveytheobjectcodeusingpeertopeertransmission,providedyouinformotherpeerswheretheobjectcodeand CorrespondingSourceoftheworkarebeingofferedtothegeneralpublicatnochargeundersubsection6d. Aseparableportionoftheobjectcode,whosesourcecodeisexcludedfromtheCorrespondingSourceasaSystemLibrary,need notbeincludedinconveyingtheobjectcodework. A"UserProduct"iseither(1)a"consumerproduct",whichmeansanytangiblepersonalpropertywhichisnormallyusedfor personal,family,orhouseholdpurposes,or(2)anythingdesignedorsoldforincorporationintoadwelling.Indeterminingwhether aproductisaconsumerproduct,doubtfulcasesshallberesolvedinfavorofcoverage.Foraparticularproductreceivedbya particularuser,"normallyused"referstoatypicalorcommonuseofthatclassofproduct,regardlessofthestatusoftheparticular userorofthewayinwhichtheparticularuseractuallyuses,orexpectsorisexpectedtouse,theproduct.Aproductisaconsumer productregardlessofwhethertheproducthassubstantialcommercial,industrialornonconsumeruses,unlesssuchusesrepresent theonlysignificantmodeofuseoftheproduct. "InstallationInformation"foraUserProductmeansanymethods,procedures,authorizationkeys,orotherinformationrequiredto installandexecutemodifiedversionsofacoveredworkinthatUserProductfromamodifiedversionofitsCorrespondingSource. Theinformationmustsufficetoensurethatthecontinuedfunctioningofthemodifiedobjectcodeisinnocasepreventedor interferedwithsolelybecausemodificationhasbeenmade. Ifyouconveyanobjectcodeworkunderthissectionin,orwith,orspecificallyforusein,aUserProduct,andtheconveying occursaspartofatransactioninwhichtherightofpossessionanduseoftheUserProductistransferredtotherecipientin perpetuityorforafixedterm(regardlessofhowthetransactionischaracterized),theCorrespondingSourceconveyedunderthis sectionmustbeaccompaniedbytheInstallationInformation.Butthisrequirementdoesnotapplyifneitheryounoranythirdparty retainstheabilitytoinstallmodifiedobjectcodeontheUserProduct(forexample,theworkhasbeeninstalledinROM). TherequirementtoprovideInstallationInformationdoesnotincludearequirementtocontinuetoprovidesupportservice,warranty, orupdatesforaworkthathasbeenmodifiedorinstalledbytherecipient,orfortheUserProductinwhichithasbeenmodifiedor installed.Accesstoanetworkmaybedeniedwhenthemodificationitselfmateriallyandadverselyaffectstheoperationofthe networkorviolatestherulesandprotocolsforcommunicationacrossthenetwork. CorrespondingSourceconveyed,andInstallationInformationprovided,inaccordwiththissectionmustbeinaformatthatis publiclydocumented(andwithanimplementationavailabletothepublicinsourcecodeform),andmustrequirenospecial passwordorkeyforunpacking,readingorcopying. 7.AdditionalTerms. "Additionalpermissions"aretermsthatsupplementthetermsofthisLicensebymakingexceptionsfromoneormoreofits conditions.AdditionalpermissionsthatareapplicabletotheentireProgramshallbetreatedasthoughtheywereincludedinthis License,totheextentthattheyarevalidunderapplicablelaw.IfadditionalpermissionsapplyonlytopartoftheProgram,thatpart maybeusedseparatelyunderthosepermissions,buttheentireProgramremainsgovernedbythisLicensewithoutregardtothe additionalpermissions. Whenyouconveyacopyofacoveredwork,youmayatyouroptionremoveanyadditionalpermissionsfromthatcopy,orfrom anypartofit.(Additionalpermissionsmaybewrittentorequiretheirownremovalincertaincaseswhenyoumodifythework.) Youmayplaceadditionalpermissionsonmaterial,addedbyyoutoacoveredwork,forwhichyouhaveorcangiveappropriate copyrightpermission.

NotwithstandinganyotherprovisionofthisLicense,formaterialyouaddtoacoveredwork,youmay(ifauthorizedbythe copyrightholdersofthatmaterial)supplementthetermsofthisLicensewithterms: a)Disclaimingwarrantyorlimitingliabilitydifferentlyfromthetermsofsections15and16ofthisLicenseor b)Requiringpreservationofspecifiedreasonablelegalnoticesorauthorattributionsinthatmaterialorinthe AppropriateLegalNoticesdisplayedbyworkscontainingitor c)Prohibitingmisrepresentationoftheoriginofthatmaterial,orrequiringthatmodifiedversionsofsuchmaterialbe markedinreasonablewaysasdifferentfromtheoriginalversionor d)Limitingtheuseforpublicitypurposesofnamesoflicensorsorauthorsofthematerialor e)Decliningtograntrightsundertrademarklawforuseofsometradenames,trademarks,orservicemarksor f)Requiringindemnificationoflicensorsandauthorsofthatmaterialbyanyonewhoconveysthematerial(ormodified versionsofit)withcontractualassumptionsofliabilitytotherecipient,foranyliabilitythatthesecontractual assumptionsdirectlyimposeonthoselicensorsandauthors. Allothernonpermissiveadditionaltermsareconsidered"furtherrestrictions"withinthemeaningofsection10.IftheProgramas youreceivedit,oranypartofit,containsanoticestatingthatitisgovernedbythisLicensealongwithatermthatisafurther restriction,youmayremovethatterm.Ifalicensedocumentcontainsafurtherrestrictionbutpermitsrelicensingorconveyingunder thisLicense,youmayaddtoacoveredworkmaterialgovernedbythetermsofthatlicensedocument,providedthatthefurther restrictiondoesnotsurvivesuchrelicensingorconveying. Ifyouaddtermstoacoveredworkinaccordwiththissection,youmustplace,intherelevantsourcefiles,astatementofthe additionaltermsthatapplytothosefiles,oranoticeindicatingwheretofindtheapplicableterms. Additionalterms,permissiveornonpermissive,maybestatedintheformofaseparatelywrittenlicense,orstatedasexceptionsthe aboverequirementsapplyeitherway. 8.Termination. YoumaynotpropagateormodifyacoveredworkexceptasexpresslyprovidedunderthisLicense.Anyattemptotherwiseto propagateormodifyitisvoid,andwillautomaticallyterminateyourrightsunderthisLicense(includinganypatentlicensesgranted underthethirdparagraphofsection11). However,ifyouceaseallviolationofthisLicense,thenyourlicensefromaparticularcopyrightholderisreinstated(a) provisionally,unlessanduntilthecopyrightholderexplicitlyandfinallyterminatesyourlicense,and(b)permanently,ifthe copyrightholderfailstonotifyyouoftheviolationbysomereasonablemeanspriorto60daysafterthecessation. Moreover,yourlicensefromaparticularcopyrightholderisreinstatedpermanentlyifthecopyrightholdernotifiesyouofthe violationbysomereasonablemeans,thisisthefirsttimeyouhavereceivednoticeofviolationofthisLicense(foranywork)from thatcopyrightholder,andyoucuretheviolationpriorto30daysafteryourreceiptofthenotice. Terminationofyourrightsunderthissectiondoesnotterminatethelicensesofpartieswhohavereceivedcopiesorrightsfromyou underthisLicense.Ifyourrightshavebeenterminatedandnotpermanentlyreinstated,youdonotqualifytoreceivenewlicenses forthesamematerialundersection10. 9.AcceptanceNotRequiredforHavingCopies. YouarenotrequiredtoacceptthisLicenseinordertoreceiveorrunacopyoftheProgram.Ancillarypropagationofacovered workoccurringsolelyasaconsequenceofusingpeertopeertransmissiontoreceiveacopylikewisedoesnotrequireacceptance. However,nothingotherthanthisLicensegrantsyoupermissiontopropagateormodifyanycoveredwork.Theseactionsinfringe copyrightifyoudonotacceptthisLicense.Therefore,bymodifyingorpropagatingacoveredwork,youindicateyouracceptance ofthisLicensetodoso. 10.AutomaticLicensingofDownstreamRecipients.

Eachtimeyouconveyacoveredwork,therecipientautomaticallyreceivesalicensefromtheoriginallicensors,torun,modifyand propagatethatwork,subjecttothisLicense.YouarenotresponsibleforenforcingcompliancebythirdpartieswiththisLicense. An"entitytransaction"isatransactiontransferringcontrolofanorganization,orsubstantiallyallassetsofone,orsubdividingan organization,ormergingorganizations.Ifpropagationofacoveredworkresultsfromanentitytransaction,eachpartytothat transactionwhoreceivesacopyoftheworkalsoreceiveswhateverlicensestotheworktheparty'spredecessorininteresthador couldgiveunderthepreviousparagraph,plusarighttopossessionoftheCorrespondingSourceoftheworkfromthepredecessor ininterest,ifthepredecessorhasitorcangetitwithreasonableefforts. YoumaynotimposeanyfurtherrestrictionsontheexerciseoftherightsgrantedoraffirmedunderthisLicense.Forexample,you maynotimposealicensefee,royalty,orotherchargeforexerciseofrightsgrantedunderthisLicense,andyoumaynotinitiate litigation(includingacrossclaimorcounterclaiminalawsuit)allegingthatanypatentclaimisinfringedbymaking,using,selling, offeringforsale,orimportingtheProgramoranyportionofit. 11.Patents. A"contributor"isacopyrightholderwhoauthorizesuseunderthisLicenseoftheProgramoraworkonwhichtheProgramis based.Theworkthuslicensediscalledthecontributor's"contributorversion". Acontributor's"essentialpatentclaims"areallpatentclaimsownedorcontrolledbythecontributor,whetheralreadyacquiredor hereafteracquired,thatwouldbeinfringedbysomemanner,permittedbythisLicense,ofmaking,using,orsellingitscontributor version,butdonotincludeclaimsthatwouldbeinfringedonlyasaconsequenceoffurthermodificationofthecontributorversion. Forpurposesofthisdefinition,"control"includestherighttograntpatentsublicensesinamannerconsistentwiththerequirements ofthisLicense. Eachcontributorgrantsyouanonexclusive,worldwide,royaltyfreepatentlicenseunderthecontributor'sessentialpatentclaims,to make,use,sell,offerforsale,importandotherwiserun,modifyandpropagatethecontentsofitscontributorversion. Inthefollowingthreeparagraphs,a"patentlicense"isanyexpressagreementorcommitment,howeverdenominated,nottoenforce apatent(suchasanexpresspermissiontopracticeapatentorcovenantnottosueforpatentinfringement).To"grant"suchapatent licensetoapartymeanstomakesuchanagreementorcommitmentnottoenforceapatentagainsttheparty. Ifyouconveyacoveredwork,knowinglyrelyingonapatentlicense,andtheCorrespondingSourceoftheworkisnotavailablefor anyonetocopy,freeofchargeandunderthetermsofthisLicense,throughapubliclyavailablenetworkserverorotherreadily accessiblemeans,thenyoumusteither(1)causetheCorrespondingSourcetobesoavailable,or(2)arrangetodepriveyourselfof thebenefitofthepatentlicenseforthisparticularwork,or(3)arrange,inamannerconsistentwiththerequirementsofthisLicense, toextendthepatentlicensetodownstreamrecipients."Knowinglyrelying"meansyouhaveactualknowledgethat,butforthe patentlicense,yourconveyingthecoveredworkinacountry,oryourrecipient'suseofthecoveredworkinacountry,would infringeoneormoreidentifiablepatentsinthatcountrythatyouhavereasontobelievearevalid. If,pursuanttoorinconnectionwithasingletransactionorarrangement,youconvey,orpropagatebyprocuringconveyanceof,a coveredwork,andgrantapatentlicensetosomeofthepartiesreceivingthecoveredworkauthorizingthemtouse,propagate, modifyorconveyaspecificcopyofthecoveredwork,thenthepatentlicenseyougrantisautomaticallyextendedtoallrecipientsof thecoveredworkandworksbasedonit. Apatentlicenseis"discriminatory"ifitdoesnotincludewithinthescopeofitscoverage,prohibitstheexerciseof,orisconditioned onthenonexerciseofoneormoreoftherightsthatarespecificallygrantedunderthisLicense.Youmaynotconveyacovered workifyouareapartytoanarrangementwithathirdpartythatisinthebusinessofdistributingsoftware,underwhichyoumake paymenttothethirdpartybasedontheextentofyouractivityofconveyingthework,andunderwhichthethirdpartygrants,toany ofthepartieswhowouldreceivethecoveredworkfromyou,adiscriminatorypatentlicense(a)inconnectionwithcopiesofthe coveredworkconveyedbyyou(orcopiesmadefromthosecopies),or(b)primarilyforandinconnectionwithspecificproductsor compilationsthatcontainthecoveredwork,unlessyouenteredintothatarrangement,orthatpatentlicensewasgranted,priorto28 March2007. NothinginthisLicenseshallbeconstruedasexcludingorlimitinganyimpliedlicenseorotherdefensestoinfringementthatmay otherwisebeavailabletoyouunderapplicablepatentlaw.

12.NoSurrenderofOthers'Freedom. Ifconditionsareimposedonyou(whetherbycourtorder,agreementorotherwise)thatcontradicttheconditionsofthisLicense, theydonotexcuseyoufromtheconditionsofthisLicense.Ifyoucannotconveyacoveredworksoastosatisfysimultaneously yourobligationsunderthisLicenseandanyotherpertinentobligations,thenasaconsequenceyoumaynotconveyitatall.For example,ifyouagreetotermsthatobligateyoutocollectaroyaltyforfurtherconveyingfromthosetowhomyouconveythe Program,theonlywayyoucouldsatisfyboththosetermsandthisLicensewouldbetorefrainentirelyfromconveyingtheProgram. 13.UsewiththeGNUAfferoGeneralPublicLicense. NotwithstandinganyotherprovisionofthisLicense,youhavepermissiontolinkorcombineanycoveredworkwithawork licensedunderversion3oftheGNUAfferoGeneralPublicLicenseintoasinglecombinedwork,andtoconveytheresultingwork. ThetermsofthisLicensewillcontinuetoapplytothepartwhichisthecoveredwork,butthespecialrequirementsoftheGNU AfferoGeneralPublicLicense,section13,concerninginteractionthroughanetworkwillapplytothecombinationassuch. 14.RevisedVersionsofthisLicense. TheFreeSoftwareFoundationmaypublishrevisedand/ornewversionsoftheGNUGeneralPublicLicensefromtimetotime. Suchnewversionswillbesimilarinspirittothepresentversion,butmaydifferindetailtoaddressnewproblemsorconcerns. Eachversionisgivenadistinguishingversionnumber.IftheProgramspecifiesthatacertainnumberedversionoftheGNUGeneral PublicLicense"oranylaterversion"appliestoit,youhavetheoptionoffollowingthetermsandconditionseitherofthatnumbered versionorofanylaterversionpublishedbytheFreeSoftwareFoundation.IftheProgramdoesnotspecifyaversionnumberofthe GNUGeneralPublicLicense,youmaychooseanyversioneverpublishedbytheFreeSoftwareFoundation. IftheProgramspecifiesthataproxycandecidewhichfutureversionsoftheGNUGeneralPublicLicensecanbeused,thatproxy's publicstatementofacceptanceofaversionpermanentlyauthorizesyoutochoosethatversionfortheProgram. Laterlicenseversionsmaygiveyouadditionalordifferentpermissions.However,noadditionalobligationsareimposedonany authororcopyrightholderasaresultofyourchoosingtofollowalaterversion. 15.DisclaimerofWarranty. THEREISNOWARRANTYFORTHEPROGRAM,TOTHEEXTENTPERMITTEDBYAPPLICABLELAW.EXCEPT WHENOTHERWISESTATEDINWRITINGTHECOPYRIGHTHOLDERSAND/OROTHERPARTIESPROVIDETHE PROGRAM"ASIS"WITHOUTWARRANTYOFANYKIND,EITHEREXPRESSEDORIMPLIED,INCLUDING,BUT NOTLIMITEDTO,THEIMPLIEDWARRANTIESOFMERCHANTABILITYANDFITNESSFORAPARTICULAR PURPOSE.THEENTIRERISKASTOTHEQUALITYANDPERFORMANCEOFTHEPROGRAMISWITHYOU. SHOULDTHEPROGRAMPROVEDEFECTIVE,YOUASSUMETHECOSTOFALLNECESSARYSERVICING, REPAIRORCORRECTION. 16.LimitationofLiability. INNOEVENTUNLESSREQUIREDBYAPPLICABLELAWORAGREEDTOINWRITINGWILLANYCOPYRIGHT HOLDER,ORANYOTHERPARTYWHOMODIFIESAND/ORCONVEYSTHEPROGRAMASPERMITTED ABOVE,BELIABLETOYOUFORDAMAGES,INCLUDINGANYGENERAL,SPECIAL,INCIDENTALOR CONSEQUENTIALDAMAGESARISINGOUTOFTHEUSEORINABILITYTOUSETHEPROGRAM(INCLUDING BUTNOTLIMITEDTOLOSSOFDATAORDATABEINGRENDEREDINACCURATEORLOSSESSUSTAINEDBY YOUORTHIRDPARTIESORAFAILUREOFTHEPROGRAMTOOPERATEWITHANYOTHERPROGRAMS), EVENIFSUCHHOLDEROROTHERPARTYHASBEENADVISEDOFTHEPOSSIBILITYOFSUCHDAMAGES. 17.InterpretationofSections15and16. Ifthedisclaimerofwarrantyandlimitationofliabilityprovidedabovecannotbegivenlocallegaleffectaccordingtotheirterms, reviewingcourtsshallapplylocallawthatmostcloselyapproximatesanabsolutewaiverofallcivilliabilityinconnectionwiththe Program,unlessawarrantyorassumptionofliabilityaccompaniesacopyofthePrograminreturnforafee.

ENDOFTERMSANDCONDITIONS

()

You might also like