srfi-modules.texi 288 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000-2004, 2006, 2007-2014, 2017, 2018, 2019, 2020
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node SRFI Support
  7. @section SRFI Support Modules
  8. @cindex SRFI
  9. SRFI is an acronym for Scheme Request For Implementation. The SRFI
  10. documents define a lot of syntactic and procedure extensions to standard
  11. Scheme as defined in R5RS.
  12. Guile has support for a number of SRFIs. This chapter gives an overview
  13. over the available SRFIs and some usage hints. For complete
  14. documentation, design rationales and further examples, we advise you to
  15. get the relevant SRFI documents from the SRFI home page
  16. @url{http://srfi.schemers.org/}.
  17. @menu
  18. * About SRFI Usage:: What to know about Guile's SRFI support.
  19. * SRFI-0:: cond-expand
  20. * SRFI-1:: List library.
  21. * SRFI-2:: and-let*.
  22. * SRFI-4:: Homogeneous numeric vector datatypes.
  23. * SRFI-6:: Basic String Ports.
  24. * SRFI-8:: receive.
  25. * SRFI-9:: define-record-type.
  26. * SRFI-10:: Hash-Comma Reader Extension.
  27. * SRFI-11:: let-values and let*-values.
  28. * SRFI-13:: String library.
  29. * SRFI-14:: Character-set library.
  30. * SRFI-16:: case-lambda
  31. * SRFI-17:: Generalized set!
  32. * SRFI-18:: Multithreading support
  33. * SRFI-19:: Time/Date library.
  34. * SRFI-23:: Error reporting
  35. * SRFI-26:: Specializing parameters
  36. * SRFI-27:: Sources of Random Bits
  37. * SRFI-28:: Basic format strings.
  38. * SRFI-30:: Nested multi-line block comments
  39. * SRFI-31:: A special form `rec' for recursive evaluation
  40. * SRFI-34:: Exception handling.
  41. * SRFI-35:: Conditions.
  42. * SRFI-37:: args-fold program argument processor
  43. * SRFI-38:: External Representation for Data With Shared Structure
  44. * SRFI-39:: Parameter objects
  45. * SRFI-41:: Streams.
  46. * SRFI-42:: Eager comprehensions
  47. * SRFI-43:: Vector Library.
  48. * SRFI-45:: Primitives for expressing iterative lazy algorithms
  49. * SRFI-46:: Basic syntax-rules Extensions.
  50. * SRFI-55:: Requiring Features.
  51. * SRFI-60:: Integers as bits.
  52. * SRFI-61:: A more general `cond' clause
  53. * SRFI-62:: S-expression comments.
  54. * SRFI-64:: A Scheme API for test suites.
  55. * SRFI-67:: Compare procedures
  56. * SRFI-69:: Basic hash tables.
  57. * SRFI-71:: Extended let-syntax for multiple values.
  58. * SRFI-87:: => in case clauses.
  59. * SRFI-88:: Keyword objects.
  60. * SRFI-98:: Accessing environment variables.
  61. * SRFI-105:: Curly-infix expressions.
  62. * SRFI-111:: Boxes.
  63. * SRFI-126:: R6RS-based hash tables.
  64. * SRFI-128:: Comparators.
  65. * SRFI-171:: Transducers.
  66. @end menu
  67. @node About SRFI Usage
  68. @subsection About SRFI Usage
  69. @c FIXME::martin: Review me!
  70. SRFI support in Guile is currently implemented partly in the core
  71. library, and partly as add-on modules. That means that some SRFIs are
  72. automatically available when the interpreter is started, whereas the
  73. other SRFIs require you to use the appropriate support module
  74. explicitly.
  75. There are several reasons for this inconsistency. First, the feature
  76. checking syntactic form @code{cond-expand} (@pxref{SRFI-0}) must be
  77. available immediately, because it must be there when the user wants to
  78. check for the Scheme implementation, that is, before she can know that
  79. it is safe to use @code{use-modules} to load SRFI support modules. The
  80. second reason is that some features defined in SRFIs had been
  81. implemented in Guile before the developers started to add SRFI
  82. implementations as modules (for example SRFI-13 (@pxref{SRFI-13})). In
  83. the future, it is possible that SRFIs in the core library might be
  84. factored out into separate modules, requiring explicit module loading
  85. when they are needed. So you should be prepared to have to use
  86. @code{use-modules} someday in the future to access SRFI-13 bindings. If
  87. you want, you can do that already. We have included the module
  88. @code{(srfi srfi-13)} in the distribution, which currently does nothing,
  89. but ensures that you can write future-safe code.
  90. Generally, support for a specific SRFI is made available by using
  91. modules named @code{(srfi srfi-@var{number})}, where @var{number} is the
  92. number of the SRFI needed. Another possibility is to use the command
  93. line option @code{--use-srfi}, which will load the necessary modules
  94. automatically (@pxref{Invoking Guile}).
  95. @node SRFI-0
  96. @subsection SRFI-0 - cond-expand
  97. @cindex SRFI-0
  98. This SRFI lets a portable Scheme program test for the presence of
  99. certain features, and adapt itself by using different blocks of code,
  100. or fail if the necessary features are not available. There's no
  101. module to load, this is in the Guile core.
  102. A program designed only for Guile will generally not need this
  103. mechanism, such a program can of course directly use the various
  104. documented parts of Guile.
  105. @deffn syntax cond-expand (feature body@dots{}) @dots{}
  106. Expand to the @var{body} of the first clause whose @var{feature}
  107. specification is satisfied. It is an error if no @var{feature} is
  108. satisfied.
  109. Features are symbols such as @code{srfi-1}, and a feature
  110. specification can use @code{and}, @code{or} and @code{not} forms to
  111. test combinations. The last clause can be an @code{else}, to be used
  112. if no other passes.
  113. For example, define a private version of @code{alist-cons} if SRFI-1
  114. is not available.
  115. @example
  116. (cond-expand (srfi-1
  117. )
  118. (else
  119. (define (alist-cons key val alist)
  120. (cons (cons key val) alist))))
  121. @end example
  122. Or demand a certain set of SRFIs (list operations, string ports,
  123. @code{receive} and string operations), failing if they're not
  124. available.
  125. @example
  126. (cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
  127. ))
  128. @end example
  129. @end deffn
  130. @noindent
  131. The Guile core has the following features,
  132. @example
  133. guile
  134. guile-2 ;; starting from Guile 2.x
  135. guile-2.2 ;; starting from Guile 2.2
  136. guile-3 ;; starting from Guile 3.x
  137. guile-3.0 ;; starting from Guile 3.0
  138. r5rs
  139. r6rs
  140. r7rs
  141. exact-closed ieee-float full-unicode ratios ;; R7RS features
  142. srfi-0
  143. srfi-4
  144. srfi-6
  145. srfi-13
  146. srfi-14
  147. srfi-16
  148. srfi-23
  149. srfi-30
  150. srfi-39
  151. srfi-46
  152. srfi-55
  153. srfi-61
  154. srfi-62
  155. srfi-87
  156. srfi-105
  157. @end example
  158. Other SRFI feature symbols are defined once their code has been loaded
  159. with @code{use-modules}, since only then are their bindings available.
  160. The @samp{--use-srfi} command line option (@pxref{Invoking Guile}) is
  161. a good way to load SRFIs to satisfy @code{cond-expand} when running a
  162. portable program.
  163. Testing the @code{guile} feature allows a program to adapt itself to
  164. the Guile module system, but still run on other Scheme systems. For
  165. example the following demands SRFI-8 (@code{receive}), but also knows
  166. how to load it with the Guile mechanism.
  167. @example
  168. (cond-expand (srfi-8
  169. )
  170. (guile
  171. (use-modules (srfi srfi-8))))
  172. @end example
  173. @cindex @code{guile-2} SRFI-0 feature
  174. @cindex portability between 2.0 and older versions
  175. Likewise, testing the @code{guile-2} feature allows code to be portable
  176. between Guile 2.@var{x} and previous versions of Guile. For instance, it
  177. makes it possible to write code that accounts for Guile 2.@var{x}'s compiler,
  178. yet be correctly interpreted on 1.8 and earlier versions:
  179. @example
  180. (cond-expand (guile-2 (eval-when (compile)
  181. ;; This must be evaluated at compile time.
  182. (fluid-set! current-reader my-reader)))
  183. (guile
  184. ;; Earlier versions of Guile do not have a
  185. ;; separate compilation phase.
  186. (fluid-set! current-reader my-reader)))
  187. @end example
  188. It should be noted that @code{cond-expand} is separate from the
  189. @code{*features*} mechanism (@pxref{Feature Tracking}), feature
  190. symbols in one are unrelated to those in the other.
  191. @node SRFI-1
  192. @subsection SRFI-1 - List library
  193. @cindex SRFI-1
  194. @cindex list
  195. @c FIXME::martin: Review me!
  196. The list library defined in SRFI-1 contains a lot of useful list
  197. processing procedures for construction, examining, destructuring and
  198. manipulating lists and pairs.
  199. Since SRFI-1 also defines some procedures which are already contained
  200. in R5RS and thus are supported by the Guile core library, some list
  201. and pair procedures which appear in the SRFI-1 document may not appear
  202. in this section. So when looking for a particular list/pair
  203. processing procedure, you should also have a look at the sections
  204. @ref{Lists} and @ref{Pairs}.
  205. @menu
  206. * SRFI-1 Constructors:: Constructing new lists.
  207. * SRFI-1 Predicates:: Testing list for specific properties.
  208. * SRFI-1 Selectors:: Selecting elements from lists.
  209. * SRFI-1 Length Append etc:: Length calculation and list appending.
  210. * SRFI-1 Fold and Map:: Higher-order list processing.
  211. * SRFI-1 Filtering and Partitioning:: Filter lists based on predicates.
  212. * SRFI-1 Searching:: Search for elements.
  213. * SRFI-1 Deleting:: Delete elements from lists.
  214. * SRFI-1 Association Lists:: Handle association lists.
  215. * SRFI-1 Set Operations:: Use lists for representing sets.
  216. @end menu
  217. @node SRFI-1 Constructors
  218. @subsubsection Constructors
  219. @cindex list constructor
  220. @c FIXME::martin: Review me!
  221. New lists can be constructed by calling one of the following
  222. procedures.
  223. @deffn {Scheme Procedure} xcons d a
  224. Like @code{cons}, but with interchanged arguments. Useful mostly when
  225. passed to higher-order procedures.
  226. @end deffn
  227. @deffn {Scheme Procedure} list-tabulate n init-proc
  228. Return an @var{n}-element list, where each list element is produced by
  229. applying the procedure @var{init-proc} to the corresponding list
  230. index. The order in which @var{init-proc} is applied to the indices
  231. is not specified.
  232. @end deffn
  233. @deffn {Scheme Procedure} list-copy lst
  234. Return a new list containing the elements of the list @var{lst}.
  235. This function differs from the core @code{list-copy} (@pxref{List
  236. Constructors}) in accepting improper lists too. And if @var{lst} is
  237. not a pair at all then it's treated as the final tail of an improper
  238. list and simply returned.
  239. @end deffn
  240. @deffn {Scheme Procedure} circular-list elt1 elt2 @dots{}
  241. Return a circular list containing the given arguments @var{elt1}
  242. @var{elt2} @dots{}.
  243. @end deffn
  244. @deffn {Scheme Procedure} iota count [start step]
  245. Return a list containing @var{count} numbers, starting from
  246. @var{start} and adding @var{step} each time. The default @var{start}
  247. is 0, the default @var{step} is 1. For example,
  248. @example
  249. (iota 6) @result{} (0 1 2 3 4 5)
  250. (iota 4 2.5 -2) @result{} (2.5 0.5 -1.5 -3.5)
  251. @end example
  252. This function takes its name from the corresponding primitive in the
  253. APL language.
  254. @end deffn
  255. @node SRFI-1 Predicates
  256. @subsubsection Predicates
  257. @cindex list predicate
  258. @c FIXME::martin: Review me!
  259. The procedures in this section test specific properties of lists.
  260. @deffn {Scheme Procedure} proper-list? obj
  261. Return @code{#t} if @var{obj} is a proper list, or @code{#f}
  262. otherwise. This is the same as the core @code{list?} (@pxref{List
  263. Predicates}).
  264. A proper list is a list which ends with the empty list @code{()} in
  265. the usual way. The empty list @code{()} itself is a proper list too.
  266. @example
  267. (proper-list? '(1 2 3)) @result{} #t
  268. (proper-list? '()) @result{} #t
  269. @end example
  270. @end deffn
  271. @deffn {Scheme Procedure} circular-list? obj
  272. Return @code{#t} if @var{obj} is a circular list, or @code{#f}
  273. otherwise.
  274. A circular list is a list where at some point the @code{cdr} refers
  275. back to a previous pair in the list (either the start or some later
  276. point), so that following the @code{cdr}s takes you around in a
  277. circle, with no end.
  278. @example
  279. (define x (list 1 2 3 4))
  280. (set-cdr! (last-pair x) (cddr x))
  281. x @result{} (1 2 3 4 3 4 3 4 ...)
  282. (circular-list? x) @result{} #t
  283. @end example
  284. @end deffn
  285. @deffn {Scheme Procedure} dotted-list? obj
  286. Return @code{#t} if @var{obj} is a dotted list, or @code{#f}
  287. otherwise.
  288. A dotted list is a list where the @code{cdr} of the last pair is not
  289. the empty list @code{()}. Any non-pair @var{obj} is also considered a
  290. dotted list, with length zero.
  291. @example
  292. (dotted-list? '(1 2 . 3)) @result{} #t
  293. (dotted-list? 99) @result{} #t
  294. @end example
  295. @end deffn
  296. It will be noted that any Scheme object passes exactly one of the
  297. above three tests @code{proper-list?}, @code{circular-list?} and
  298. @code{dotted-list?}. Non-lists are @code{dotted-list?}, finite lists
  299. are either @code{proper-list?} or @code{dotted-list?}, and infinite
  300. lists are @code{circular-list?}.
  301. @sp 1
  302. @deffn {Scheme Procedure} null-list? lst
  303. Return @code{#t} if @var{lst} is the empty list @code{()}, @code{#f}
  304. otherwise. If something else than a proper or circular list is passed
  305. as @var{lst}, an error is signaled. This procedure is recommended
  306. for checking for the end of a list in contexts where dotted lists are
  307. not allowed.
  308. @end deffn
  309. @deffn {Scheme Procedure} not-pair? obj
  310. Return @code{#t} is @var{obj} is not a pair, @code{#f} otherwise.
  311. This is shorthand notation @code{(not (pair? @var{obj}))} and is
  312. supposed to be used for end-of-list checking in contexts where dotted
  313. lists are allowed.
  314. @end deffn
  315. @deffn {Scheme Procedure} list= elt= list1 @dots{}
  316. Return @code{#t} if all argument lists are equal, @code{#f} otherwise.
  317. List equality is determined by testing whether all lists have the same
  318. length and the corresponding elements are equal in the sense of the
  319. equality predicate @var{elt=}. If no or only one list is given,
  320. @code{#t} is returned.
  321. @end deffn
  322. @node SRFI-1 Selectors
  323. @subsubsection Selectors
  324. @cindex list selector
  325. @c FIXME::martin: Review me!
  326. @deffn {Scheme Procedure} first pair
  327. @deffnx {Scheme Procedure} second pair
  328. @deffnx {Scheme Procedure} third pair
  329. @deffnx {Scheme Procedure} fourth pair
  330. @deffnx {Scheme Procedure} fifth pair
  331. @deffnx {Scheme Procedure} sixth pair
  332. @deffnx {Scheme Procedure} seventh pair
  333. @deffnx {Scheme Procedure} eighth pair
  334. @deffnx {Scheme Procedure} ninth pair
  335. @deffnx {Scheme Procedure} tenth pair
  336. These are synonyms for @code{car}, @code{cadr}, @code{caddr}, @dots{}.
  337. @end deffn
  338. @deffn {Scheme Procedure} car+cdr pair
  339. Return two values, the @sc{car} and the @sc{cdr} of @var{pair}.
  340. @end deffn
  341. @lisp
  342. (car+cdr '(0 1 2 3))
  343. @result{}
  344. 0
  345. (1 2 3)
  346. @end lisp
  347. @deffn {Scheme Procedure} take lst i
  348. @deffnx {Scheme Procedure} take! lst i
  349. Return a list containing the first @var{i} elements of @var{lst}.
  350. @code{take!} may modify the structure of the argument list @var{lst}
  351. in order to produce the result.
  352. @end deffn
  353. @deffn {Scheme Procedure} drop lst i
  354. Return a list containing all but the first @var{i} elements of
  355. @var{lst}.
  356. @end deffn
  357. @deffn {Scheme Procedure} take-right lst i
  358. Return a list containing the @var{i} last elements of @var{lst}.
  359. The return shares a common tail with @var{lst}.
  360. @end deffn
  361. @deffn {Scheme Procedure} drop-right lst i
  362. @deffnx {Scheme Procedure} drop-right! lst i
  363. Return a list containing all but the @var{i} last elements of
  364. @var{lst}.
  365. @code{drop-right} always returns a new list, even when @var{i} is
  366. zero. @code{drop-right!} may modify the structure of the argument
  367. list @var{lst} in order to produce the result.
  368. @end deffn
  369. @deffn {Scheme Procedure} split-at lst i
  370. @deffnx {Scheme Procedure} split-at! lst i
  371. Return two values, a list containing the first @var{i} elements of the
  372. list @var{lst} and a list containing the remaining elements.
  373. @code{split-at!} may modify the structure of the argument list
  374. @var{lst} in order to produce the result.
  375. @end deffn
  376. @deffn {Scheme Procedure} last lst
  377. Return the last element of the non-empty, finite list @var{lst}.
  378. @end deffn
  379. @node SRFI-1 Length Append etc
  380. @subsubsection Length, Append, Concatenate, etc.
  381. @c FIXME::martin: Review me!
  382. @deffn {Scheme Procedure} length+ lst
  383. Return the length of the argument list @var{lst}. When @var{lst} is a
  384. circular list, @code{#f} is returned.
  385. @end deffn
  386. @deffn {Scheme Procedure} concatenate list-of-lists
  387. @deffnx {Scheme Procedure} concatenate! list-of-lists
  388. Construct a list by appending all lists in @var{list-of-lists}.
  389. @code{concatenate!} may modify the structure of the given lists in
  390. order to produce the result.
  391. @code{concatenate} is the same as @code{(apply append
  392. @var{list-of-lists})}. It exists because some Scheme implementations
  393. have a limit on the number of arguments a function takes, which the
  394. @code{apply} might exceed. In Guile there is no such limit.
  395. @end deffn
  396. @deffn {Scheme Procedure} append-reverse rev-head tail
  397. @deffnx {Scheme Procedure} append-reverse! rev-head tail
  398. Reverse @var{rev-head}, append @var{tail} to it, and return the
  399. result. This is equivalent to @code{(append (reverse @var{rev-head})
  400. @var{tail})}, but its implementation is more efficient.
  401. @example
  402. (append-reverse '(1 2 3) '(4 5 6)) @result{} (3 2 1 4 5 6)
  403. @end example
  404. @code{append-reverse!} may modify @var{rev-head} in order to produce
  405. the result.
  406. @end deffn
  407. @deffn {Scheme Procedure} zip lst1 lst2 @dots{}
  408. Return a list as long as the shortest of the argument lists, where
  409. each element is a list. The first list contains the first elements of
  410. the argument lists, the second list contains the second elements, and
  411. so on.
  412. @end deffn
  413. @deffn {Scheme Procedure} unzip1 lst
  414. @deffnx {Scheme Procedure} unzip2 lst
  415. @deffnx {Scheme Procedure} unzip3 lst
  416. @deffnx {Scheme Procedure} unzip4 lst
  417. @deffnx {Scheme Procedure} unzip5 lst
  418. @code{unzip1} takes a list of lists, and returns a list containing the
  419. first elements of each list, @code{unzip2} returns two lists, the
  420. first containing the first elements of each lists and the second
  421. containing the second elements of each lists, and so on.
  422. @end deffn
  423. @deffn {Scheme Procedure} count pred lst1 lst2 @dots{}
  424. Return a count of the number of times @var{pred} returns true when
  425. called on elements from the given lists.
  426. @var{pred} is called with @var{N} parameters @code{(@var{pred}
  427. @var{elem1} @dots{} @var{elemN} )}, each element being from the
  428. corresponding list. The first call is with the first element of each
  429. list, the second with the second element from each, and so on.
  430. Counting stops when the end of the shortest list is reached. At least
  431. one list must be non-circular.
  432. @end deffn
  433. @node SRFI-1 Fold and Map
  434. @subsubsection Fold, Unfold & Map
  435. @cindex list fold
  436. @cindex list map
  437. @c FIXME::martin: Review me!
  438. @deffn {Scheme Procedure} fold proc init lst1 lst2 @dots{}
  439. @deffnx {Scheme Procedure} fold-right proc init lst1 lst2 @dots{}
  440. Apply @var{proc} to the elements of @var{lst1} @var{lst2} @dots{} to
  441. build a result, and return that result.
  442. Each @var{proc} call is @code{(@var{proc} @var{elem1} @var{elem2}
  443. @dots{} @var{previous})}, where @var{elem1} is from @var{lst1},
  444. @var{elem2} is from @var{lst2}, and so on. @var{previous} is the return
  445. from the previous call to @var{proc}, or the given @var{init} for the
  446. first call. If any list is empty, just @var{init} is returned.
  447. @code{fold} works through the list elements from first to last. The
  448. following shows a list reversal and the calls it makes,
  449. @example
  450. (fold cons '() '(1 2 3))
  451. (cons 1 '())
  452. (cons 2 '(1))
  453. (cons 3 '(2 1)
  454. @result{} (3 2 1)
  455. @end example
  456. @code{fold-right} works through the list elements from last to first,
  457. ie.@: from the right. So for example the following finds the longest
  458. string, and the last among equal longest,
  459. @example
  460. (fold-right (lambda (str prev)
  461. (if (> (string-length str) (string-length prev))
  462. str
  463. prev))
  464. ""
  465. '("x" "abc" "xyz" "jk"))
  466. @result{} "xyz"
  467. @end example
  468. If @var{lst1} @var{lst2} @dots{} have different lengths, @code{fold}
  469. stops when the end of the shortest is reached; @code{fold-right}
  470. commences at the last element of the shortest. Ie.@: elements past the
  471. length of the shortest are ignored in the other @var{lst}s. At least
  472. one @var{lst} must be non-circular.
  473. @code{fold} should be preferred over @code{fold-right} if the order of
  474. processing doesn't matter, or can be arranged either way, since
  475. @code{fold} is a little more efficient.
  476. The way @code{fold} builds a result from iterating is quite general,
  477. it can do more than other iterations like say @code{map} or
  478. @code{filter}. The following for example removes adjacent duplicate
  479. elements from a list,
  480. @example
  481. (define (delete-adjacent-duplicates lst)
  482. (fold-right (lambda (elem ret)
  483. (if (equal? elem (first ret))
  484. ret
  485. (cons elem ret)))
  486. (list (last lst))
  487. lst))
  488. (delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
  489. @result{} (1 2 3 4 5)
  490. @end example
  491. Clearly the same sort of thing can be done with a @code{for-each} and
  492. a variable in which to build the result, but a self-contained
  493. @var{proc} can be re-used in multiple contexts, where a
  494. @code{for-each} would have to be written out each time.
  495. @end deffn
  496. @deffn {Scheme Procedure} pair-fold proc init lst1 lst2 @dots{}
  497. @deffnx {Scheme Procedure} pair-fold-right proc init lst1 lst2 @dots{}
  498. The same as @code{fold} and @code{fold-right}, but apply @var{proc} to
  499. the pairs of the lists instead of the list elements.
  500. @end deffn
  501. @deffn {Scheme Procedure} reduce proc default lst
  502. @deffnx {Scheme Procedure} reduce-right proc default lst
  503. @code{reduce} is a variant of @code{fold}, where the first call to
  504. @var{proc} is on two elements from @var{lst}, rather than one element
  505. and a given initial value.
  506. If @var{lst} is empty, @code{reduce} returns @var{default} (this is
  507. the only use for @var{default}). If @var{lst} has just one element
  508. then that's the return value. Otherwise @var{proc} is called on the
  509. elements of @var{lst}.
  510. Each @var{proc} call is @code{(@var{proc} @var{elem} @var{previous})},
  511. where @var{elem} is from @var{lst} (the second and subsequent elements
  512. of @var{lst}), and @var{previous} is the return from the previous call
  513. to @var{proc}. The first element of @var{lst} is the @var{previous}
  514. for the first call to @var{proc}.
  515. For example, the following adds a list of numbers, the calls made to
  516. @code{+} are shown. (Of course @code{+} accepts multiple arguments
  517. and can add a list directly, with @code{apply}.)
  518. @example
  519. (reduce + 0 '(5 6 7)) @result{} 18
  520. (+ 6 5) @result{} 11
  521. (+ 7 11) @result{} 18
  522. @end example
  523. @code{reduce} can be used instead of @code{fold} where the @var{init}
  524. value is an ``identity'', meaning a value which under @var{proc}
  525. doesn't change the result, in this case 0 is an identity since
  526. @code{(+ 5 0)} is just 5. @code{reduce} avoids that unnecessary call.
  527. @code{reduce-right} is a similar variation on @code{fold-right},
  528. working from the end (ie.@: the right) of @var{lst}. The last element
  529. of @var{lst} is the @var{previous} for the first call to @var{proc},
  530. and the @var{elem} values go from the second last.
  531. @code{reduce} should be preferred over @code{reduce-right} if the
  532. order of processing doesn't matter, or can be arranged either way,
  533. since @code{reduce} is a little more efficient.
  534. @end deffn
  535. @deffn {Scheme Procedure} unfold p f g seed [tail-gen]
  536. @code{unfold} is defined as follows:
  537. @lisp
  538. (unfold p f g seed) =
  539. (if (p seed) (tail-gen seed)
  540. (cons (f seed)
  541. (unfold p f g (g seed))))
  542. @end lisp
  543. @table @var
  544. @item p
  545. Determines when to stop unfolding.
  546. @item f
  547. Maps each seed value to the corresponding list element.
  548. @item g
  549. Maps each seed value to next seed value.
  550. @item seed
  551. The state value for the unfold.
  552. @item tail-gen
  553. Creates the tail of the list; defaults to @code{(lambda (x) '())}.
  554. @end table
  555. @var{g} produces a series of seed values, which are mapped to list
  556. elements by @var{f}. These elements are put into a list in
  557. left-to-right order, and @var{p} tells when to stop unfolding.
  558. @end deffn
  559. @deffn {Scheme Procedure} unfold-right p f g seed [tail]
  560. Construct a list with the following loop.
  561. @lisp
  562. (let lp ((seed seed) (lis tail))
  563. (if (p seed) lis
  564. (lp (g seed)
  565. (cons (f seed) lis))))
  566. @end lisp
  567. @table @var
  568. @item p
  569. Determines when to stop unfolding.
  570. @item f
  571. Maps each seed value to the corresponding list element.
  572. @item g
  573. Maps each seed value to next seed value.
  574. @item seed
  575. The state value for the unfold.
  576. @item tail
  577. The tail of the list; defaults to @code{'()}.
  578. @end table
  579. @end deffn
  580. @deffn {Scheme Procedure} map f lst1 lst2 @dots{}
  581. Map the procedure over the list(s) @var{lst1}, @var{lst2}, @dots{} and
  582. return a list containing the results of the procedure applications.
  583. This procedure is extended with respect to R5RS, because the argument
  584. lists may have different lengths. The result list will have the same
  585. length as the shortest argument lists. The order in which @var{f}
  586. will be applied to the list element(s) is not specified.
  587. @end deffn
  588. @deffn {Scheme Procedure} for-each f lst1 lst2 @dots{}
  589. Apply the procedure @var{f} to each pair of corresponding elements of
  590. the list(s) @var{lst1}, @var{lst2}, @dots{}. The return value is not
  591. specified. This procedure is extended with respect to R5RS, because
  592. the argument lists may have different lengths. The shortest argument
  593. list determines the number of times @var{f} is called. @var{f} will
  594. be applied to the list elements in left-to-right order.
  595. @end deffn
  596. @deffn {Scheme Procedure} append-map f lst1 lst2 @dots{}
  597. @deffnx {Scheme Procedure} append-map! f lst1 lst2 @dots{}
  598. Equivalent to
  599. @lisp
  600. (apply append (map f clist1 clist2 ...))
  601. @end lisp
  602. and
  603. @lisp
  604. (apply append! (map f clist1 clist2 ...))
  605. @end lisp
  606. Map @var{f} over the elements of the lists, just as in the @code{map}
  607. function. However, the results of the applications are appended
  608. together to make the final result. @code{append-map} uses
  609. @code{append} to append the results together; @code{append-map!} uses
  610. @code{append!}.
  611. The dynamic order in which the various applications of @var{f} are
  612. made is not specified.
  613. @end deffn
  614. @deffn {Scheme Procedure} map! f lst1 lst2 @dots{}
  615. Linear-update variant of @code{map} -- @code{map!} is allowed, but not
  616. required, to alter the cons cells of @var{lst1} to construct the
  617. result list.
  618. The dynamic order in which the various applications of @var{f} are
  619. made is not specified. In the n-ary case, @var{lst2}, @var{lst3},
  620. @dots{} must have at least as many elements as @var{lst1}.
  621. @end deffn
  622. @deffn {Scheme Procedure} pair-for-each f lst1 lst2 @dots{}
  623. Like @code{for-each}, but applies the procedure @var{f} to the pairs
  624. from which the argument lists are constructed, instead of the list
  625. elements. The return value is not specified.
  626. @end deffn
  627. @deffn {Scheme Procedure} filter-map f lst1 lst2 @dots{}
  628. Like @code{map}, but only results from the applications of @var{f}
  629. which are true are saved in the result list.
  630. @end deffn
  631. @node SRFI-1 Filtering and Partitioning
  632. @subsubsection Filtering and Partitioning
  633. @cindex list filter
  634. @cindex list partition
  635. @c FIXME::martin: Review me!
  636. Filtering means to collect all elements from a list which satisfy a
  637. specific condition. Partitioning a list means to make two groups of
  638. list elements, one which contains the elements satisfying a condition,
  639. and the other for the elements which don't.
  640. The @code{filter} and @code{filter!} functions are implemented in the
  641. Guile core, @xref{List Modification}.
  642. @deffn {Scheme Procedure} partition pred lst
  643. @deffnx {Scheme Procedure} partition! pred lst
  644. Split @var{lst} into those elements which do and don't satisfy the
  645. predicate @var{pred}.
  646. The return is two values (@pxref{Multiple Values}), the first being a
  647. list of all elements from @var{lst} which satisfy @var{pred}, the
  648. second a list of those which do not.
  649. The elements in the result lists are in the same order as in @var{lst}
  650. but the order in which the calls @code{(@var{pred} elem)} are made on
  651. the list elements is unspecified.
  652. @code{partition} does not change @var{lst}, but one of the returned
  653. lists may share a tail with it. @code{partition!} may modify
  654. @var{lst} to construct its return.
  655. @end deffn
  656. @deffn {Scheme Procedure} remove pred lst
  657. @deffnx {Scheme Procedure} remove! pred lst
  658. Return a list containing all elements from @var{lst} which do not
  659. satisfy the predicate @var{pred}. The elements in the result list
  660. have the same order as in @var{lst}. The order in which @var{pred} is
  661. applied to the list elements is not specified.
  662. @code{remove!} is allowed, but not required to modify the structure of
  663. the input list.
  664. @end deffn
  665. @node SRFI-1 Searching
  666. @subsubsection Searching
  667. @cindex list search
  668. @c FIXME::martin: Review me!
  669. The procedures for searching elements in lists either accept a
  670. predicate or a comparison object for determining which elements are to
  671. be searched.
  672. @deffn {Scheme Procedure} find pred lst
  673. Return the first element of @var{lst} that satisfies the predicate
  674. @var{pred} and @code{#f} if no such element is found.
  675. @end deffn
  676. @deffn {Scheme Procedure} find-tail pred lst
  677. Return the first pair of @var{lst} whose @sc{car} satisfies the
  678. predicate @var{pred} and @code{#f} if no such element is found.
  679. @end deffn
  680. @deffn {Scheme Procedure} take-while pred lst
  681. @deffnx {Scheme Procedure} take-while! pred lst
  682. Return the longest initial prefix of @var{lst} whose elements all
  683. satisfy the predicate @var{pred}.
  684. @code{take-while!} is allowed, but not required to modify the input
  685. list while producing the result.
  686. @end deffn
  687. @deffn {Scheme Procedure} drop-while pred lst
  688. Drop the longest initial prefix of @var{lst} whose elements all
  689. satisfy the predicate @var{pred}.
  690. @end deffn
  691. @deffn {Scheme Procedure} span pred lst
  692. @deffnx {Scheme Procedure} span! pred lst
  693. @deffnx {Scheme Procedure} break pred lst
  694. @deffnx {Scheme Procedure} break! pred lst
  695. @code{span} splits the list @var{lst} into the longest initial prefix
  696. whose elements all satisfy the predicate @var{pred}, and the remaining
  697. tail. @code{break} inverts the sense of the predicate.
  698. @code{span!} and @code{break!} are allowed, but not required to modify
  699. the structure of the input list @var{lst} in order to produce the
  700. result.
  701. Note that the name @code{break} conflicts with the @code{break}
  702. binding established by @code{while} (@pxref{while do}). Applications
  703. wanting to use @code{break} from within a @code{while} loop will need
  704. to make a new define under a different name.
  705. @end deffn
  706. @deffn {Scheme Procedure} any pred lst1 lst2 @dots{}
  707. Test whether any set of elements from @var{lst1} @var{lst2} @dots{}
  708. satisfies @var{pred}. If so, the return value is the return value from
  709. the successful @var{pred} call, or if not, the return value is
  710. @code{#f}.
  711. If there are n list arguments, then @var{pred} must be a predicate
  712. taking n arguments. Each @var{pred} call is @code{(@var{pred}
  713. @var{elem1} @var{elem2} @dots{} )} taking an element from each
  714. @var{lst}. The calls are made successively for the first, second, etc.
  715. elements of the lists, stopping when @var{pred} returns non-@code{#f},
  716. or when the end of the shortest list is reached.
  717. The @var{pred} call on the last set of elements (i.e., when the end of
  718. the shortest list has been reached), if that point is reached, is a
  719. tail call.
  720. @end deffn
  721. @deffn {Scheme Procedure} every pred lst1 lst2 @dots{}
  722. Test whether every set of elements from @var{lst1} @var{lst2} @dots{}
  723. satisfies @var{pred}. If so, the return value is the return from the
  724. final @var{pred} call, or if not, the return value is @code{#f}.
  725. If there are n list arguments, then @var{pred} must be a predicate
  726. taking n arguments. Each @var{pred} call is @code{(@var{pred}
  727. @var{elem1} @var{elem2 @dots{}})} taking an element from each
  728. @var{lst}. The calls are made successively for the first, second, etc.
  729. elements of the lists, stopping if @var{pred} returns @code{#f}, or when
  730. the end of any of the lists is reached.
  731. The @var{pred} call on the last set of elements (i.e., when the end of
  732. the shortest list has been reached) is a tail call.
  733. If one of @var{lst1} @var{lst2} @dots{}is empty then no calls to
  734. @var{pred} are made, and the return value is @code{#t}.
  735. @end deffn
  736. @deffn {Scheme Procedure} list-index pred lst1 lst2 @dots{}
  737. Return the index of the first set of elements, one from each of
  738. @var{lst1} @var{lst2} @dots{}, which satisfies @var{pred}.
  739. @var{pred} is called as @code{(@var{elem1} @var{elem2 @dots{}})}.
  740. Searching stops when the end of the shortest @var{lst} is reached.
  741. The return index starts from 0 for the first set of elements. If no
  742. set of elements pass, then the return value is @code{#f}.
  743. @example
  744. (list-index odd? '(2 4 6 9)) @result{} 3
  745. (list-index = '(1 2 3) '(3 1 2)) @result{} #f
  746. @end example
  747. @end deffn
  748. @deffn {Scheme Procedure} member x lst [=]
  749. Return the first sublist of @var{lst} whose @sc{car} is equal to
  750. @var{x}. If @var{x} does not appear in @var{lst}, return @code{#f}.
  751. Equality is determined by @code{equal?}, or by the equality predicate
  752. @var{=} if given. @var{=} is called @code{(= @var{x} elem)},
  753. ie.@: with the given @var{x} first, so for example to find the first
  754. element greater than 5,
  755. @example
  756. (member 5 '(3 5 1 7 2 9) <) @result{} (7 2 9)
  757. @end example
  758. This version of @code{member} extends the core @code{member}
  759. (@pxref{List Searching}) by accepting an equality predicate.
  760. @end deffn
  761. @node SRFI-1 Deleting
  762. @subsubsection Deleting
  763. @cindex list delete
  764. @deffn {Scheme Procedure} delete x lst [=]
  765. @deffnx {Scheme Procedure} delete! x lst [=]
  766. Return a list containing the elements of @var{lst} but with those
  767. equal to @var{x} deleted. The returned elements will be in the same
  768. order as they were in @var{lst}.
  769. Equality is determined by the @var{=} predicate, or @code{equal?} if
  770. not given. An equality call is made just once for each element, but
  771. the order in which the calls are made on the elements is unspecified.
  772. The equality calls are always @code{(= x elem)}, ie.@: the given @var{x}
  773. is first. This means for instance elements greater than 5 can be
  774. deleted with @code{(delete 5 lst <)}.
  775. @code{delete} does not modify @var{lst}, but the return might share a
  776. common tail with @var{lst}. @code{delete!} may modify the structure
  777. of @var{lst} to construct its return.
  778. These functions extend the core @code{delete} and @code{delete!}
  779. (@pxref{List Modification}) in accepting an equality predicate. See
  780. also @code{lset-difference} (@pxref{SRFI-1 Set Operations}) for
  781. deleting multiple elements from a list.
  782. @end deffn
  783. @deffn {Scheme Procedure} delete-duplicates lst [=]
  784. @deffnx {Scheme Procedure} delete-duplicates! lst [=]
  785. Return a list containing the elements of @var{lst} but without
  786. duplicates.
  787. When elements are equal, only the first in @var{lst} is retained.
  788. Equal elements can be anywhere in @var{lst}, they don't have to be
  789. adjacent. The returned list will have the retained elements in the
  790. same order as they were in @var{lst}.
  791. Equality is determined by the @var{=} predicate, or @code{equal?} if
  792. not given. Calls @code{(= x y)} are made with element @var{x} being
  793. before @var{y} in @var{lst}. A call is made at most once for each
  794. combination, but the sequence of the calls across the elements is
  795. unspecified.
  796. @code{delete-duplicates} does not modify @var{lst}, but the return
  797. might share a common tail with @var{lst}. @code{delete-duplicates!}
  798. may modify the structure of @var{lst} to construct its return.
  799. In the worst case, this is an @math{O(N^2)} algorithm because it must
  800. check each element against all those preceding it. For long lists it
  801. is more efficient to sort and then compare only adjacent elements.
  802. @end deffn
  803. @node SRFI-1 Association Lists
  804. @subsubsection Association Lists
  805. @cindex association list
  806. @cindex alist
  807. @c FIXME::martin: Review me!
  808. Association lists are described in detail in section @ref{Association
  809. Lists}. The present section only documents the additional procedures
  810. for dealing with association lists defined by SRFI-1.
  811. @deffn {Scheme Procedure} assoc key alist [=]
  812. Return the pair from @var{alist} which matches @var{key}. This
  813. extends the core @code{assoc} (@pxref{Retrieving Alist Entries}) by
  814. taking an optional @var{=} comparison procedure.
  815. The default comparison is @code{equal?}. If an @var{=} parameter is
  816. given it's called @code{(@var{=} @var{key} @var{alistcar})}, i.e.@: the
  817. given target @var{key} is the first argument, and a @code{car} from
  818. @var{alist} is second.
  819. For example a case-insensitive string lookup,
  820. @example
  821. (assoc "yy" '(("XX" . 1) ("YY" . 2)) string-ci=?)
  822. @result{} ("YY" . 2)
  823. @end example
  824. @end deffn
  825. @deffn {Scheme Procedure} alist-cons key datum alist
  826. Cons a new association @var{key} and @var{datum} onto @var{alist} and
  827. return the result. This is equivalent to
  828. @lisp
  829. (cons (cons @var{key} @var{datum}) @var{alist})
  830. @end lisp
  831. @code{acons} (@pxref{Adding or Setting Alist Entries}) in the Guile
  832. core does the same thing.
  833. @end deffn
  834. @deffn {Scheme Procedure} alist-copy alist
  835. Return a newly allocated copy of @var{alist}, that means that the
  836. spine of the list as well as the pairs are copied.
  837. @end deffn
  838. @deffn {Scheme Procedure} alist-delete key alist [=]
  839. @deffnx {Scheme Procedure} alist-delete! key alist [=]
  840. Return a list containing the elements of @var{alist} but with those
  841. elements whose keys are equal to @var{key} deleted. The returned
  842. elements will be in the same order as they were in @var{alist}.
  843. Equality is determined by the @var{=} predicate, or @code{equal?} if
  844. not given. The order in which elements are tested is unspecified, but
  845. each equality call is made @code{(= key alistkey)}, i.e.@: the given
  846. @var{key} parameter is first and the key from @var{alist} second.
  847. This means for instance all associations with a key greater than 5 can
  848. be removed with @code{(alist-delete 5 alist <)}.
  849. @code{alist-delete} does not modify @var{alist}, but the return might
  850. share a common tail with @var{alist}. @code{alist-delete!} may modify
  851. the list structure of @var{alist} to construct its return.
  852. @end deffn
  853. @node SRFI-1 Set Operations
  854. @subsubsection Set Operations on Lists
  855. @cindex list set operation
  856. Lists can be used to represent sets of objects. The procedures in
  857. this section operate on such lists as sets.
  858. Note that lists are not an efficient way to implement large sets. The
  859. procedures here typically take time @math{@var{m}@cross{}@var{n}} when
  860. operating on @var{m} and @var{n} element lists. Other data structures
  861. like trees, bitsets (@pxref{Bit Vectors}) or hash tables (@pxref{Hash
  862. Tables}) are faster.
  863. All these procedures take an equality predicate as the first argument.
  864. This predicate is used for testing the objects in the list sets for
  865. sameness. This predicate must be consistent with @code{eq?}
  866. (@pxref{Equality}) in the sense that if two list elements are
  867. @code{eq?} then they must also be equal under the predicate. This
  868. simply means a given object must be equal to itself.
  869. @deffn {Scheme Procedure} lset<= = list @dots{}
  870. Return @code{#t} if each list is a subset of the one following it.
  871. I.e., @var{list1} is a subset of @var{list2}, @var{list2} is a subset of
  872. @var{list3}, etc., for as many lists as given. If only one list or no
  873. lists are given, the return value is @code{#t}.
  874. A list @var{x} is a subset of @var{y} if each element of @var{x} is
  875. equal to some element in @var{y}. Elements are compared using the
  876. given @var{=} procedure, called as @code{(@var{=} xelem yelem)}.
  877. @example
  878. (lset<= eq?) @result{} #t
  879. (lset<= eqv? '(1 2 3) '(1)) @result{} #f
  880. (lset<= eqv? '(1 3 2) '(4 3 1 2)) @result{} #t
  881. @end example
  882. @end deffn
  883. @deffn {Scheme Procedure} lset= = list @dots{}
  884. Return @code{#t} if all argument lists are set-equal. @var{list1} is
  885. compared to @var{list2}, @var{list2} to @var{list3}, etc., for as many
  886. lists as given. If only one list or no lists are given, the return
  887. value is @code{#t}.
  888. Two lists @var{x} and @var{y} are set-equal if each element of @var{x}
  889. is equal to some element of @var{y} and conversely each element of
  890. @var{y} is equal to some element of @var{x}. The order of the
  891. elements in the lists doesn't matter. Element equality is determined
  892. with the given @var{=} procedure, called as @code{(@var{=} xelem
  893. yelem)}, but exactly which calls are made is unspecified.
  894. @example
  895. (lset= eq?) @result{} #t
  896. (lset= eqv? '(1 2 3) '(3 2 1)) @result{} #t
  897. (lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) @result{} #t
  898. @end example
  899. @end deffn
  900. @deffn {Scheme Procedure} lset-adjoin = list elem @dots{}
  901. Add to @var{list} any of the given @var{elem}s not already in the list.
  902. @var{elem}s are @code{cons}ed onto the start of @var{list} (so the
  903. return value shares a common tail with @var{list}), but the order that
  904. the @var{elem}s are added is unspecified.
  905. The given @var{=} procedure is used for comparing elements, called as
  906. @code{(@var{=} listelem elem)}, i.e., the second argument is one of
  907. the given @var{elem} parameters.
  908. @example
  909. (lset-adjoin eqv? '(1 2 3) 4 1 5) @result{} (5 4 1 2 3)
  910. @end example
  911. @end deffn
  912. @deffn {Scheme Procedure} lset-union = list @dots{}
  913. @deffnx {Scheme Procedure} lset-union! = list @dots{}
  914. Return the union of the argument list sets. The result is built by
  915. taking the union of @var{list1} and @var{list2}, then the union of
  916. that with @var{list3}, etc., for as many lists as given. For one list
  917. argument that list itself is the result, for no list arguments the
  918. result is the empty list.
  919. The union of two lists @var{x} and @var{y} is formed as follows. If
  920. @var{x} is empty then the result is @var{y}. Otherwise start with
  921. @var{x} as the result and consider each @var{y} element (from first to
  922. last). A @var{y} element not equal to something already in the result
  923. is @code{cons}ed onto the result.
  924. The given @var{=} procedure is used for comparing elements, called as
  925. @code{(@var{=} relem yelem)}. The first argument is from the result
  926. accumulated so far, and the second is from the list being union-ed in.
  927. But exactly which calls are made is otherwise unspecified.
  928. Notice that duplicate elements in @var{list1} (or the first non-empty
  929. list) are preserved, but that repeated elements in subsequent lists
  930. are only added once.
  931. @example
  932. (lset-union eqv?) @result{} ()
  933. (lset-union eqv? '(1 2 3)) @result{} (1 2 3)
  934. (lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) @result{} (5 4 1 2 1 3)
  935. @end example
  936. @code{lset-union} doesn't change the given lists but the result may
  937. share a tail with the first non-empty list. @code{lset-union!} can
  938. modify all of the given lists to form the result.
  939. @end deffn
  940. @deffn {Scheme Procedure} lset-intersection = list1 list2 @dots{}
  941. @deffnx {Scheme Procedure} lset-intersection! = list1 list2 @dots{}
  942. Return the intersection of @var{list1} with the other argument lists,
  943. meaning those elements of @var{list1} which are also in all of
  944. @var{list2} etc. For one list argument, just that list is returned.
  945. The test for an element of @var{list1} to be in the return is simply
  946. that it's equal to some element in each of @var{list2} etc. Notice
  947. this means an element appearing twice in @var{list1} but only once in
  948. each of @var{list2} etc will go into the return twice. The return has
  949. its elements in the same order as they were in @var{list1}.
  950. The given @var{=} procedure is used for comparing elements, called as
  951. @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
  952. and the second is from one of the subsequent lists. But exactly which
  953. calls are made and in what order is unspecified.
  954. @example
  955. (lset-intersection eqv? '(x y)) @result{} (x y)
  956. (lset-intersection eqv? '(1 2 3) '(4 3 2)) @result{} (2 3)
  957. (lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) @result{} (2 2)
  958. @end example
  959. The return from @code{lset-intersection} may share a tail with
  960. @var{list1}. @code{lset-intersection!} may modify @var{list1} to form
  961. its result.
  962. @end deffn
  963. @deffn {Scheme Procedure} lset-difference = list1 list2 @dots{}
  964. @deffnx {Scheme Procedure} lset-difference! = list1 list2 @dots{}
  965. Return @var{list1} with any elements in @var{list2}, @var{list3} etc
  966. removed (ie.@: subtracted). For one list argument, just that list is
  967. returned.
  968. The given @var{=} procedure is used for comparing elements, called as
  969. @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
  970. and the second from one of the subsequent lists. But exactly which
  971. calls are made and in what order is unspecified.
  972. @example
  973. (lset-difference eqv? '(x y)) @result{} (x y)
  974. (lset-difference eqv? '(1 2 3) '(3 1)) @result{} (2)
  975. (lset-difference eqv? '(1 2 3) '(3) '(2)) @result{} (1)
  976. @end example
  977. The return from @code{lset-difference} may share a tail with
  978. @var{list1}. @code{lset-difference!} may modify @var{list1} to form
  979. its result.
  980. @end deffn
  981. @deffn {Scheme Procedure} lset-diff+intersection = list1 list2 @dots{}
  982. @deffnx {Scheme Procedure} lset-diff+intersection! = list1 list2 @dots{}
  983. Return two values (@pxref{Multiple Values}), the difference and
  984. intersection of the argument lists as per @code{lset-difference} and
  985. @code{lset-intersection} above.
  986. For two list arguments this partitions @var{list1} into those elements
  987. of @var{list1} which are in @var{list2} and not in @var{list2}. (But
  988. for more than two arguments there can be elements of @var{list1} which
  989. are neither part of the difference nor the intersection.)
  990. One of the return values from @code{lset-diff+intersection} may share
  991. a tail with @var{list1}. @code{lset-diff+intersection!} may modify
  992. @var{list1} to form its results.
  993. @end deffn
  994. @deffn {Scheme Procedure} lset-xor = list @dots{}
  995. @deffnx {Scheme Procedure} lset-xor! = list @dots{}
  996. Return an XOR of the argument lists. For two lists this means those
  997. elements which are in exactly one of the lists. For more than two
  998. lists it means those elements which appear in an odd number of the
  999. lists.
  1000. To be precise, the XOR of two lists @var{x} and @var{y} is formed by
  1001. taking those elements of @var{x} not equal to any element of @var{y},
  1002. plus those elements of @var{y} not equal to any element of @var{x}.
  1003. Equality is determined with the given @var{=} procedure, called as
  1004. @code{(@var{=} e1 e2)}. One argument is from @var{x} and the other
  1005. from @var{y}, but which way around is unspecified. Exactly which
  1006. calls are made is also unspecified, as is the order of the elements in
  1007. the result.
  1008. @example
  1009. (lset-xor eqv? '(x y)) @result{} (x y)
  1010. (lset-xor eqv? '(1 2 3) '(4 3 2)) @result{} (4 1)
  1011. @end example
  1012. The return from @code{lset-xor} may share a tail with one of the list
  1013. arguments. @code{lset-xor!} may modify @var{list1} to form its
  1014. result.
  1015. @end deffn
  1016. @node SRFI-2
  1017. @subsection SRFI-2 - and-let*
  1018. @cindex SRFI-2
  1019. @noindent
  1020. The following syntax can be obtained with
  1021. @lisp
  1022. (use-modules (srfi srfi-2))
  1023. @end lisp
  1024. or alternatively
  1025. @lisp
  1026. (use-modules (ice-9 and-let-star))
  1027. @end lisp
  1028. @deffn {library syntax} and-let* (clause @dots{}) body @dots{}
  1029. A combination of @code{and} and @code{let*}.
  1030. Each @var{clause} is evaluated in turn, and if @code{#f} is obtained
  1031. then evaluation stops and @code{#f} is returned. If all are
  1032. non-@code{#f} then @var{body} is evaluated and the last form gives the
  1033. return value, or if @var{body} is empty then the result is @code{#t}.
  1034. Each @var{clause} should be one of the following,
  1035. @table @code
  1036. @item (symbol expr)
  1037. Evaluate @var{expr}, check for @code{#f}, and bind it to @var{symbol}.
  1038. Like @code{let*}, that binding is available to subsequent clauses.
  1039. @item (expr)
  1040. Evaluate @var{expr} and check for @code{#f}.
  1041. @item symbol
  1042. Get the value bound to @var{symbol} and check for @code{#f}.
  1043. @end table
  1044. Notice that @code{(expr)} has an ``extra'' pair of parentheses, for
  1045. instance @code{((eq? x y))}. One way to remember this is to imagine
  1046. the @code{symbol} in @code{(symbol expr)} is omitted.
  1047. @code{and-let*} is good for calculations where a @code{#f} value means
  1048. termination, but where a non-@code{#f} value is going to be needed in
  1049. subsequent expressions.
  1050. The following illustrates this, it returns text between brackets
  1051. @samp{[...]} in a string, or @code{#f} if there are no such brackets
  1052. (ie.@: either @code{string-index} gives @code{#f}).
  1053. @example
  1054. (define (extract-brackets str)
  1055. (and-let* ((start (string-index str #\[))
  1056. (end (string-index str #\] start)))
  1057. (substring str (1+ start) end)))
  1058. @end example
  1059. The following shows plain variables and expressions tested too.
  1060. @code{diagnostic-levels} is taken to be an alist associating a
  1061. diagnostic type with a level. @code{str} is printed only if the type
  1062. is known and its level is high enough.
  1063. @example
  1064. (define (show-diagnostic type str)
  1065. (and-let* (want-diagnostics
  1066. (level (assq-ref diagnostic-levels type))
  1067. ((>= level current-diagnostic-level)))
  1068. (display str)))
  1069. @end example
  1070. The advantage of @code{and-let*} is that an extended sequence of
  1071. expressions and tests doesn't require lots of nesting as would arise
  1072. from separate @code{and} and @code{let*}, or from @code{cond} with
  1073. @code{=>}.
  1074. @end deffn
  1075. @node SRFI-4
  1076. @subsection SRFI-4 - Homogeneous numeric vector datatypes
  1077. @cindex SRFI-4
  1078. SRFI-4 provides an interface to uniform numeric vectors: vectors whose elements
  1079. are all of a single numeric type. Guile offers uniform numeric vectors for
  1080. signed and unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
  1081. floating point values, and, as an extension to SRFI-4, complex floating-point
  1082. numbers of these two sizes.
  1083. The standard SRFI-4 procedures and data types may be included via loading the
  1084. appropriate module:
  1085. @example
  1086. (use-modules (srfi srfi-4))
  1087. @end example
  1088. This module is currently a part of the default Guile environment, but it is a
  1089. good practice to explicitly import the module. In the future, using SRFI-4
  1090. procedures without importing the SRFI-4 module will cause a deprecation message
  1091. to be printed. (Of course, one may call the C functions at any time. Would that
  1092. C had modules!)
  1093. @menu
  1094. * SRFI-4 Overview:: The warp and weft of uniform numeric vectors.
  1095. * SRFI-4 API:: Uniform vectors, from Scheme and from C.
  1096. * SRFI-4 and Bytevectors:: SRFI-4 vectors are backed by bytevectors.
  1097. * SRFI-4 Extensions:: Guile-specific extensions to the standard.
  1098. @end menu
  1099. @node SRFI-4 Overview
  1100. @subsubsection SRFI-4 - Overview
  1101. Uniform numeric vectors can be useful since they consume less memory
  1102. than the non-uniform, general vectors. Also, since the types they can
  1103. store correspond directly to C types, it is easier to work with them
  1104. efficiently on a low level. Consider image processing as an example,
  1105. where you want to apply a filter to some image. While you could store
  1106. the pixels of an image in a general vector and write a general
  1107. convolution function, things are much more efficient with uniform
  1108. vectors: the convolution function knows that all pixels are unsigned
  1109. 8-bit values (say), and can use a very tight inner loop.
  1110. This is implemented in Scheme by having the compiler notice calls to the SRFI-4
  1111. accessors, and inline them to appropriate compiled code. From C you have access
  1112. to the raw array; functions for efficiently working with uniform numeric vectors
  1113. from C are listed at the end of this section.
  1114. Uniform numeric vectors are the special case of one dimensional uniform
  1115. numeric arrays.
  1116. There are 12 standard kinds of uniform numeric vectors, and they all have their
  1117. own complement of constructors, accessors, and so on. Procedures that operate on
  1118. a specific kind of uniform numeric vector have a ``tag'' in their name,
  1119. indicating the element type.
  1120. @table @nicode
  1121. @item u8
  1122. unsigned 8-bit integers
  1123. @item s8
  1124. signed 8-bit integers
  1125. @item u16
  1126. unsigned 16-bit integers
  1127. @item s16
  1128. signed 16-bit integers
  1129. @item u32
  1130. unsigned 32-bit integers
  1131. @item s32
  1132. signed 32-bit integers
  1133. @item u64
  1134. unsigned 64-bit integers
  1135. @item s64
  1136. signed 64-bit integers
  1137. @item f32
  1138. the C type @code{float}
  1139. @item f64
  1140. the C type @code{double}
  1141. @end table
  1142. In addition, Guile supports uniform arrays of complex numbers, with the
  1143. nonstandard tags:
  1144. @table @nicode
  1145. @item c32
  1146. complex numbers in rectangular form with the real and imaginary part
  1147. being a @code{float}
  1148. @item c64
  1149. complex numbers in rectangular form with the real and imaginary part
  1150. being a @code{double}
  1151. @end table
  1152. The external representation (ie.@: read syntax) for these vectors is
  1153. similar to normal Scheme vectors, but with an additional tag from the
  1154. tables above indicating the vector's type. For example,
  1155. @lisp
  1156. #u16(1 2 3)
  1157. #f64(3.1415 2.71)
  1158. @end lisp
  1159. Note that the read syntax for floating-point here conflicts with
  1160. @code{#f} for false. In Standard Scheme one can write @code{(1 #f3)}
  1161. for a three element list @code{(1 #f 3)}, but for Guile @code{(1 #f3)}
  1162. is invalid. @code{(1 #f 3)} is almost certainly what one should write
  1163. anyway to make the intention clear, so this is rarely a problem.
  1164. @node SRFI-4 API
  1165. @subsubsection SRFI-4 - API
  1166. Note that the @nicode{c32} and @nicode{c64} functions are only available from
  1167. @nicode{(srfi srfi-4 gnu)}.
  1168. @deffn {Scheme Procedure} u8vector? obj
  1169. @deffnx {Scheme Procedure} s8vector? obj
  1170. @deffnx {Scheme Procedure} u16vector? obj
  1171. @deffnx {Scheme Procedure} s16vector? obj
  1172. @deffnx {Scheme Procedure} u32vector? obj
  1173. @deffnx {Scheme Procedure} s32vector? obj
  1174. @deffnx {Scheme Procedure} u64vector? obj
  1175. @deffnx {Scheme Procedure} s64vector? obj
  1176. @deffnx {Scheme Procedure} f32vector? obj
  1177. @deffnx {Scheme Procedure} f64vector? obj
  1178. @deffnx {Scheme Procedure} c32vector? obj
  1179. @deffnx {Scheme Procedure} c64vector? obj
  1180. @deffnx {C Function} scm_u8vector_p (obj)
  1181. @deffnx {C Function} scm_s8vector_p (obj)
  1182. @deffnx {C Function} scm_u16vector_p (obj)
  1183. @deffnx {C Function} scm_s16vector_p (obj)
  1184. @deffnx {C Function} scm_u32vector_p (obj)
  1185. @deffnx {C Function} scm_s32vector_p (obj)
  1186. @deffnx {C Function} scm_u64vector_p (obj)
  1187. @deffnx {C Function} scm_s64vector_p (obj)
  1188. @deffnx {C Function} scm_f32vector_p (obj)
  1189. @deffnx {C Function} scm_f64vector_p (obj)
  1190. @deffnx {C Function} scm_c32vector_p (obj)
  1191. @deffnx {C Function} scm_c64vector_p (obj)
  1192. Return @code{#t} if @var{obj} is a homogeneous numeric vector of the
  1193. indicated type.
  1194. @end deffn
  1195. @deffn {Scheme Procedure} make-u8vector n [value]
  1196. @deffnx {Scheme Procedure} make-s8vector n [value]
  1197. @deffnx {Scheme Procedure} make-u16vector n [value]
  1198. @deffnx {Scheme Procedure} make-s16vector n [value]
  1199. @deffnx {Scheme Procedure} make-u32vector n [value]
  1200. @deffnx {Scheme Procedure} make-s32vector n [value]
  1201. @deffnx {Scheme Procedure} make-u64vector n [value]
  1202. @deffnx {Scheme Procedure} make-s64vector n [value]
  1203. @deffnx {Scheme Procedure} make-f32vector n [value]
  1204. @deffnx {Scheme Procedure} make-f64vector n [value]
  1205. @deffnx {Scheme Procedure} make-c32vector n [value]
  1206. @deffnx {Scheme Procedure} make-c64vector n [value]
  1207. @deffnx {C Function} scm_make_u8vector (n, value)
  1208. @deffnx {C Function} scm_make_s8vector (n, value)
  1209. @deffnx {C Function} scm_make_u16vector (n, value)
  1210. @deffnx {C Function} scm_make_s16vector (n, value)
  1211. @deffnx {C Function} scm_make_u32vector (n, value)
  1212. @deffnx {C Function} scm_make_s32vector (n, value)
  1213. @deffnx {C Function} scm_make_u64vector (n, value)
  1214. @deffnx {C Function} scm_make_s64vector (n, value)
  1215. @deffnx {C Function} scm_make_f32vector (n, value)
  1216. @deffnx {C Function} scm_make_f64vector (n, value)
  1217. @deffnx {C Function} scm_make_c32vector (n, value)
  1218. @deffnx {C Function} scm_make_c64vector (n, value)
  1219. Return a newly allocated homogeneous numeric vector holding @var{n}
  1220. elements of the indicated type. If @var{value} is given, the vector
  1221. is initialized with that value, otherwise the contents are
  1222. unspecified.
  1223. @end deffn
  1224. @deffn {Scheme Procedure} u8vector value @dots{}
  1225. @deffnx {Scheme Procedure} s8vector value @dots{}
  1226. @deffnx {Scheme Procedure} u16vector value @dots{}
  1227. @deffnx {Scheme Procedure} s16vector value @dots{}
  1228. @deffnx {Scheme Procedure} u32vector value @dots{}
  1229. @deffnx {Scheme Procedure} s32vector value @dots{}
  1230. @deffnx {Scheme Procedure} u64vector value @dots{}
  1231. @deffnx {Scheme Procedure} s64vector value @dots{}
  1232. @deffnx {Scheme Procedure} f32vector value @dots{}
  1233. @deffnx {Scheme Procedure} f64vector value @dots{}
  1234. @deffnx {Scheme Procedure} c32vector value @dots{}
  1235. @deffnx {Scheme Procedure} c64vector value @dots{}
  1236. @deffnx {C Function} scm_u8vector (values)
  1237. @deffnx {C Function} scm_s8vector (values)
  1238. @deffnx {C Function} scm_u16vector (values)
  1239. @deffnx {C Function} scm_s16vector (values)
  1240. @deffnx {C Function} scm_u32vector (values)
  1241. @deffnx {C Function} scm_s32vector (values)
  1242. @deffnx {C Function} scm_u64vector (values)
  1243. @deffnx {C Function} scm_s64vector (values)
  1244. @deffnx {C Function} scm_f32vector (values)
  1245. @deffnx {C Function} scm_f64vector (values)
  1246. @deffnx {C Function} scm_c32vector (values)
  1247. @deffnx {C Function} scm_c64vector (values)
  1248. Return a newly allocated homogeneous numeric vector of the indicated
  1249. type, holding the given parameter @var{value}s. The vector length is
  1250. the number of parameters given.
  1251. @end deffn
  1252. @deffn {Scheme Procedure} u8vector-length vec
  1253. @deffnx {Scheme Procedure} s8vector-length vec
  1254. @deffnx {Scheme Procedure} u16vector-length vec
  1255. @deffnx {Scheme Procedure} s16vector-length vec
  1256. @deffnx {Scheme Procedure} u32vector-length vec
  1257. @deffnx {Scheme Procedure} s32vector-length vec
  1258. @deffnx {Scheme Procedure} u64vector-length vec
  1259. @deffnx {Scheme Procedure} s64vector-length vec
  1260. @deffnx {Scheme Procedure} f32vector-length vec
  1261. @deffnx {Scheme Procedure} f64vector-length vec
  1262. @deffnx {Scheme Procedure} c32vector-length vec
  1263. @deffnx {Scheme Procedure} c64vector-length vec
  1264. @deffnx {C Function} scm_u8vector_length (vec)
  1265. @deffnx {C Function} scm_s8vector_length (vec)
  1266. @deffnx {C Function} scm_u16vector_length (vec)
  1267. @deffnx {C Function} scm_s16vector_length (vec)
  1268. @deffnx {C Function} scm_u32vector_length (vec)
  1269. @deffnx {C Function} scm_s32vector_length (vec)
  1270. @deffnx {C Function} scm_u64vector_length (vec)
  1271. @deffnx {C Function} scm_s64vector_length (vec)
  1272. @deffnx {C Function} scm_f32vector_length (vec)
  1273. @deffnx {C Function} scm_f64vector_length (vec)
  1274. @deffnx {C Function} scm_c32vector_length (vec)
  1275. @deffnx {C Function} scm_c64vector_length (vec)
  1276. Return the number of elements in @var{vec}.
  1277. @end deffn
  1278. @deffn {Scheme Procedure} u8vector-ref vec i
  1279. @deffnx {Scheme Procedure} s8vector-ref vec i
  1280. @deffnx {Scheme Procedure} u16vector-ref vec i
  1281. @deffnx {Scheme Procedure} s16vector-ref vec i
  1282. @deffnx {Scheme Procedure} u32vector-ref vec i
  1283. @deffnx {Scheme Procedure} s32vector-ref vec i
  1284. @deffnx {Scheme Procedure} u64vector-ref vec i
  1285. @deffnx {Scheme Procedure} s64vector-ref vec i
  1286. @deffnx {Scheme Procedure} f32vector-ref vec i
  1287. @deffnx {Scheme Procedure} f64vector-ref vec i
  1288. @deffnx {Scheme Procedure} c32vector-ref vec i
  1289. @deffnx {Scheme Procedure} c64vector-ref vec i
  1290. @deffnx {C Function} scm_u8vector_ref (vec, i)
  1291. @deffnx {C Function} scm_s8vector_ref (vec, i)
  1292. @deffnx {C Function} scm_u16vector_ref (vec, i)
  1293. @deffnx {C Function} scm_s16vector_ref (vec, i)
  1294. @deffnx {C Function} scm_u32vector_ref (vec, i)
  1295. @deffnx {C Function} scm_s32vector_ref (vec, i)
  1296. @deffnx {C Function} scm_u64vector_ref (vec, i)
  1297. @deffnx {C Function} scm_s64vector_ref (vec, i)
  1298. @deffnx {C Function} scm_f32vector_ref (vec, i)
  1299. @deffnx {C Function} scm_f64vector_ref (vec, i)
  1300. @deffnx {C Function} scm_c32vector_ref (vec, i)
  1301. @deffnx {C Function} scm_c64vector_ref (vec, i)
  1302. Return the element at index @var{i} in @var{vec}. The first element
  1303. in @var{vec} is index 0.
  1304. @end deffn
  1305. @deffn {Scheme Procedure} u8vector-set! vec i value
  1306. @deffnx {Scheme Procedure} s8vector-set! vec i value
  1307. @deffnx {Scheme Procedure} u16vector-set! vec i value
  1308. @deffnx {Scheme Procedure} s16vector-set! vec i value
  1309. @deffnx {Scheme Procedure} u32vector-set! vec i value
  1310. @deffnx {Scheme Procedure} s32vector-set! vec i value
  1311. @deffnx {Scheme Procedure} u64vector-set! vec i value
  1312. @deffnx {Scheme Procedure} s64vector-set! vec i value
  1313. @deffnx {Scheme Procedure} f32vector-set! vec i value
  1314. @deffnx {Scheme Procedure} f64vector-set! vec i value
  1315. @deffnx {Scheme Procedure} c32vector-set! vec i value
  1316. @deffnx {Scheme Procedure} c64vector-set! vec i value
  1317. @deffnx {C Function} scm_u8vector_set_x (vec, i, value)
  1318. @deffnx {C Function} scm_s8vector_set_x (vec, i, value)
  1319. @deffnx {C Function} scm_u16vector_set_x (vec, i, value)
  1320. @deffnx {C Function} scm_s16vector_set_x (vec, i, value)
  1321. @deffnx {C Function} scm_u32vector_set_x (vec, i, value)
  1322. @deffnx {C Function} scm_s32vector_set_x (vec, i, value)
  1323. @deffnx {C Function} scm_u64vector_set_x (vec, i, value)
  1324. @deffnx {C Function} scm_s64vector_set_x (vec, i, value)
  1325. @deffnx {C Function} scm_f32vector_set_x (vec, i, value)
  1326. @deffnx {C Function} scm_f64vector_set_x (vec, i, value)
  1327. @deffnx {C Function} scm_c32vector_set_x (vec, i, value)
  1328. @deffnx {C Function} scm_c64vector_set_x (vec, i, value)
  1329. Set the element at index @var{i} in @var{vec} to @var{value}. The
  1330. first element in @var{vec} is index 0. The return value is
  1331. unspecified.
  1332. @end deffn
  1333. @deffn {Scheme Procedure} u8vector->list vec
  1334. @deffnx {Scheme Procedure} s8vector->list vec
  1335. @deffnx {Scheme Procedure} u16vector->list vec
  1336. @deffnx {Scheme Procedure} s16vector->list vec
  1337. @deffnx {Scheme Procedure} u32vector->list vec
  1338. @deffnx {Scheme Procedure} s32vector->list vec
  1339. @deffnx {Scheme Procedure} u64vector->list vec
  1340. @deffnx {Scheme Procedure} s64vector->list vec
  1341. @deffnx {Scheme Procedure} f32vector->list vec
  1342. @deffnx {Scheme Procedure} f64vector->list vec
  1343. @deffnx {Scheme Procedure} c32vector->list vec
  1344. @deffnx {Scheme Procedure} c64vector->list vec
  1345. @deffnx {C Function} scm_u8vector_to_list (vec)
  1346. @deffnx {C Function} scm_s8vector_to_list (vec)
  1347. @deffnx {C Function} scm_u16vector_to_list (vec)
  1348. @deffnx {C Function} scm_s16vector_to_list (vec)
  1349. @deffnx {C Function} scm_u32vector_to_list (vec)
  1350. @deffnx {C Function} scm_s32vector_to_list (vec)
  1351. @deffnx {C Function} scm_u64vector_to_list (vec)
  1352. @deffnx {C Function} scm_s64vector_to_list (vec)
  1353. @deffnx {C Function} scm_f32vector_to_list (vec)
  1354. @deffnx {C Function} scm_f64vector_to_list (vec)
  1355. @deffnx {C Function} scm_c32vector_to_list (vec)
  1356. @deffnx {C Function} scm_c64vector_to_list (vec)
  1357. Return a newly allocated list holding all elements of @var{vec}.
  1358. @end deffn
  1359. @deffn {Scheme Procedure} list->u8vector lst
  1360. @deffnx {Scheme Procedure} list->s8vector lst
  1361. @deffnx {Scheme Procedure} list->u16vector lst
  1362. @deffnx {Scheme Procedure} list->s16vector lst
  1363. @deffnx {Scheme Procedure} list->u32vector lst
  1364. @deffnx {Scheme Procedure} list->s32vector lst
  1365. @deffnx {Scheme Procedure} list->u64vector lst
  1366. @deffnx {Scheme Procedure} list->s64vector lst
  1367. @deffnx {Scheme Procedure} list->f32vector lst
  1368. @deffnx {Scheme Procedure} list->f64vector lst
  1369. @deffnx {Scheme Procedure} list->c32vector lst
  1370. @deffnx {Scheme Procedure} list->c64vector lst
  1371. @deffnx {C Function} scm_list_to_u8vector (lst)
  1372. @deffnx {C Function} scm_list_to_s8vector (lst)
  1373. @deffnx {C Function} scm_list_to_u16vector (lst)
  1374. @deffnx {C Function} scm_list_to_s16vector (lst)
  1375. @deffnx {C Function} scm_list_to_u32vector (lst)
  1376. @deffnx {C Function} scm_list_to_s32vector (lst)
  1377. @deffnx {C Function} scm_list_to_u64vector (lst)
  1378. @deffnx {C Function} scm_list_to_s64vector (lst)
  1379. @deffnx {C Function} scm_list_to_f32vector (lst)
  1380. @deffnx {C Function} scm_list_to_f64vector (lst)
  1381. @deffnx {C Function} scm_list_to_c32vector (lst)
  1382. @deffnx {C Function} scm_list_to_c64vector (lst)
  1383. Return a newly allocated homogeneous numeric vector of the indicated type,
  1384. initialized with the elements of the list @var{lst}.
  1385. @end deffn
  1386. @deftypefn {C Function} SCM scm_take_u8vector (const scm_t_uint8 *data, size_t len)
  1387. @deftypefnx {C Function} SCM scm_take_s8vector (const scm_t_int8 *data, size_t len)
  1388. @deftypefnx {C Function} SCM scm_take_u16vector (const scm_t_uint16 *data, size_t len)
  1389. @deftypefnx {C Function} SCM scm_take_s16vector (const scm_t_int16 *data, size_t len)
  1390. @deftypefnx {C Function} SCM scm_take_u32vector (const scm_t_uint32 *data, size_t len)
  1391. @deftypefnx {C Function} SCM scm_take_s32vector (const scm_t_int32 *data, size_t len)
  1392. @deftypefnx {C Function} SCM scm_take_u64vector (const scm_t_uint64 *data, size_t len)
  1393. @deftypefnx {C Function} SCM scm_take_s64vector (const scm_t_int64 *data, size_t len)
  1394. @deftypefnx {C Function} SCM scm_take_f32vector (const float *data, size_t len)
  1395. @deftypefnx {C Function} SCM scm_take_f64vector (const double *data, size_t len)
  1396. @deftypefnx {C Function} SCM scm_take_c32vector (const float *data, size_t len)
  1397. @deftypefnx {C Function} SCM scm_take_c64vector (const double *data, size_t len)
  1398. Return a new uniform numeric vector of the indicated type and length
  1399. that uses the memory pointed to by @var{data} to store its elements.
  1400. This memory will eventually be freed with @code{free}. The argument
  1401. @var{len} specifies the number of elements in @var{data}, not its size
  1402. in bytes.
  1403. The @code{c32} and @code{c64} variants take a pointer to a C array of
  1404. @code{float}s or @code{double}s. The real parts of the complex numbers
  1405. are at even indices in that array, the corresponding imaginary parts are
  1406. at the following odd index.
  1407. @end deftypefn
  1408. @deftypefn {C Function} {const scm_t_uint8 *} scm_u8vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1409. @deftypefnx {C Function} {const scm_t_int8 *} scm_s8vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1410. @deftypefnx {C Function} {const scm_t_uint16 *} scm_u16vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1411. @deftypefnx {C Function} {const scm_t_int16 *} scm_s16vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1412. @deftypefnx {C Function} {const scm_t_uint32 *} scm_u32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1413. @deftypefnx {C Function} {const scm_t_int32 *} scm_s32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1414. @deftypefnx {C Function} {const scm_t_uint64 *} scm_u64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1415. @deftypefnx {C Function} {const scm_t_int64 *} scm_s64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1416. @deftypefnx {C Function} {const float *} scm_f32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1417. @deftypefnx {C Function} {const double *} scm_f64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1418. @deftypefnx {C Function} {const float *} scm_c32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1419. @deftypefnx {C Function} {const double *} scm_c64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1420. Like @code{scm_vector_elements} (@pxref{Vector Accessing from C}), but
  1421. returns a pointer to the elements of a uniform numeric vector of the
  1422. indicated kind.
  1423. @end deftypefn
  1424. @deftypefn {C Function} {scm_t_uint8 *} scm_u8vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1425. @deftypefnx {C Function} {scm_t_int8 *} scm_s8vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1426. @deftypefnx {C Function} {scm_t_uint16 *} scm_u16vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1427. @deftypefnx {C Function} {scm_t_int16 *} scm_s16vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1428. @deftypefnx {C Function} {scm_t_uint32 *} scm_u32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1429. @deftypefnx {C Function} {scm_t_int32 *} scm_s32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1430. @deftypefnx {C Function} {scm_t_uint64 *} scm_u64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1431. @deftypefnx {C Function} {scm_t_int64 *} scm_s64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1432. @deftypefnx {C Function} {float *} scm_f32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1433. @deftypefnx {C Function} {double *} scm_f64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1434. @deftypefnx {C Function} {float *} scm_c32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1435. @deftypefnx {C Function} {double *} scm_c64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  1436. Like @code{scm_vector_writable_elements} (@pxref{Vector Accessing from C}),
  1437. but returns a pointer to the elements of a uniform numeric vector of the
  1438. indicated kind.
  1439. @end deftypefn
  1440. @node SRFI-4 and Bytevectors
  1441. @subsubsection SRFI-4 - Relation to bytevectors
  1442. Guile implements SRFI-4 vectors using bytevectors (@pxref{Bytevectors}). Often
  1443. when you have a numeric vector, you end up wanting to write its bytes somewhere,
  1444. or have access to the underlying bytes, or read in bytes from somewhere else.
  1445. Bytevectors are very good at this sort of thing. But the SRFI-4 APIs are nicer
  1446. to use when doing number-crunching, because they are addressed by element and
  1447. not by byte.
  1448. So as a compromise, Guile allows all bytevector functions to operate on numeric
  1449. vectors. They address the underlying bytes in the native endianness, as one
  1450. would expect.
  1451. Following the same reasoning, that it's just bytes underneath, Guile also allows
  1452. uniform vectors of a given type to be accessed as if they were of any type. One
  1453. can fill a @nicode{u32vector}, and access its elements with
  1454. @nicode{u8vector-ref}. One can use @nicode{f64vector-ref} on bytevectors. It's
  1455. all the same to Guile.
  1456. In this way, uniform numeric vectors may be written to and read from
  1457. input/output ports using the procedures that operate on bytevectors.
  1458. @xref{Bytevectors}, for more information.
  1459. @node SRFI-4 Extensions
  1460. @subsubsection SRFI-4 - Guile extensions
  1461. Guile defines some useful extensions to SRFI-4, which are not available in the
  1462. default Guile environment. They may be imported by loading the extensions
  1463. module:
  1464. @example
  1465. (use-modules (srfi srfi-4 gnu))
  1466. @end example
  1467. @deffn {Scheme Procedure} srfi-4-vector-type-size obj
  1468. Return the size, in bytes, of each element of SRFI-4 vector
  1469. @var{obj}. For example, @code{(srfi-4-vector-type-size #u32())} returns
  1470. @code{4}.
  1471. @end deffn
  1472. @deffn {Scheme Procedure} any->u8vector obj
  1473. @deffnx {Scheme Procedure} any->s8vector obj
  1474. @deffnx {Scheme Procedure} any->u16vector obj
  1475. @deffnx {Scheme Procedure} any->s16vector obj
  1476. @deffnx {Scheme Procedure} any->u32vector obj
  1477. @deffnx {Scheme Procedure} any->s32vector obj
  1478. @deffnx {Scheme Procedure} any->u64vector obj
  1479. @deffnx {Scheme Procedure} any->s64vector obj
  1480. @deffnx {Scheme Procedure} any->f32vector obj
  1481. @deffnx {Scheme Procedure} any->f64vector obj
  1482. @deffnx {Scheme Procedure} any->c32vector obj
  1483. @deffnx {Scheme Procedure} any->c64vector obj
  1484. @deffnx {C Function} scm_any_to_u8vector (obj)
  1485. @deffnx {C Function} scm_any_to_s8vector (obj)
  1486. @deffnx {C Function} scm_any_to_u16vector (obj)
  1487. @deffnx {C Function} scm_any_to_s16vector (obj)
  1488. @deffnx {C Function} scm_any_to_u32vector (obj)
  1489. @deffnx {C Function} scm_any_to_s32vector (obj)
  1490. @deffnx {C Function} scm_any_to_u64vector (obj)
  1491. @deffnx {C Function} scm_any_to_s64vector (obj)
  1492. @deffnx {C Function} scm_any_to_f32vector (obj)
  1493. @deffnx {C Function} scm_any_to_f64vector (obj)
  1494. @deffnx {C Function} scm_any_to_c32vector (obj)
  1495. @deffnx {C Function} scm_any_to_c64vector (obj)
  1496. Return a (maybe newly allocated) uniform numeric vector of the indicated
  1497. type, initialized with the elements of @var{obj}, which must be a list,
  1498. a vector, or a uniform vector. When @var{obj} is already a suitable
  1499. uniform numeric vector, it is returned unchanged.
  1500. @end deffn
  1501. @deffn {Scheme Procedure} u8vector-copy! dst at src [start [end]]
  1502. @deffnx {Scheme Procedure} s8vector-copy! dst at src [start [end]]
  1503. @deffnx {Scheme Procedure} u16vector-copy! dst at src [start [end]]
  1504. @deffnx {Scheme Procedure} s16vector-copy! dst at src [start [end]]
  1505. @deffnx {Scheme Procedure} u32vector-copy! dst at src [start [end]]
  1506. @deffnx {Scheme Procedure} s32vector-copy! dst at src [start [end]]
  1507. @deffnx {Scheme Procedure} u64vector-copy! dst at src [start [end]]
  1508. @deffnx {Scheme Procedure} s64vector-copy! dst at src [start [end]]
  1509. @deffnx {Scheme Procedure} f32vector-copy! dst at src [start [end]]
  1510. @deffnx {Scheme Procedure} f64vector-copy! dst at src [start [end]]
  1511. @deffnx {Scheme Procedure} c32vector-copy! dst at src [start [end]]
  1512. @deffnx {Scheme Procedure} c64vector-copy! dst at src [start [end]]
  1513. Copy a block of elements from @var{src} to @var{dst}, both of which must
  1514. be vectors of the indicated type, starting in @var{dst} at @var{at} and
  1515. starting in @var{src} at @var{start} and ending at @var{end}. It is an
  1516. error for @var{dst} to have a length less than @var{at} + (@var{end} -
  1517. @var{start}). @var{at} and @var{start} default to 0 and @var{end}
  1518. defaults to the length of @var{src}.
  1519. If source and destination overlap, copying takes place as if the
  1520. source is first copied into a temporary vector and then into the
  1521. destination.
  1522. See also @ref{x-vector-copy!,@code{vector-copy!}}.
  1523. @end deffn
  1524. @deffn {Scheme Procedure} u8vector-copy src [start [end]]
  1525. @deffnx {Scheme Procedure} s8vector-copy src [start [end]]
  1526. @deffnx {Scheme Procedure} u16vector-copy src [start [end]]
  1527. @deffnx {Scheme Procedure} s16vector-copy src [start [end]]
  1528. @deffnx {Scheme Procedure} u32vector-copy src [start [end]]
  1529. @deffnx {Scheme Procedure} s32vector-copy src [start [end]]
  1530. @deffnx {Scheme Procedure} u64vector-copy src [start [end]]
  1531. @deffnx {Scheme Procedure} s64vector-copy src [start [end]]
  1532. @deffnx {Scheme Procedure} f32vector-copy src [start [end]]
  1533. @deffnx {Scheme Procedure} f64vector-copy src [start [end]]
  1534. @deffnx {Scheme Procedure} c32vector-copy src [start [end]]
  1535. @deffnx {Scheme Procedure} c64vector-copy src [start [end]]
  1536. Returns a freshly allocated vector of the indicated type, which must be
  1537. the same as that of @var{src}, containing the elements of @var{src}
  1538. between @var{start} and @var{end}. @var{start} defaults to 0 and
  1539. @var{end} defaults to the length of @var{src}.
  1540. See also @ref{x-vector-copy,@code{vector-copy}}.
  1541. @end deffn
  1542. @node SRFI-6
  1543. @subsection SRFI-6 - Basic String Ports
  1544. @cindex SRFI-6
  1545. SRFI-6 defines the procedures @code{open-input-string},
  1546. @code{open-output-string} and @code{get-output-string}. These
  1547. procedures are included in the Guile core, so using this module does not
  1548. make any difference at the moment. But it is possible that support for
  1549. SRFI-6 will be factored out of the core library in the future, so using
  1550. this module does not hurt, after all.
  1551. @node SRFI-8
  1552. @subsection SRFI-8 - receive
  1553. @cindex SRFI-8
  1554. @code{receive} is a syntax for making the handling of multiple-value
  1555. procedures easier. It is documented in @xref{Multiple Values}.
  1556. @node SRFI-9
  1557. @subsection SRFI-9 - define-record-type
  1558. This SRFI is a syntax for defining new record types and creating
  1559. predicate, constructor, and field getter and setter functions. It is
  1560. documented in the ``Data Types'' section of the manual (@pxref{SRFI-9
  1561. Records}).
  1562. @node SRFI-10
  1563. @subsection SRFI-10 - Hash-Comma Reader Extension
  1564. @cindex SRFI-10
  1565. @cindex hash-comma
  1566. @cindex #,()
  1567. This SRFI implements a reader extension @code{#,()} called hash-comma.
  1568. It allows the reader to give new kinds of objects, for use both in data
  1569. and as constants or literals in source code. This feature is available
  1570. with
  1571. @example
  1572. (use-modules (srfi srfi-10))
  1573. @end example
  1574. @noindent
  1575. The new read syntax is of the form
  1576. @example
  1577. #,(@var{tag} @var{arg}@dots{})
  1578. @end example
  1579. @noindent
  1580. where @var{tag} is a symbol and the @var{arg}s are objects taken as
  1581. parameters. @var{tag}s are registered with the following procedure.
  1582. @deffn {Scheme Procedure} define-reader-ctor tag proc
  1583. Register @var{proc} as the constructor for a hash-comma read syntax
  1584. starting with symbol @var{tag}, i.e.@: @nicode{#,(@var{tag} arg@dots{})}.
  1585. @var{proc} is called with the given arguments @code{(@var{proc}
  1586. arg@dots{})} and the object it returns is the result of the read.
  1587. @end deffn
  1588. @noindent
  1589. For example, a syntax giving a list of @var{N} copies of an object.
  1590. @example
  1591. (define-reader-ctor 'repeat
  1592. (lambda (obj reps)
  1593. (make-list reps obj)))
  1594. (display '#,(repeat 99 3))
  1595. @print{} (99 99 99)
  1596. @end example
  1597. Notice the quote @nicode{'} when the @nicode{#,( )} is used. The
  1598. @code{repeat} handler returns a list and the program must quote to use
  1599. it literally, the same as any other list. Ie.
  1600. @example
  1601. (display '#,(repeat 99 3))
  1602. @result{}
  1603. (display '(99 99 99))
  1604. @end example
  1605. When a handler returns an object which is self-evaluating, like a
  1606. number or a string, then there's no need for quoting, just as there's
  1607. no need when giving those directly as literals. For example an
  1608. addition,
  1609. @example
  1610. (define-reader-ctor 'sum
  1611. (lambda (x y)
  1612. (+ x y)))
  1613. (display #,(sum 123 456)) @print{} 579
  1614. @end example
  1615. Once @code{(srfi srfi-10)} has loaded, @nicode{#,()} is available
  1616. globally, there's no need to use @code{(srfi srfi-10)} in later
  1617. modules. Similarly the tags registered are global and can be used
  1618. anywhere once registered.
  1619. We do not recommend @nicode{#,()} reader extensions, however, and for
  1620. three reasons.
  1621. First of all, this SRFI is not modular: the tag is matched by name, not
  1622. as an identifier within a scope. Defining a reader extension in one
  1623. part of a program can thus affect unrelated parts of a program because
  1624. the tag is not scoped.
  1625. Secondly, reader extensions can be hard to manage from a time
  1626. perspective: when does the reader extension take effect? @xref{Eval
  1627. When}, for more discussion.
  1628. Finally, reader extensions can easily produce objects that can't be
  1629. reified to an object file by the compiler. For example if you define a
  1630. reader extension that makes a hash table (@pxref{Hash Tables}), then it
  1631. will work fine when run with the interpreter, and you think you have a
  1632. neat hack. But then if you try to compile your program, after wrangling
  1633. with the @code{eval-when} concerns mentioned above, the compiler will
  1634. carp that it doesn't know how to serialize a hash table to disk.
  1635. In the specific case of hash tables, it would be possible for Guile to
  1636. know how to pack hash tables into compiled files, but this doesn't work
  1637. in general. What if the object you produce is an instance of a record
  1638. type? Guile would then have to serialize the record type to disk too,
  1639. and then what happens if the program independently loads the code that
  1640. defines the record type? Does it define the same type or a different
  1641. type? Guile's record types are nominal, not structural, so the answer
  1642. is not clear at all.
  1643. For all of these reasons we recommend macros over reader extensions.
  1644. Macros fulfill many of the same needs while preserving modular
  1645. composition, and their interaction with @code{eval-when} is well-known.
  1646. If you need brevity, instead use @code{read-hash-extend} and make your
  1647. reader extension expand to a macro invocation. In that way we preserve
  1648. scoping as much as possible. @xref{Reader Extensions}.
  1649. @node SRFI-11
  1650. @subsection SRFI-11 - let-values
  1651. @cindex SRFI-11
  1652. @findex let-values
  1653. @findex let*-values
  1654. This module implements the binding forms for multiple values
  1655. @code{let-values} and @code{let*-values}. These forms are similar to
  1656. @code{let} and @code{let*} (@pxref{Local Bindings}), but they support
  1657. binding of the values returned by multiple-valued expressions.
  1658. Write @code{(use-modules (srfi srfi-11))} to make the bindings
  1659. available.
  1660. @lisp
  1661. (let-values (((x y) (values 1 2))
  1662. ((z f) (values 3 4)))
  1663. (+ x y z f))
  1664. @result{}
  1665. 10
  1666. @end lisp
  1667. @code{let-values} performs all bindings simultaneously, which means that
  1668. no expression in the binding clauses may refer to variables bound in the
  1669. same clause list. @code{let*-values}, on the other hand, performs the
  1670. bindings sequentially, just like @code{let*} does for single-valued
  1671. expressions.
  1672. @node SRFI-13
  1673. @subsection SRFI-13 - String Library
  1674. @cindex SRFI-13
  1675. The SRFI-13 procedures are always available, @xref{Strings}.
  1676. @node SRFI-14
  1677. @subsection SRFI-14 - Character-set Library
  1678. @cindex SRFI-14
  1679. The SRFI-14 data type and procedures are always available,
  1680. @xref{Character Sets}.
  1681. @node SRFI-16
  1682. @subsection SRFI-16 - case-lambda
  1683. @cindex SRFI-16
  1684. @cindex variable arity
  1685. @cindex arity, variable
  1686. SRFI-16 defines a variable-arity @code{lambda} form,
  1687. @code{case-lambda}. This form is available in the default Guile
  1688. environment. @xref{Case-lambda}, for more information.
  1689. @node SRFI-17
  1690. @subsection SRFI-17 - Generalized set!
  1691. @cindex SRFI-17
  1692. This SRFI implements a generalized @code{set!}, allowing some
  1693. ``referencing'' functions to be used as the target location of a
  1694. @code{set!}. This feature is available from
  1695. @example
  1696. (use-modules (srfi srfi-17))
  1697. @end example
  1698. @noindent
  1699. For example @code{vector-ref} is extended so that
  1700. @example
  1701. (set! (vector-ref vec idx) new-value)
  1702. @end example
  1703. @noindent
  1704. is equivalent to
  1705. @example
  1706. (vector-set! vec idx new-value)
  1707. @end example
  1708. The idea is that a @code{vector-ref} expression identifies a location,
  1709. which may be either fetched or stored. The same form is used for the
  1710. location in both cases, encouraging visual clarity. This is similar
  1711. to the idea of an ``lvalue'' in C.
  1712. The mechanism for this kind of @code{set!} is in the Guile core
  1713. (@pxref{Procedures with Setters}). This module adds definitions of
  1714. the following functions as procedures with setters, allowing them to
  1715. be targets of a @code{set!},
  1716. @quotation
  1717. @nicode{car}, @nicode{cdr}, @nicode{caar}, @nicode{cadr},
  1718. @nicode{cdar}, @nicode{cddr}, @nicode{caaar}, @nicode{caadr},
  1719. @nicode{cadar}, @nicode{caddr}, @nicode{cdaar}, @nicode{cdadr},
  1720. @nicode{cddar}, @nicode{cdddr}, @nicode{caaaar}, @nicode{caaadr},
  1721. @nicode{caadar}, @nicode{caaddr}, @nicode{cadaar}, @nicode{cadadr},
  1722. @nicode{caddar}, @nicode{cadddr}, @nicode{cdaaar}, @nicode{cdaadr},
  1723. @nicode{cdadar}, @nicode{cdaddr}, @nicode{cddaar}, @nicode{cddadr},
  1724. @nicode{cdddar}, @nicode{cddddr}
  1725. @nicode{string-ref}, @nicode{vector-ref}
  1726. @end quotation
  1727. The SRFI specifies @code{setter} (@pxref{Procedures with Setters}) as
  1728. a procedure with setter, allowing the setter for a procedure to be
  1729. changed, eg.@: @code{(set! (setter foo) my-new-setter-handler)}.
  1730. Currently Guile does not implement this, a setter can only be
  1731. specified on creation (@code{getter-with-setter} below).
  1732. @defun getter-with-setter
  1733. The same as the Guile core @code{make-procedure-with-setter}
  1734. (@pxref{Procedures with Setters}).
  1735. @end defun
  1736. @node SRFI-18
  1737. @subsection SRFI-18 - Multithreading support
  1738. @cindex SRFI-18
  1739. This is an implementation of the SRFI-18 threading and synchronization
  1740. library. The functions and variables described here are provided by
  1741. @example
  1742. (use-modules (srfi srfi-18))
  1743. @end example
  1744. SRFI-18 defines facilities for threads, mutexes, condition variables,
  1745. time, and exception handling. Because these facilities are at a higher
  1746. level than Guile's primitives, they are implemented as a layer on top of
  1747. what Guile provides. In particular this means that a Guile mutex is not
  1748. a SRFI-18 mutex, and a Guile thread is not a SRFI-18 thread, and so on.
  1749. Guile provides a set of primitives and SRFI-18 is one of the systems built in terms of those primitives.
  1750. @menu
  1751. * SRFI-18 Threads:: Executing code
  1752. * SRFI-18 Mutexes:: Mutual exclusion devices
  1753. * SRFI-18 Condition variables:: Synchronizing of groups of threads
  1754. * SRFI-18 Time:: Representation of times and durations
  1755. * SRFI-18 Exceptions:: Signalling and handling errors
  1756. @end menu
  1757. @node SRFI-18 Threads
  1758. @subsubsection SRFI-18 Threads
  1759. Threads created by SRFI-18 differ in two ways from threads created by
  1760. Guile's built-in thread functions. First, a thread created by SRFI-18
  1761. @code{make-thread} begins in a blocked state and will not start
  1762. execution until @code{thread-start!} is called on it. Second, SRFI-18
  1763. threads are constructed with a top-level exception handler that
  1764. captures any exceptions that are thrown on thread exit.
  1765. SRFI-18 threads are disjoint from Guile's primitive threads.
  1766. @xref{Threads}, for more on Guile's primitive facility.
  1767. @defun current-thread
  1768. Returns the thread that called this function. This is the same
  1769. procedure as the same-named built-in procedure @code{current-thread}
  1770. (@pxref{Threads}).
  1771. @end defun
  1772. @defun thread? obj
  1773. Returns @code{#t} if @var{obj} is a thread, @code{#f} otherwise. This
  1774. is the same procedure as the same-named built-in procedure
  1775. @code{thread?} (@pxref{Threads}).
  1776. @end defun
  1777. @defun make-thread thunk [name]
  1778. Call @code{thunk} in a new thread and with a new dynamic state,
  1779. returning the new thread and optionally assigning it the object name
  1780. @var{name}, which may be any Scheme object.
  1781. Note that the name @code{make-thread} conflicts with the
  1782. @code{(ice-9 threads)} function @code{make-thread}. Applications
  1783. wanting to use both of these functions will need to refer to them by
  1784. different names.
  1785. @end defun
  1786. @defun thread-name thread
  1787. Returns the name assigned to @var{thread} at the time of its creation,
  1788. or @code{#f} if it was not given a name.
  1789. @end defun
  1790. @defun thread-specific thread
  1791. @defunx thread-specific-set! thread obj
  1792. Get or set the ``object-specific'' property of @var{thread}. In
  1793. Guile's implementation of SRFI-18, this value is stored as an object
  1794. property, and will be @code{#f} if not set.
  1795. @end defun
  1796. @defun thread-start! thread
  1797. Unblocks @var{thread} and allows it to begin execution if it has not
  1798. done so already.
  1799. @end defun
  1800. @defun thread-yield!
  1801. If one or more threads are waiting to execute, calling
  1802. @code{thread-yield!} forces an immediate context switch to one of them.
  1803. Otherwise, @code{thread-yield!} has no effect. @code{thread-yield!}
  1804. behaves identically to the Guile built-in function @code{yield}.
  1805. @end defun
  1806. @defun thread-sleep! timeout
  1807. The current thread waits until the point specified by the time object
  1808. @var{timeout} is reached (@pxref{SRFI-18 Time}). This blocks the
  1809. thread only if @var{timeout} represents a point in the future. it is
  1810. an error for @var{timeout} to be @code{#f}.
  1811. @end defun
  1812. @defun thread-terminate! thread
  1813. Causes an abnormal termination of @var{thread}. If @var{thread} is
  1814. not already terminated, all mutexes owned by @var{thread} become
  1815. unlocked/abandoned. If @var{thread} is the current thread,
  1816. @code{thread-terminate!} does not return. Otherwise
  1817. @code{thread-terminate!} returns an unspecified value; the termination
  1818. of @var{thread} will occur before @code{thread-terminate!} returns.
  1819. Subsequent attempts to join on @var{thread} will cause a ``terminated
  1820. thread exception'' to be raised.
  1821. @code{thread-terminate!} is compatible with the thread cancellation
  1822. procedures in the core threads API (@pxref{Threads}) in that if a
  1823. cleanup handler has been installed for the target thread, it will be
  1824. called before the thread exits and its return value (or exception, if
  1825. any) will be stored for later retrieval via a call to
  1826. @code{thread-join!}.
  1827. @end defun
  1828. @defun thread-join! thread [timeout [timeout-val]]
  1829. Wait for @var{thread} to terminate and return its exit value. When a
  1830. time value @var{timeout} is given, it specifies a point in time where
  1831. the waiting should be aborted. When the waiting is aborted,
  1832. @var{timeout-val} is returned if it is specified; otherwise, a
  1833. @code{join-timeout-exception} exception is raised
  1834. (@pxref{SRFI-18 Exceptions}). Exceptions may also be raised if the
  1835. thread was terminated by a call to @code{thread-terminate!}
  1836. (@code{terminated-thread-exception} will be raised) or if the thread
  1837. exited by raising an exception that was handled by the top-level
  1838. exception handler (@code{uncaught-exception} will be raised; the
  1839. original exception can be retrieved using
  1840. @code{uncaught-exception-reason}).
  1841. @end defun
  1842. @node SRFI-18 Mutexes
  1843. @subsubsection SRFI-18 Mutexes
  1844. SRFI-18 mutexes are disjoint from Guile's primitive mutexes.
  1845. @xref{Mutexes and Condition Variables}, for more on Guile's primitive
  1846. facility.
  1847. @defun make-mutex [name]
  1848. Returns a new mutex, optionally assigning it the object name @var{name},
  1849. which may be any Scheme object. The returned mutex will be created with
  1850. the configuration described above.
  1851. @end defun
  1852. @defun mutex-name mutex
  1853. Returns the name assigned to @var{mutex} at the time of its creation, or
  1854. @code{#f} if it was not given a name.
  1855. @end defun
  1856. @defun mutex-specific mutex
  1857. Return the ``object-specific'' property of @var{mutex}, or @code{#f} if
  1858. none is set.
  1859. @end defun
  1860. @defun mutex-specific-set! mutex obj
  1861. Set the ``object-specific'' property of @var{mutex}.
  1862. @end defun
  1863. @defun mutex-state mutex
  1864. Returns information about the state of @var{mutex}. Possible values
  1865. are:
  1866. @itemize @bullet
  1867. @item
  1868. thread @var{t}: the mutex is in the locked/owned state and thread
  1869. @var{t} is the owner of the mutex
  1870. @item
  1871. symbol @code{not-owned}: the mutex is in the locked/not-owned state
  1872. @item
  1873. symbol @code{abandoned}: the mutex is in the unlocked/abandoned state
  1874. @item
  1875. symbol @code{not-abandoned}: the mutex is in the
  1876. unlocked/not-abandoned state
  1877. @end itemize
  1878. @end defun
  1879. @defun mutex-lock! mutex [timeout [thread]]
  1880. Lock @var{mutex}, optionally specifying a time object @var{timeout}
  1881. after which to abort the lock attempt and a thread @var{thread} giving
  1882. a new owner for @var{mutex} different than the current thread.
  1883. @end defun
  1884. @defun mutex-unlock! mutex [condition-variable [timeout]]
  1885. Unlock @var{mutex}, optionally specifying a condition variable
  1886. @var{condition-variable} on which to wait, either indefinitely or,
  1887. optionally, until the time object @var{timeout} has passed, to be
  1888. signaled.
  1889. @end defun
  1890. @node SRFI-18 Condition variables
  1891. @subsubsection SRFI-18 Condition variables
  1892. SRFI-18 does not specify a ``wait'' function for condition variables.
  1893. Waiting on a condition variable can be simulated using the SRFI-18
  1894. @code{mutex-unlock!} function described in the previous section.
  1895. SRFI-18 condition variables are disjoint from Guile's primitive
  1896. condition variables. @xref{Mutexes and Condition Variables}, for more
  1897. on Guile's primitive facility.
  1898. @defun condition-variable? obj
  1899. Returns @code{#t} if @var{obj} is a condition variable, @code{#f}
  1900. otherwise.
  1901. @end defun
  1902. @defun make-condition-variable [name]
  1903. Returns a new condition variable, optionally assigning it the object
  1904. name @var{name}, which may be any Scheme object.
  1905. @end defun
  1906. @defun condition-variable-name condition-variable
  1907. Returns the name assigned to @var{condition-variable} at the time of its
  1908. creation, or @code{#f} if it was not given a name.
  1909. @end defun
  1910. @defun condition-variable-specific condition-variable
  1911. Return the ``object-specific'' property of @var{condition-variable}, or
  1912. @code{#f} if none is set.
  1913. @end defun
  1914. @defun condition-variable-specific-set! condition-variable obj
  1915. Set the ``object-specific'' property of @var{condition-variable}.
  1916. @end defun
  1917. @defun condition-variable-signal! condition-variable
  1918. @defunx condition-variable-broadcast! condition-variable
  1919. Wake up one thread that is waiting for @var{condition-variable}, in
  1920. the case of @code{condition-variable-signal!}, or all threads waiting
  1921. for it, in the case of @code{condition-variable-broadcast!}.
  1922. @end defun
  1923. @node SRFI-18 Time
  1924. @subsubsection SRFI-18 Time
  1925. The SRFI-18 time functions manipulate time in two formats: a
  1926. ``time object'' type that represents an absolute point in time in some
  1927. implementation-specific way; and the number of seconds since some
  1928. unspecified ``epoch''. In Guile's implementation, the epoch is the
  1929. Unix epoch, 00:00:00 UTC, January 1, 1970.
  1930. @defun current-time
  1931. Return the current time as a time object. This procedure replaces
  1932. the procedure of the same name in the core library, which returns the
  1933. current time in seconds since the epoch.
  1934. @end defun
  1935. @defun time? obj
  1936. Returns @code{#t} if @var{obj} is a time object, @code{#f} otherwise.
  1937. @end defun
  1938. @defun time->seconds time
  1939. @defunx seconds->time seconds
  1940. Convert between time objects and numerical values representing the
  1941. number of seconds since the epoch. When converting from a time object
  1942. to seconds, the return value is the number of seconds between
  1943. @var{time} and the epoch. When converting from seconds to a time
  1944. object, the return value is a time object that represents a time
  1945. @var{seconds} seconds after the epoch.
  1946. @end defun
  1947. @node SRFI-18 Exceptions
  1948. @subsubsection SRFI-18 Exceptions
  1949. SRFI-18 exceptions are identical to the exceptions provided by
  1950. Guile's implementation of SRFI-34. The behavior of exception
  1951. handlers invoked to handle exceptions thrown from SRFI-18 functions,
  1952. however, differs from the conventional behavior of SRFI-34 in that
  1953. the continuation of the handler is the same as that of the call to
  1954. the function. Handlers are called in a tail-recursive manner; the
  1955. exceptions do not ``bubble up''.
  1956. @defun current-exception-handler
  1957. Returns the current exception handler.
  1958. @end defun
  1959. @defun with-exception-handler handler thunk
  1960. Installs @var{handler} as the current exception handler and calls the
  1961. procedure @var{thunk} with no arguments, returning its value as the
  1962. value of the exception. @var{handler} must be a procedure that accepts
  1963. a single argument. The current exception handler at the time this
  1964. procedure is called will be restored after the call returns.
  1965. @end defun
  1966. @defun raise obj
  1967. Raise @var{obj} as an exception. This is the same procedure as the
  1968. same-named procedure defined in SRFI 34.
  1969. @end defun
  1970. @defun join-timeout-exception? obj
  1971. Returns @code{#t} if @var{obj} is an exception raised as the result of
  1972. performing a timed join on a thread that does not exit within the
  1973. specified timeout, @code{#f} otherwise.
  1974. @end defun
  1975. @defun abandoned-mutex-exception? obj
  1976. Returns @code{#t} if @var{obj} is an exception raised as the result of
  1977. attempting to lock a mutex that has been abandoned by its owner thread,
  1978. @code{#f} otherwise.
  1979. @end defun
  1980. @defun terminated-thread-exception? obj
  1981. Returns @code{#t} if @var{obj} is an exception raised as the result of
  1982. joining on a thread that exited as the result of a call to
  1983. @code{thread-terminate!}.
  1984. @end defun
  1985. @defun uncaught-exception? obj
  1986. @defunx uncaught-exception-reason exc
  1987. @code{uncaught-exception?} returns @code{#t} if @var{obj} is an
  1988. exception thrown as the result of joining a thread that exited by
  1989. raising an exception that was handled by the top-level exception
  1990. handler installed by @code{make-thread}. When this occurs, the
  1991. original exception is preserved as part of the exception thrown by
  1992. @code{thread-join!} and can be accessed by calling
  1993. @code{uncaught-exception-reason} on that exception. Note that
  1994. because this exception-preservation mechanism is a side-effect of
  1995. @code{make-thread}, joining on threads that exited as described above
  1996. but were created by other means will not raise this
  1997. @code{uncaught-exception} error.
  1998. @end defun
  1999. @node SRFI-19
  2000. @subsection SRFI-19 - Time/Date Library
  2001. @cindex SRFI-19
  2002. @cindex time
  2003. @cindex date
  2004. This is an implementation of the SRFI-19 time/date library. The
  2005. functions and variables described here are provided by
  2006. @example
  2007. (use-modules (srfi srfi-19))
  2008. @end example
  2009. @menu
  2010. * SRFI-19 Introduction::
  2011. * SRFI-19 Time::
  2012. * SRFI-19 Date::
  2013. * SRFI-19 Time/Date conversions::
  2014. * SRFI-19 Date to string::
  2015. * SRFI-19 String to date::
  2016. @end menu
  2017. @node SRFI-19 Introduction
  2018. @subsubsection SRFI-19 Introduction
  2019. @cindex universal time
  2020. @cindex atomic time
  2021. @cindex UTC
  2022. @cindex TAI
  2023. This module implements time and date representations and calculations,
  2024. in various time systems, including Coordinated Universal Time (UTC)
  2025. and International Atomic Time (TAI).
  2026. For those not familiar with these time systems, TAI is based on a
  2027. fixed length second derived from oscillations of certain atoms. UTC
  2028. differs from TAI by an integral number of seconds, which is increased
  2029. or decreased at announced times to keep UTC aligned to a mean solar
  2030. day (the orbit and rotation of the earth are not quite constant).
  2031. @cindex leap second
  2032. So far, only increases in the TAI
  2033. @tex
  2034. $\leftrightarrow$
  2035. @end tex
  2036. @ifnottex
  2037. <->
  2038. @end ifnottex
  2039. UTC difference have been needed. Such an increase is a ``leap
  2040. second'', an extra second of TAI introduced at the end of a UTC day.
  2041. When working entirely within UTC this is never seen, every day simply
  2042. has 86400 seconds. But when converting from TAI to a UTC date, an
  2043. extra 23:59:60 is present, where normally a day would end at 23:59:59.
  2044. Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI
  2045. seconds.
  2046. @cindex system clock
  2047. In the current implementation, the system clock is assumed to be UTC,
  2048. and a table of leap seconds in the code converts to TAI. See comments
  2049. in @file{srfi-19.scm} for how to update this table.
  2050. @cindex julian day
  2051. @cindex modified julian day
  2052. Also, for those not familiar with the terminology, a @dfn{Julian Day}
  2053. represents a point in time as a real number of days since
  2054. -4713-11-24T12:00:00Z, i.e.@: midday UT on 24 November 4714 BC in the
  2055. proleptic Gregorian calendar (1 January 4713 BC in the proleptic Julian
  2056. calendar).
  2057. A @dfn{Modified Julian Day} represents a point in time as a real number
  2058. of days since 1858-11-17T00:00:00Z, i.e.@: midnight UT on Wednesday 17
  2059. November AD 1858. That time is julian day 2400000.5.
  2060. @node SRFI-19 Time
  2061. @subsubsection SRFI-19 Time
  2062. @cindex time
  2063. A @dfn{time} object has type, seconds and nanoseconds fields
  2064. representing a point in time starting from some epoch. This is an
  2065. arbitrary point in time, not just a time of day. Although times are
  2066. represented in nanoseconds, the actual resolution may be lower.
  2067. The following variables hold the possible time types. For instance
  2068. @code{(current-time time-process)} would give the current CPU process
  2069. time.
  2070. @defvar time-utc
  2071. Universal Coordinated Time (UTC).
  2072. @cindex UTC
  2073. @end defvar
  2074. @defvar time-tai
  2075. International Atomic Time (TAI).
  2076. @cindex TAI
  2077. @end defvar
  2078. @defvar time-monotonic
  2079. Monotonic time, meaning a monotonically increasing time starting from
  2080. an unspecified epoch.
  2081. Note that in the current implementation @code{time-monotonic} is the
  2082. same as @code{time-tai}, and unfortunately is therefore affected by
  2083. adjustments to the system clock. Perhaps this will change in the
  2084. future.
  2085. @end defvar
  2086. @defvar time-duration
  2087. A duration, meaning simply a difference between two times.
  2088. @end defvar
  2089. @defvar time-process
  2090. CPU time spent in the current process, starting from when the process
  2091. began.
  2092. @cindex process time
  2093. @end defvar
  2094. @defvar time-thread
  2095. CPU time spent in the current thread. Not currently implemented.
  2096. @cindex thread time
  2097. @end defvar
  2098. @sp 1
  2099. @defun time? obj
  2100. Return @code{#t} if @var{obj} is a time object, or @code{#f} if not.
  2101. @end defun
  2102. @defun make-time type nanoseconds seconds
  2103. Create a time object with the given @var{type}, @var{seconds} and
  2104. @var{nanoseconds}.
  2105. @end defun
  2106. @defun time-type time
  2107. @defunx time-nanosecond time
  2108. @defunx time-second time
  2109. @defunx set-time-type! time type
  2110. @defunx set-time-nanosecond! time nsec
  2111. @defunx set-time-second! time sec
  2112. Get or set the type, seconds or nanoseconds fields of a time object.
  2113. @code{set-time-type!} merely changes the field, it doesn't convert the
  2114. time value. For conversions, see @ref{SRFI-19 Time/Date conversions}.
  2115. @end defun
  2116. @defun copy-time time
  2117. Return a new time object, which is a copy of the given @var{time}.
  2118. @end defun
  2119. @defun current-time [type]
  2120. Return the current time of the given @var{type}. The default
  2121. @var{type} is @code{time-utc}.
  2122. Note that the name @code{current-time} conflicts with the Guile core
  2123. @code{current-time} function (@pxref{Time}) as well as the SRFI-18
  2124. @code{current-time} function (@pxref{SRFI-18 Time}). Applications
  2125. wanting to use more than one of these functions will need to refer to
  2126. them by different names.
  2127. @end defun
  2128. @defun time-resolution [type]
  2129. Return the resolution, in nanoseconds, of the given time @var{type}.
  2130. The default @var{type} is @code{time-utc}.
  2131. @end defun
  2132. @defun time<=? t1 t2
  2133. @defunx time<? t1 t2
  2134. @defunx time=? t1 t2
  2135. @defunx time>=? t1 t2
  2136. @defunx time>? t1 t2
  2137. Return @code{#t} or @code{#f} according to the respective relation
  2138. between time objects @var{t1} and @var{t2}. @var{t1} and @var{t2}
  2139. must be the same time type.
  2140. @end defun
  2141. @defun time-difference t1 t2
  2142. @defunx time-difference! t1 t2
  2143. Return a time object of type @code{time-duration} representing the
  2144. period between @var{t1} and @var{t2}. @var{t1} and @var{t2} must be
  2145. the same time type.
  2146. @code{time-difference} returns a new time object,
  2147. @code{time-difference!} may modify @var{t1} to form its return.
  2148. @end defun
  2149. @defun add-duration time duration
  2150. @defunx add-duration! time duration
  2151. @defunx subtract-duration time duration
  2152. @defunx subtract-duration! time duration
  2153. Return a time object which is @var{time} with the given @var{duration}
  2154. added or subtracted. @var{duration} must be a time object of type
  2155. @code{time-duration}.
  2156. @code{add-duration} and @code{subtract-duration} return a new time
  2157. object. @code{add-duration!} and @code{subtract-duration!} may modify
  2158. the given @var{time} to form their return.
  2159. @end defun
  2160. @node SRFI-19 Date
  2161. @subsubsection SRFI-19 Date
  2162. @cindex date
  2163. A @dfn{date} object represents a date in the Gregorian calendar and a
  2164. time of day on that date in some timezone.
  2165. The fields are year, month, day, hour, minute, second, nanoseconds and
  2166. timezone. A date object is immutable, its fields can be read but they
  2167. cannot be modified once the object is created.
  2168. Historically, the Gregorian calendar was only used from the latter part
  2169. of the year 1582 onwards, and not until even later in many countries.
  2170. Prior to that most countries used the Julian calendar. SRFI-19 does
  2171. not deal with the Julian calendar at all, and so does not reflect this
  2172. historical calendar reform. Instead it projects the Gregorian calendar
  2173. back proleptically as far as necessary. When dealing with historical
  2174. data, especially prior to the British Empire's adoption of the Gregorian
  2175. calendar in 1752, one should be mindful of which calendar is used in
  2176. each context, and apply non-SRFI-19 facilities to convert where necessary.
  2177. @defun date? obj
  2178. Return @code{#t} if @var{obj} is a date object, or @code{#f} if not.
  2179. @end defun
  2180. @defun make-date nsecs seconds minutes hours date month year zone-offset
  2181. Create a new date object.
  2182. @c
  2183. @c FIXME: What can we say about the ranges of the values. The
  2184. @c current code looks it doesn't normalize, but expects then in their
  2185. @c usual range already.
  2186. @c
  2187. @end defun
  2188. @defun date-nanosecond date
  2189. Nanoseconds, 0 to 999999999.
  2190. @end defun
  2191. @defun date-second date
  2192. Seconds, 0 to 59, or 60 for a leap second. 60 is never seen when working
  2193. entirely within UTC, it's only when converting to or from TAI.
  2194. @end defun
  2195. @defun date-minute date
  2196. Minutes, 0 to 59.
  2197. @end defun
  2198. @defun date-hour date
  2199. Hour, 0 to 23.
  2200. @end defun
  2201. @defun date-day date
  2202. Day of the month, 1 to 31 (or less, according to the month).
  2203. @end defun
  2204. @defun date-month date
  2205. Month, 1 to 12.
  2206. @end defun
  2207. @defun date-year date
  2208. Year, eg.@: 2003. Dates B.C.@: are negative, eg.@: @math{-46} is 46
  2209. B.C. There is no year 0, year @math{-1} is followed by year 1.
  2210. @end defun
  2211. @defun date-zone-offset date
  2212. Time zone, an integer number of seconds east of Greenwich.
  2213. @end defun
  2214. @defun date-year-day date
  2215. Day of the year, starting from 1 for 1st January.
  2216. @end defun
  2217. @defun date-week-day date
  2218. Day of the week, starting from 0 for Sunday.
  2219. @end defun
  2220. @defun date-week-number date dstartw
  2221. Week of the year, ignoring a first partial week. @var{dstartw} is the
  2222. day of the week which is taken to start a week, 0 for Sunday, 1 for
  2223. Monday, etc.
  2224. @c
  2225. @c FIXME: The spec doesn't say whether numbering starts at 0 or 1.
  2226. @c The code looks like it's 0, if that's the correct intention.
  2227. @c
  2228. @end defun
  2229. @c The SRFI text doesn't actually give the default for tz-offset, but
  2230. @c the reference implementation has the local timezone and the
  2231. @c conversions functions all specify that, so it should be ok to
  2232. @c document it here.
  2233. @c
  2234. @defun current-date [tz-offset]
  2235. Return a date object representing the current date/time, in UTC offset
  2236. by @var{tz-offset}. @var{tz-offset} is seconds east of Greenwich and
  2237. defaults to the local timezone.
  2238. @end defun
  2239. @defun current-julian-day
  2240. @cindex julian day
  2241. Return the current Julian Day.
  2242. @end defun
  2243. @defun current-modified-julian-day
  2244. @cindex modified julian day
  2245. Return the current Modified Julian Day.
  2246. @end defun
  2247. @node SRFI-19 Time/Date conversions
  2248. @subsubsection SRFI-19 Time/Date conversions
  2249. @cindex time conversion
  2250. @cindex date conversion
  2251. @defun date->julian-day date
  2252. @defunx date->modified-julian-day date
  2253. @defunx date->time-monotonic date
  2254. @defunx date->time-tai date
  2255. @defunx date->time-utc date
  2256. @end defun
  2257. @defun julian-day->date jdn [tz-offset]
  2258. @defunx julian-day->time-monotonic jdn
  2259. @defunx julian-day->time-tai jdn
  2260. @defunx julian-day->time-utc jdn
  2261. @end defun
  2262. @defun modified-julian-day->date jdn [tz-offset]
  2263. @defunx modified-julian-day->time-monotonic jdn
  2264. @defunx modified-julian-day->time-tai jdn
  2265. @defunx modified-julian-day->time-utc jdn
  2266. @end defun
  2267. @defun time-monotonic->date time [tz-offset]
  2268. @defunx time-monotonic->time-tai time
  2269. @defunx time-monotonic->time-tai! time
  2270. @defunx time-monotonic->time-utc time
  2271. @defunx time-monotonic->time-utc! time
  2272. @end defun
  2273. @defun time-tai->date time [tz-offset]
  2274. @defunx time-tai->julian-day time
  2275. @defunx time-tai->modified-julian-day time
  2276. @defunx time-tai->time-monotonic time
  2277. @defunx time-tai->time-monotonic! time
  2278. @defunx time-tai->time-utc time
  2279. @defunx time-tai->time-utc! time
  2280. @end defun
  2281. @defun time-utc->date time [tz-offset]
  2282. @defunx time-utc->julian-day time
  2283. @defunx time-utc->modified-julian-day time
  2284. @defunx time-utc->time-monotonic time
  2285. @defunx time-utc->time-monotonic! time
  2286. @defunx time-utc->time-tai time
  2287. @defunx time-utc->time-tai! time
  2288. @sp 1
  2289. Convert between dates, times and days of the respective types. For
  2290. instance @code{time-tai->time-utc} accepts a @var{time} object of type
  2291. @code{time-tai} and returns an object of type @code{time-utc}.
  2292. The @code{!} variants may modify their @var{time} argument to form
  2293. their return. The plain functions create a new object.
  2294. For conversions to dates, @var{tz-offset} is seconds east of
  2295. Greenwich. The default is the local timezone, at the given time, as
  2296. provided by the system, using @code{localtime} (@pxref{Time}).
  2297. On 32-bit systems, @code{localtime} is limited to a 32-bit
  2298. @code{time_t}, so a default @var{tz-offset} is only available for
  2299. times between Dec 1901 and Jan 2038. For prior dates an application
  2300. might like to use the value in 1902, though some locations have zone
  2301. changes prior to that. For future dates an application might like to
  2302. assume today's rules extend indefinitely. But for correct daylight
  2303. savings transitions it will be necessary to take an offset for the
  2304. same day and time but a year in range and which has the same starting
  2305. weekday and same leap/non-leap (to support rules like last Sunday in
  2306. October).
  2307. @end defun
  2308. @node SRFI-19 Date to string
  2309. @subsubsection SRFI-19 Date to string
  2310. @cindex date to string
  2311. @cindex string, from date
  2312. @defun date->string date [format]
  2313. Convert a date to a string under the control of a format.
  2314. @var{format} should be a string containing @samp{~} escapes, which
  2315. will be expanded as per the following conversion table. The default
  2316. @var{format} is @samp{~c}, a locale-dependent date and time.
  2317. Many of these conversion characters are the same as POSIX
  2318. @code{strftime} (@pxref{Time}), but there are some extras and some
  2319. variations.
  2320. @multitable {MMMM} {MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}
  2321. @item @nicode{~~} @tab literal ~
  2322. @item @nicode{~a} @tab locale abbreviated weekday, eg.@: @samp{Sun}
  2323. @item @nicode{~A} @tab locale full weekday, eg.@: @samp{Sunday}
  2324. @item @nicode{~b} @tab locale abbreviated month, eg.@: @samp{Jan}
  2325. @item @nicode{~B} @tab locale full month, eg.@: @samp{January}
  2326. @item @nicode{~c} @tab locale date and time, eg.@: @*
  2327. @samp{Fri Jul 14 20:28:42-0400 2000}
  2328. @item @nicode{~d} @tab day of month, zero padded, @samp{01} to @samp{31}
  2329. @c Spec says d/m/y, reference implementation says m/d/y.
  2330. @c Apparently the reference code was the intention, but would like to
  2331. @c see an errata published for the spec before contradicting it here.
  2332. @c
  2333. @c @item @nicode{~D} @tab date @nicode{~d/~m/~y}
  2334. @item @nicode{~e} @tab day of month, blank padded, @samp{ 1} to @samp{31}
  2335. @item @nicode{~f} @tab seconds and fractional seconds,
  2336. with locale decimal point, eg.@: @samp{5.2}
  2337. @item @nicode{~h} @tab same as @nicode{~b}
  2338. @item @nicode{~H} @tab hour, 24-hour clock, zero padded, @samp{00} to @samp{23}
  2339. @item @nicode{~I} @tab hour, 12-hour clock, zero padded, @samp{01} to @samp{12}
  2340. @item @nicode{~j} @tab day of year, zero padded, @samp{001} to @samp{366}
  2341. @item @nicode{~k} @tab hour, 24-hour clock, blank padded, @samp{ 0} to @samp{23}
  2342. @item @nicode{~l} @tab hour, 12-hour clock, blank padded, @samp{ 1} to @samp{12}
  2343. @item @nicode{~m} @tab month, zero padded, @samp{01} to @samp{12}
  2344. @item @nicode{~M} @tab minute, zero padded, @samp{00} to @samp{59}
  2345. @item @nicode{~n} @tab newline
  2346. @item @nicode{~N} @tab nanosecond, zero padded, @samp{000000000} to @samp{999999999}
  2347. @item @nicode{~p} @tab locale AM or PM
  2348. @item @nicode{~r} @tab time, 12 hour clock, @samp{~I:~M:~S ~p}
  2349. @item @nicode{~s} @tab number of full seconds since ``the epoch'' in UTC
  2350. @item @nicode{~S} @tab second, zero padded @samp{00} to @samp{60} @*
  2351. (usual limit is 59, 60 is a leap second)
  2352. @item @nicode{~t} @tab horizontal tab character
  2353. @item @nicode{~T} @tab time, 24 hour clock, @samp{~H:~M:~S}
  2354. @item @nicode{~U} @tab week of year, Sunday first day of week,
  2355. @samp{00} to @samp{52}
  2356. @item @nicode{~V} @tab week of year, Monday first day of week,
  2357. @samp{01} to @samp{53}
  2358. @item @nicode{~w} @tab day of week, 0 for Sunday, @samp{0} to @samp{6}
  2359. @item @nicode{~W} @tab week of year, Monday first day of week,
  2360. @samp{00} to @samp{52}
  2361. @c The spec has ~x as an apparent duplicate of ~W, and ~X as a locale
  2362. @c date. The reference code has ~x as the locale date and ~X as a
  2363. @c locale time. The rule is apparently that the code should be
  2364. @c believed, but would like to see an errata for the spec before
  2365. @c contradicting it here.
  2366. @c
  2367. @c @item @nicode{~x} @tab week of year, Monday as first day of week,
  2368. @c @samp{00} to @samp{53}
  2369. @c @item @nicode{~X} @tab locale date, eg.@: @samp{07/31/00}
  2370. @item @nicode{~y} @tab year, two digits, @samp{00} to @samp{99}
  2371. @item @nicode{~Y} @tab year, full, eg.@: @samp{2003}
  2372. @item @nicode{~z} @tab time zone, RFC-822 style
  2373. @item @nicode{~Z} @tab time zone symbol (not currently implemented)
  2374. @item @nicode{~1} @tab ISO-8601 date, @samp{~Y-~m-~d}
  2375. @item @nicode{~2} @tab ISO-8601 time+zone, @samp{~H:~M:~S~z}
  2376. @item @nicode{~3} @tab ISO-8601 time, @samp{~H:~M:~S}
  2377. @item @nicode{~4} @tab ISO-8601 date/time+zone, @samp{~Y-~m-~dT~H:~M:~S~z}
  2378. @item @nicode{~5} @tab ISO-8601 date/time, @samp{~Y-~m-~dT~H:~M:~S}
  2379. @end multitable
  2380. @end defun
  2381. Conversions @samp{~D}, @samp{~x} and @samp{~X} are not currently
  2382. described here, since the specification and reference implementation
  2383. differ.
  2384. Conversion is locale-dependent on systems that support it
  2385. (@pxref{Accessing Locale Information}). @xref{Locales,
  2386. @code{setlocale}}, for information on how to change the current
  2387. locale.
  2388. @node SRFI-19 String to date
  2389. @subsubsection SRFI-19 String to date
  2390. @cindex string to date
  2391. @cindex date, from string
  2392. @c FIXME: Can we say what happens when an incomplete date is
  2393. @c converted? I.e. fields left as 0, or what? The spec seems to be
  2394. @c silent on this.
  2395. @defun string->date input template
  2396. Convert an @var{input} string to a date under the control of a
  2397. @var{template} string. Return a newly created date object.
  2398. Literal characters in @var{template} must match characters in
  2399. @var{input} and @samp{~} escapes must match the input forms described
  2400. in the table below. ``Skip to'' means characters up to one of the
  2401. given type are ignored, or ``no skip'' for no skipping. ``Read'' is
  2402. what's then read, and ``Set'' is the field affected in the date
  2403. object.
  2404. For example @samp{~Y} skips input characters until a digit is reached,
  2405. at which point it expects a year and stores that to the year field of
  2406. the date.
  2407. @multitable {MMMM} {@nicode{char-alphabetic?}} {MMMMMMMMMMMMMMMMMMMMMMMMM} {@nicode{date-zone-offset}}
  2408. @item
  2409. @tab Skip to
  2410. @tab Read
  2411. @tab Set
  2412. @item @nicode{~~}
  2413. @tab no skip
  2414. @tab literal ~
  2415. @tab nothing
  2416. @item @nicode{~a}
  2417. @tab @nicode{char-alphabetic?}
  2418. @tab locale abbreviated weekday name
  2419. @tab nothing
  2420. @item @nicode{~A}
  2421. @tab @nicode{char-alphabetic?}
  2422. @tab locale full weekday name
  2423. @tab nothing
  2424. @c Note that the SRFI spec says that ~b and ~B don't set anything,
  2425. @c but that looks like a mistake. The reference implementation sets
  2426. @c the month field, which seems sensible and is what we describe
  2427. @c here.
  2428. @item @nicode{~b}
  2429. @tab @nicode{char-alphabetic?}
  2430. @tab locale abbreviated month name
  2431. @tab @nicode{date-month}
  2432. @item @nicode{~B}
  2433. @tab @nicode{char-alphabetic?}
  2434. @tab locale full month name
  2435. @tab @nicode{date-month}
  2436. @item @nicode{~d}
  2437. @tab @nicode{char-numeric?}
  2438. @tab day of month
  2439. @tab @nicode{date-day}
  2440. @item @nicode{~e}
  2441. @tab no skip
  2442. @tab day of month, blank padded
  2443. @tab @nicode{date-day}
  2444. @item @nicode{~h}
  2445. @tab same as @samp{~b}
  2446. @item @nicode{~H}
  2447. @tab @nicode{char-numeric?}
  2448. @tab hour
  2449. @tab @nicode{date-hour}
  2450. @item @nicode{~k}
  2451. @tab no skip
  2452. @tab hour, blank padded
  2453. @tab @nicode{date-hour}
  2454. @item @nicode{~m}
  2455. @tab @nicode{char-numeric?}
  2456. @tab month
  2457. @tab @nicode{date-month}
  2458. @item @nicode{~M}
  2459. @tab @nicode{char-numeric?}
  2460. @tab minute
  2461. @tab @nicode{date-minute}
  2462. @item @nicode{~N}
  2463. @tab @nicode{char-numeric?}
  2464. @tab nanosecond
  2465. @tab @nicode{date-nanosecond}
  2466. @item @nicode{~S}
  2467. @tab @nicode{char-numeric?}
  2468. @tab second
  2469. @tab @nicode{date-second}
  2470. @item @nicode{~y}
  2471. @tab no skip
  2472. @tab 2-digit year
  2473. @tab @nicode{date-year} within 50 years
  2474. @item @nicode{~Y}
  2475. @tab @nicode{char-numeric?}
  2476. @tab year
  2477. @tab @nicode{date-year}
  2478. @item @nicode{~z}
  2479. @tab no skip
  2480. @tab time zone
  2481. @tab date-zone-offset
  2482. @end multitable
  2483. Notice that the weekday matching forms don't affect the date object
  2484. returned, instead the weekday will be derived from the day, month and
  2485. year.
  2486. Conversion is locale-dependent on systems that support it
  2487. (@pxref{Accessing Locale Information}). @xref{Locales,
  2488. @code{setlocale}}, for information on how to change the current
  2489. locale.
  2490. @end defun
  2491. @node SRFI-23
  2492. @subsection SRFI-23 - Error Reporting
  2493. @cindex SRFI-23
  2494. The SRFI-23 @code{error} procedure is always available.
  2495. @node SRFI-26
  2496. @subsection SRFI-26 - specializing parameters
  2497. @cindex SRFI-26
  2498. @cindex parameter specialize
  2499. @cindex argument specialize
  2500. @cindex specialize parameter
  2501. This SRFI provides a syntax for conveniently specializing selected
  2502. parameters of a function. It can be used with,
  2503. @example
  2504. (use-modules (srfi srfi-26))
  2505. @end example
  2506. @deffn {library syntax} cut slot1 slot2 @dots{}
  2507. @deffnx {library syntax} cute slot1 slot2 @dots{}
  2508. Return a new procedure which will make a call (@var{slot1} @var{slot2}
  2509. @dots{}) but with selected parameters specialized to given expressions.
  2510. An example will illustrate the idea. The following is a
  2511. specialization of @code{write}, sending output to
  2512. @code{my-output-port},
  2513. @example
  2514. (cut write <> my-output-port)
  2515. @result{}
  2516. (lambda (obj) (write obj my-output-port))
  2517. @end example
  2518. The special symbol @code{<>} indicates a slot to be filled by an
  2519. argument to the new procedure. @code{my-output-port} on the other
  2520. hand is an expression to be evaluated and passed, ie.@: it specializes
  2521. the behaviour of @code{write}.
  2522. @table @nicode
  2523. @item <>
  2524. A slot to be filled by an argument from the created procedure.
  2525. Arguments are assigned to @code{<>} slots in the order they appear in
  2526. the @code{cut} form, there's no way to re-arrange arguments.
  2527. The first argument to @code{cut} is usually a procedure (or expression
  2528. giving a procedure), but @code{<>} is allowed there too. For example,
  2529. @example
  2530. (cut <> 1 2 3)
  2531. @result{}
  2532. (lambda (proc) (proc 1 2 3))
  2533. @end example
  2534. @item <...>
  2535. A slot to be filled by all remaining arguments from the new procedure.
  2536. This can only occur at the end of a @code{cut} form.
  2537. For example, a procedure taking a variable number of arguments like
  2538. @code{max} but in addition enforcing a lower bound,
  2539. @example
  2540. (define my-lower-bound 123)
  2541. (cut max my-lower-bound <...>)
  2542. @result{}
  2543. (lambda arglist (apply max my-lower-bound arglist))
  2544. @end example
  2545. @end table
  2546. For @code{cut} the specializing expressions are evaluated each time
  2547. the new procedure is called. For @code{cute} they're evaluated just
  2548. once, when the new procedure is created. The name @code{cute} stands
  2549. for ``@code{cut} with evaluated arguments''. In all cases the
  2550. evaluations take place in an unspecified order.
  2551. The following illustrates the difference between @code{cut} and
  2552. @code{cute},
  2553. @example
  2554. (cut format <> "the time is ~s" (current-time))
  2555. @result{}
  2556. (lambda (port) (format port "the time is ~s" (current-time)))
  2557. (cute format <> "the time is ~s" (current-time))
  2558. @result{}
  2559. (let ((val (current-time)))
  2560. (lambda (port) (format port "the time is ~s" val))
  2561. @end example
  2562. (There's no provision for a mixture of @code{cut} and @code{cute}
  2563. where some expressions would be evaluated every time but others
  2564. evaluated only once.)
  2565. @code{cut} is really just a shorthand for the sort of @code{lambda}
  2566. forms shown in the above examples. But notice @code{cut} avoids the
  2567. need to name unspecialized parameters, and is more compact. Use in
  2568. functional programming style or just with @code{map}, @code{for-each}
  2569. or similar is typical.
  2570. @example
  2571. (map (cut * 2 <>) '(1 2 3 4))
  2572. (for-each (cut write <> my-port) my-list)
  2573. @end example
  2574. @end deffn
  2575. @node SRFI-27
  2576. @subsection SRFI-27 - Sources of Random Bits
  2577. @cindex SRFI-27
  2578. This subsection is based on the
  2579. @uref{http://srfi.schemers.org/srfi-27/srfi-27.html, specification of
  2580. SRFI-27} written by Sebastian Egner.
  2581. @c The copyright notice and license text of the SRFI-27 specification is
  2582. @c reproduced below:
  2583. @c Copyright (C) Sebastian Egner (2002). All Rights Reserved.
  2584. @c Permission is hereby granted, free of charge, to any person obtaining a
  2585. @c copy of this software and associated documentation files (the
  2586. @c "Software"), to deal in the Software without restriction, including
  2587. @c without limitation the rights to use, copy, modify, merge, publish,
  2588. @c distribute, sublicense, and/or sell copies of the Software, and to
  2589. @c permit persons to whom the Software is furnished to do so, subject to
  2590. @c the following conditions:
  2591. @c The above copyright notice and this permission notice shall be included
  2592. @c in all copies or substantial portions of the Software.
  2593. @c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2594. @c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2595. @c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  2596. @c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  2597. @c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  2598. @c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  2599. @c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  2600. This SRFI provides access to a (pseudo) random number generator; for
  2601. Guile's built-in random number facilities, which SRFI-27 is implemented
  2602. upon, @xref{Random}. With SRFI-27, random numbers are obtained from a
  2603. @emph{random source}, which encapsulates a random number generation
  2604. algorithm and its state.
  2605. @menu
  2606. * SRFI-27 Default Random Source:: Obtaining random numbers
  2607. * SRFI-27 Random Sources:: Creating and manipulating random sources
  2608. * SRFI-27 Random Number Generators:: Obtaining random number generators
  2609. @end menu
  2610. @node SRFI-27 Default Random Source
  2611. @subsubsection The Default Random Source
  2612. @cindex SRFI-27
  2613. @defun random-integer n
  2614. Return a random number between zero (inclusive) and @var{n} (exclusive),
  2615. using the default random source. The numbers returned have a uniform
  2616. distribution.
  2617. @end defun
  2618. @defun random-real
  2619. Return a random number in (0,1), using the default random source. The
  2620. numbers returned have a uniform distribution.
  2621. @end defun
  2622. @defun default-random-source
  2623. A random source from which @code{random-integer} and @code{random-real}
  2624. have been derived using @code{random-source-make-integers} and
  2625. @code{random-source-make-reals} (@pxref{SRFI-27 Random Number Generators}
  2626. for those procedures). Note that an assignment to
  2627. @code{default-random-source} does not change @code{random-integer} or
  2628. @code{random-real}; it is also strongly recommended not to assign a new
  2629. value.
  2630. @end defun
  2631. @node SRFI-27 Random Sources
  2632. @subsubsection Random Sources
  2633. @cindex SRFI-27
  2634. @defun make-random-source
  2635. Create a new random source. The stream of random numbers obtained from
  2636. each random source created by this procedure will be identical, unless
  2637. its state is changed by one of the procedures below.
  2638. @end defun
  2639. @defun random-source? object
  2640. Tests whether @var{object} is a random source. Random sources are a
  2641. disjoint type.
  2642. @end defun
  2643. @defun random-source-randomize! source
  2644. Attempt to set the state of the random source to a truly random value.
  2645. The current implementation uses a seed based on the current system time.
  2646. @end defun
  2647. @defun random-source-pseudo-randomize! source i j
  2648. Changes the state of the random source s into the initial state of the
  2649. (@var{i}, @var{j})-th independent random source, where @var{i} and
  2650. @var{j} are non-negative integers. This procedure provides a mechanism
  2651. to obtain a large number of independent random sources (usually all
  2652. derived from the same backbone generator), indexed by two integers. In
  2653. contrast to @code{random-source-randomize!}, this procedure is entirely
  2654. deterministic.
  2655. @end defun
  2656. The state associated with a random state can be obtained an reinstated
  2657. with the following procedures:
  2658. @defun random-source-state-ref source
  2659. @defunx random-source-state-set! source state
  2660. Get and set the state of a random source. No assumptions should be made
  2661. about the nature of the state object, besides it having an external
  2662. representation (i.e.@: it can be passed to @code{write} and subsequently
  2663. @code{read} back).
  2664. @end defun
  2665. @node SRFI-27 Random Number Generators
  2666. @subsubsection Obtaining random number generator procedures
  2667. @cindex SRFI-27
  2668. @defun random-source-make-integers source
  2669. Obtains a procedure to generate random integers using the random source
  2670. @var{source}. The returned procedure takes a single argument @var{n},
  2671. which must be a positive integer, and returns the next uniformly
  2672. distributed random integer from the interval @{0, ..., @var{n}-1@} by
  2673. advancing the state of @var{source}.
  2674. If an application obtains and uses several generators for the same
  2675. random source @var{source}, a call to any of these generators advances
  2676. the state of @var{source}. Hence, the generators do not produce the
  2677. same sequence of random integers each but rather share a state. This
  2678. also holds for all other types of generators derived from a fixed random
  2679. sources.
  2680. While the SRFI text specifies that ``Implementations that support
  2681. concurrency make sure that the state of a generator is properly
  2682. advanced'', this is currently not the case in Guile's implementation of
  2683. SRFI-27, as it would cause a severe performance penalty. So in
  2684. multi-threaded programs, you either must perform locking on random
  2685. sources shared between threads yourself, or use different random sources
  2686. for multiple threads.
  2687. @end defun
  2688. @defun random-source-make-reals source
  2689. @defunx random-source-make-reals source unit
  2690. Obtains a procedure to generate random real numbers @math{0 < x < 1}
  2691. using the random source @var{source}. The procedure rand is called
  2692. without arguments.
  2693. The optional parameter @var{unit} determines the type of numbers being
  2694. produced by the returned procedure and the quantization of the output.
  2695. @var{unit} must be a number such that @math{0 < @var{unit} < 1}. The
  2696. numbers created by the returned procedure are of the same numerical type
  2697. as @var{unit} and the potential output values are spaced by at most
  2698. @var{unit}. One can imagine rand to create numbers as @var{x} *
  2699. @var{unit} where @var{x} is a random integer in @{1, ...,
  2700. floor(1/unit)-1@}. Note, however, that this need not be the way the
  2701. values are actually created and that the actual resolution of rand can
  2702. be much higher than unit. In case @var{unit} is absent it defaults to a
  2703. reasonably small value (related to the width of the mantissa of an
  2704. efficient number format).
  2705. @end defun
  2706. @node SRFI-28
  2707. @subsection SRFI-28 - Basic Format Strings
  2708. @cindex SRFI-28
  2709. SRFI-28 provides a basic @code{format} procedure that provides only
  2710. the @code{~a}, @code{~s}, @code{~%}, and @code{~~} format specifiers.
  2711. You can import this procedure by using:
  2712. @lisp
  2713. (use-modules (srfi srfi-28))
  2714. @end lisp
  2715. @deffn {Scheme Procedure} format message arg @dots{}
  2716. Returns a formatted message, using @var{message} as the format string,
  2717. which can contain the following format specifiers:
  2718. @table @code
  2719. @item ~a
  2720. Insert the textual representation of the next @var{arg}, as if printed
  2721. by @code{display}.
  2722. @item ~s
  2723. Insert the textual representation of the next @var{arg}, as if printed
  2724. by @code{write}.
  2725. @item ~%
  2726. Insert a newline.
  2727. @item ~~
  2728. Insert a tilde.
  2729. @end table
  2730. This procedure is the same as calling @code{simple-format}
  2731. (@pxref{Simple Output}) with @code{#f} as the destination.
  2732. @end deffn
  2733. @node SRFI-30
  2734. @subsection SRFI-30 - Nested Multi-line Comments
  2735. @cindex SRFI-30
  2736. Starting from version 2.0, Guile's @code{read} supports SRFI-30/R6RS
  2737. nested multi-line comments by default, @ref{Block Comments}.
  2738. @node SRFI-31
  2739. @subsection SRFI-31 - A special form `rec' for recursive evaluation
  2740. @cindex SRFI-31
  2741. @cindex recursive expression
  2742. @findex rec
  2743. SRFI-31 defines a special form that can be used to create
  2744. self-referential expressions more conveniently. The syntax is as
  2745. follows:
  2746. @example
  2747. @group
  2748. <rec expression> --> (rec <variable> <expression>)
  2749. <rec expression> --> (rec (<variable>+) <body>)
  2750. @end group
  2751. @end example
  2752. The first syntax can be used to create self-referential expressions,
  2753. for example:
  2754. @lisp
  2755. guile> (define tmp (rec ones (cons 1 (delay ones))))
  2756. @end lisp
  2757. The second syntax can be used to create anonymous recursive functions:
  2758. @lisp
  2759. guile> (define tmp (rec (display-n item n)
  2760. (if (positive? n)
  2761. (begin (display n) (display-n (- n 1))))))
  2762. guile> (tmp 42 3)
  2763. 424242
  2764. guile>
  2765. @end lisp
  2766. @node SRFI-34
  2767. @subsection SRFI-34 - Exception handling for programs
  2768. @cindex SRFI-34
  2769. Guile provides an implementation of
  2770. @uref{http://srfi.schemers.org/srfi-34/srfi-34.html, SRFI-34's exception
  2771. handling mechanisms} as an alternative to its own built-in mechanisms
  2772. (@pxref{Exceptions}). It can be made available as follows:
  2773. @lisp
  2774. (use-modules (srfi srfi-34))
  2775. @end lisp
  2776. @xref{Raising and Handling Exceptions}, for more on
  2777. @code{with-exception-handler} and @code{raise} (known as
  2778. @code{raise-exception} in core Guile).
  2779. SRFI-34's @code{guard} form is syntactic sugar over
  2780. @code{with-exception-handler}:
  2781. @deffn {Syntax} guard (var clause @dots{}) body @dots{}
  2782. Evaluate @var{body} with an exception handler that binds the raised
  2783. object to @var{var} and within the scope of that binding evaluates
  2784. @var{clause}@dots{} as if they were the clauses of a cond expression.
  2785. That implicit cond expression is evaluated with the continuation and
  2786. dynamic environment of the guard expression.
  2787. If every @var{clause}'s test evaluates to false and there is no
  2788. @code{else} clause, then @code{raise} is re-invoked on the raised object
  2789. within the dynamic environment of the original call to @code{raise}
  2790. except that the current exception handler is that of the @code{guard}
  2791. expression.
  2792. @end deffn
  2793. @node SRFI-35
  2794. @subsection SRFI-35 - Conditions
  2795. @cindex SRFI-35
  2796. @cindex conditions
  2797. @cindex exceptions
  2798. @uref{http://srfi.schemers.org/srfi-35/srfi-35.html, SRFI-35} defines
  2799. @dfn{conditions}, a data structure akin to records designed to convey
  2800. information about exceptional conditions between parts of a program. It
  2801. is normally used in conjunction with SRFI-34's @code{raise}:
  2802. @lisp
  2803. (raise (condition (&message
  2804. (message "An error occurred"))))
  2805. @end lisp
  2806. Users can define @dfn{condition types} containing arbitrary information.
  2807. Condition types may inherit from one another. This allows the part of
  2808. the program that handles (or ``catches'') conditions to get accurate
  2809. information about the exceptional condition that arose.
  2810. SRFI-35 conditions are made available using:
  2811. @lisp
  2812. (use-modules (srfi srfi-35))
  2813. @end lisp
  2814. The procedures available to manipulate condition types are the
  2815. following:
  2816. @deffn {Scheme Procedure} make-condition-type id parent field-names
  2817. Return a new condition type named @var{id}, inheriting from
  2818. @var{parent}, and with the fields whose names are listed in
  2819. @var{field-names}. @var{field-names} must be a list of symbols and must
  2820. not contain names already used by @var{parent} or one of its supertypes.
  2821. @end deffn
  2822. @deffn {Scheme Procedure} condition-type? obj
  2823. Return true if @var{obj} is a condition type.
  2824. @end deffn
  2825. Conditions can be created and accessed with the following procedures:
  2826. @deffn {Scheme Procedure} make-condition type . field+value
  2827. Return a new condition of type @var{type} with fields initialized as
  2828. specified by @var{field+value}, a sequence of field names (symbols) and
  2829. values as in the following example:
  2830. @lisp
  2831. (let ((&ct (make-condition-type 'foo &condition '(a b c))))
  2832. (make-condition &ct 'a 1 'b 2 'c 3))
  2833. @end lisp
  2834. Note that all fields of @var{type} and its supertypes must be specified.
  2835. @end deffn
  2836. @deffn {Scheme Procedure} make-compound-condition condition1 condition2 @dots{}
  2837. Return a new compound condition composed of @var{condition1}
  2838. @var{condition2} @enddots{}. The returned condition has the type of
  2839. each condition of condition1 condition2 @dots{} (per
  2840. @code{condition-has-type?}).
  2841. @end deffn
  2842. @deffn {Scheme Procedure} condition-has-type? c type
  2843. Return true if condition @var{c} has type @var{type}.
  2844. @end deffn
  2845. @deffn {Scheme Procedure} condition-ref c field-name
  2846. Return the value of the field named @var{field-name} from condition @var{c}.
  2847. If @var{c} is a compound condition and several underlying condition
  2848. types contain a field named @var{field-name}, then the value of the
  2849. first such field is returned, using the order in which conditions were
  2850. passed to @code{make-compound-condition}.
  2851. @end deffn
  2852. @deffn {Scheme Procedure} extract-condition c type
  2853. Return a condition of condition type @var{type} with the field values
  2854. specified by @var{c}.
  2855. If @var{c} is a compound condition, extract the field values from the
  2856. subcondition belonging to @var{type} that appeared first in the call to
  2857. @code{make-compound-condition} that created the condition.
  2858. @end deffn
  2859. Convenience macros are also available to create condition types and
  2860. conditions.
  2861. @deffn {library syntax} define-condition-type type supertype predicate field-spec...
  2862. Define a new condition type named @var{type} that inherits from
  2863. @var{supertype}. In addition, bind @var{predicate} to a type predicate
  2864. that returns true when passed a condition of type @var{type} or any of
  2865. its subtypes. @var{field-spec} must have the form @code{(field
  2866. accessor)} where @var{field} is the name of field of @var{type} and
  2867. @var{accessor} is the name of a procedure to access field @var{field} in
  2868. conditions of type @var{type}.
  2869. The example below defines condition type @code{&foo}, inheriting from
  2870. @code{&condition} with fields @code{a}, @code{b} and @code{c}:
  2871. @lisp
  2872. (define-condition-type &foo &condition
  2873. foo-condition?
  2874. (a foo-a)
  2875. (b foo-b)
  2876. (c foo-c))
  2877. @end lisp
  2878. @end deffn
  2879. @deffn {library syntax} condition type-field-binding1 type-field-binding2 @dots{}
  2880. Return a new condition or compound condition, initialized according to
  2881. @var{type-field-binding1} @var{type-field-binding2} @enddots{}. Each
  2882. @var{type-field-binding} must have the form @code{(type
  2883. field-specs...)}, where @var{type} is the name of a variable bound to a
  2884. condition type; each @var{field-spec} must have the form
  2885. @code{(field-name value)} where @var{field-name} is a symbol denoting
  2886. the field being initialized to @var{value}. As for
  2887. @code{make-condition}, all fields must be specified.
  2888. The following example returns a simple condition:
  2889. @lisp
  2890. (condition (&message (message "An error occurred")))
  2891. @end lisp
  2892. The one below returns a compound condition:
  2893. @lisp
  2894. (condition (&message (message "An error occurred"))
  2895. (&serious))
  2896. @end lisp
  2897. @end deffn
  2898. Finally, SRFI-35 defines a several standard condition types.
  2899. @defvar &condition
  2900. This condition type is the root of all condition types. It has no
  2901. fields.
  2902. @end defvar
  2903. @defvar &message
  2904. A condition type that carries a message describing the nature of the
  2905. condition to humans.
  2906. @end defvar
  2907. @deffn {Scheme Procedure} message-condition? c
  2908. Return true if @var{c} is of type @code{&message} or one of its
  2909. subtypes.
  2910. @end deffn
  2911. @deffn {Scheme Procedure} condition-message c
  2912. Return the message associated with message condition @var{c}.
  2913. @end deffn
  2914. @defvar &serious
  2915. This type describes conditions serious enough that they cannot safely be
  2916. ignored. It has no fields.
  2917. @end defvar
  2918. @deffn {Scheme Procedure} serious-condition? c
  2919. Return true if @var{c} is of type @code{&serious} or one of its
  2920. subtypes.
  2921. @end deffn
  2922. @defvar &error
  2923. This condition describes errors, typically caused by something that has
  2924. gone wrong in the interaction of the program with the external world or
  2925. the user.
  2926. @end defvar
  2927. @deffn {Scheme Procedure} error? c
  2928. Return true if @var{c} is of type @code{&error} or one of its subtypes.
  2929. @end deffn
  2930. As an implementation note, condition objects in Guile are the same as
  2931. ``exception objects''. @xref{Exception Objects}. The
  2932. @code{&condition}, @code{&serious}, and @code{&error} condition types
  2933. are known in core Guile as @code{&exception}, @code{&error}, and
  2934. @code{&external-error}, respectively.
  2935. @node SRFI-37
  2936. @subsection SRFI-37 - args-fold
  2937. @cindex SRFI-37
  2938. This is a processor for GNU @code{getopt_long}-style program
  2939. arguments. It provides an alternative, less declarative interface
  2940. than @code{getopt-long} in @code{(ice-9 getopt-long)}
  2941. (@pxref{getopt-long,,The (ice-9 getopt-long) Module}). Unlike
  2942. @code{getopt-long}, it supports repeated options and any number of
  2943. short and long names per option. Access it with:
  2944. @lisp
  2945. (use-modules (srfi srfi-37))
  2946. @end lisp
  2947. @acronym{SRFI}-37 principally provides an @code{option} type and the
  2948. @code{args-fold} function. To use the library, create a set of
  2949. options with @code{option} and use it as a specification for invoking
  2950. @code{args-fold}.
  2951. Here is an example of a simple argument processor for the typical
  2952. @samp{--version} and @samp{--help} options, which returns a backwards
  2953. list of files given on the command line:
  2954. @lisp
  2955. (args-fold (cdr (program-arguments))
  2956. (let ((display-and-exit-proc
  2957. (lambda (msg)
  2958. (lambda (opt name arg loads)
  2959. (display msg) (quit)))))
  2960. (list (option '(#\v "version") #f #f
  2961. (display-and-exit-proc "Foo version 42.0\n"))
  2962. (option '(#\h "help") #f #f
  2963. (display-and-exit-proc
  2964. "Usage: foo scheme-file ..."))))
  2965. (lambda (opt name arg loads)
  2966. (error "Unrecognized option `~A'" name))
  2967. (lambda (op loads) (cons op loads))
  2968. '())
  2969. @end lisp
  2970. @deffn {Scheme Procedure} option names required-arg? optional-arg? processor
  2971. Return an object that specifies a single kind of program option.
  2972. @var{names} is a list of command-line option names, and should consist of
  2973. characters for traditional @code{getopt} short options and strings for
  2974. @code{getopt_long}-style long options.
  2975. @var{required-arg?} and @var{optional-arg?} are mutually exclusive;
  2976. one or both must be @code{#f}. If @var{required-arg?}, the option
  2977. must be followed by an argument on the command line, such as
  2978. @samp{--opt=value} for long options, or an error will be signaled.
  2979. If @var{optional-arg?}, an argument will be taken if available.
  2980. @var{processor} is a procedure that takes at least 3 arguments, called
  2981. when @code{args-fold} encounters the option: the containing option
  2982. object, the name used on the command line, and the argument given for
  2983. the option (or @code{#f} if none). The rest of the arguments are
  2984. @code{args-fold} ``seeds'', and the @var{processor} should return
  2985. seeds as well.
  2986. @end deffn
  2987. @deffn {Scheme Procedure} option-names opt
  2988. @deffnx {Scheme Procedure} option-required-arg? opt
  2989. @deffnx {Scheme Procedure} option-optional-arg? opt
  2990. @deffnx {Scheme Procedure} option-processor opt
  2991. Return the specified field of @var{opt}, an option object, as
  2992. described above for @code{option}.
  2993. @end deffn
  2994. @deffn {Scheme Procedure} args-fold args options unrecognized-option-proc operand-proc seed @dots{}
  2995. Process @var{args}, a list of program arguments such as that returned by
  2996. @code{(cdr (program-arguments))}, in order against @var{options}, a list
  2997. of option objects as described above. All functions called take the
  2998. ``seeds'', or the last multiple-values as multiple arguments, starting
  2999. with @var{seed} @dots{}, and must return the new seeds. Return the
  3000. final seeds.
  3001. Call @code{unrecognized-option-proc}, which is like an option object's
  3002. processor, for any options not found in @var{options}.
  3003. Call @code{operand-proc} with any items on the command line that are
  3004. not named options. This includes arguments after @samp{--}. It is
  3005. called with the argument in question, as well as the seeds.
  3006. @end deffn
  3007. @node SRFI-38
  3008. @subsection SRFI-38 - External Representation for Data With Shared Structure
  3009. @cindex SRFI-38
  3010. This subsection is based on
  3011. @uref{http://srfi.schemers.org/srfi-38/srfi-38.html, the specification
  3012. of SRFI-38} written by Ray Dillinger.
  3013. @c Copyright (C) Ray Dillinger 2003. All Rights Reserved.
  3014. @c Permission is hereby granted, free of charge, to any person obtaining a
  3015. @c copy of this software and associated documentation files (the
  3016. @c "Software"), to deal in the Software without restriction, including
  3017. @c without limitation the rights to use, copy, modify, merge, publish,
  3018. @c distribute, sublicense, and/or sell copies of the Software, and to
  3019. @c permit persons to whom the Software is furnished to do so, subject to
  3020. @c the following conditions:
  3021. @c The above copyright notice and this permission notice shall be included
  3022. @c in all copies or substantial portions of the Software.
  3023. @c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3024. @c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3025. @c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  3026. @c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  3027. @c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  3028. @c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  3029. @c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  3030. This SRFI creates an alternative external representation for data
  3031. written and read using @code{write-with-shared-structure} and
  3032. @code{read-with-shared-structure}. It is identical to the grammar for
  3033. external representation for data written and read with @code{write} and
  3034. @code{read} given in section 7 of R5RS, except that the single
  3035. production
  3036. @example
  3037. <datum> --> <simple datum> | <compound datum>
  3038. @end example
  3039. is replaced by the following five productions:
  3040. @example
  3041. <datum> --> <defining datum> | <nondefining datum> | <defined datum>
  3042. <defining datum> --> #<indexnum>=<nondefining datum>
  3043. <defined datum> --> #<indexnum>#
  3044. <nondefining datum> --> <simple datum> | <compound datum>
  3045. <indexnum> --> <digit 10>+
  3046. @end example
  3047. @deffn {Scheme procedure} write-with-shared-structure obj
  3048. @deffnx {Scheme procedure} write-with-shared-structure obj port
  3049. @deffnx {Scheme procedure} write-with-shared-structure obj port optarg
  3050. Writes an external representation of @var{obj} to the given port.
  3051. Strings that appear in the written representation are enclosed in
  3052. doublequotes, and within those strings backslash and doublequote
  3053. characters are escaped by backslashes. Character objects are written
  3054. using the @code{#\} notation.
  3055. Objects which denote locations rather than values (cons cells, vectors,
  3056. and non-zero-length strings in R5RS scheme; also Guile's structs,
  3057. bytevectors and ports and hash-tables), if they appear at more than one
  3058. point in the data being written, are preceded by @samp{#@var{N}=} the
  3059. first time they are written and replaced by @samp{#@var{N}#} all
  3060. subsequent times they are written, where @var{N} is a natural number
  3061. used to identify that particular object. If objects which denote
  3062. locations occur only once in the structure, then
  3063. @code{write-with-shared-structure} must produce the same external
  3064. representation for those objects as @code{write}.
  3065. @code{write-with-shared-structure} terminates in finite time and
  3066. produces a finite representation when writing finite data.
  3067. @code{write-with-shared-structure} returns an unspecified value. The
  3068. @var{port} argument may be omitted, in which case it defaults to the
  3069. value returned by @code{(current-output-port)}. The @var{optarg}
  3070. argument may also be omitted. If present, its effects on the output and
  3071. return value are unspecified but @code{write-with-shared-structure} must
  3072. still write a representation that can be read by
  3073. @code{read-with-shared-structure}. Some implementations may wish to use
  3074. @var{optarg} to specify formatting conventions, numeric radixes, or
  3075. return values. Guile's implementation ignores @var{optarg}.
  3076. For example, the code
  3077. @lisp
  3078. (begin (define a (cons 'val1 'val2))
  3079. (set-cdr! a a)
  3080. (write-with-shared-structure a))
  3081. @end lisp
  3082. should produce the output @code{#1=(val1 . #1#)}. This shows a cons
  3083. cell whose @code{cdr} contains itself.
  3084. @end deffn
  3085. @deffn {Scheme procedure} read-with-shared-structure
  3086. @deffnx {Scheme procedure} read-with-shared-structure port
  3087. @code{read-with-shared-structure} converts the external representations
  3088. of Scheme objects produced by @code{write-with-shared-structure} into
  3089. Scheme objects. That is, it is a parser for the nonterminal
  3090. @samp{<datum>} in the augmented external representation grammar defined
  3091. above. @code{read-with-shared-structure} returns the next object
  3092. parsable from the given input port, updating @var{port} to point to the
  3093. first character past the end of the external representation of the
  3094. object.
  3095. If an end-of-file is encountered in the input before any characters are
  3096. found that can begin an object, then an end-of-file object is returned.
  3097. The port remains open, and further attempts to read it (by
  3098. @code{read-with-shared-structure} or @code{read} will also return an
  3099. end-of-file object. If an end of file is encountered after the
  3100. beginning of an object's external representation, but the external
  3101. representation is incomplete and therefore not parsable, an error is
  3102. signaled.
  3103. The @var{port} argument may be omitted, in which case it defaults to the
  3104. value returned by @code{(current-input-port)}. It is an error to read
  3105. from a closed port.
  3106. @end deffn
  3107. @node SRFI-39
  3108. @subsection SRFI-39 - Parameters
  3109. @cindex SRFI-39
  3110. This SRFI adds support for dynamically-scoped parameters. SRFI 39 is
  3111. implemented in the Guile core; there's no module needed to get SRFI-39
  3112. itself. Parameters are documented in @ref{Parameters}.
  3113. This module does export one extra function: @code{with-parameters*}.
  3114. This is a Guile-specific addition to the SRFI, similar to the core
  3115. @code{with-fluids*} (@pxref{Fluids and Dynamic States}).
  3116. @defun with-parameters* param-list value-list thunk
  3117. Establish a new dynamic scope, as per @code{parameterize} above,
  3118. taking parameters from @var{param-list} and corresponding values from
  3119. @var{value-list}. A call @code{(@var{thunk})} is made in the new
  3120. scope and the result from that @var{thunk} is the return from
  3121. @code{with-parameters*}.
  3122. @end defun
  3123. @node SRFI-41
  3124. @subsection SRFI-41 - Streams
  3125. @cindex SRFI-41
  3126. This subsection is based on the
  3127. @uref{http://srfi.schemers.org/srfi-41/srfi-41.html, specification of
  3128. SRFI-41} by Philip L.@: Bewig.
  3129. @c The copyright notice and license text of the SRFI-41 specification is
  3130. @c reproduced below:
  3131. @c Copyright (C) Philip L. Bewig (2007). All Rights Reserved.
  3132. @c Permission is hereby granted, free of charge, to any person obtaining a
  3133. @c copy of this software and associated documentation files (the
  3134. @c "Software"), to deal in the Software without restriction, including
  3135. @c without limitation the rights to use, copy, modify, merge, publish,
  3136. @c distribute, sublicense, and/or sell copies of the Software, and to
  3137. @c permit persons to whom the Software is furnished to do so, subject to
  3138. @c the following conditions:
  3139. @c The above copyright notice and this permission notice shall be included
  3140. @c in all copies or substantial portions of the Software.
  3141. @c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3142. @c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3143. @c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  3144. @c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  3145. @c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  3146. @c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  3147. @c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  3148. @noindent
  3149. This SRFI implements streams, sometimes called lazy lists, a sequential
  3150. data structure containing elements computed only on demand. A stream is
  3151. either null or is a pair with a stream in its cdr. Since elements of a
  3152. stream are computed only when accessed, streams can be infinite. Once
  3153. computed, the value of a stream element is cached in case it is needed
  3154. again. SRFI-41 can be made available with:
  3155. @example
  3156. (use-modules (srfi srfi-41))
  3157. @end example
  3158. @menu
  3159. * SRFI-41 Stream Fundamentals::
  3160. * SRFI-41 Stream Primitives::
  3161. * SRFI-41 Stream Library::
  3162. @end menu
  3163. @node SRFI-41 Stream Fundamentals
  3164. @subsubsection SRFI-41 Stream Fundamentals
  3165. SRFI-41 Streams are based on two mutually-recursive abstract data types:
  3166. An object of the @code{stream} abstract data type is a promise that,
  3167. when forced, is either @code{stream-null} or is an object of type
  3168. @code{stream-pair}. An object of the @code{stream-pair} abstract data
  3169. type contains a @code{stream-car} and a @code{stream-cdr}, which must be
  3170. a @code{stream}. The essential feature of streams is the systematic
  3171. suspensions of the recursive promises between the two data types.
  3172. The object stored in the @code{stream-car} of a @code{stream-pair} is a
  3173. promise that is forced the first time the @code{stream-car} is accessed;
  3174. its value is cached in case it is needed again. The object may have any
  3175. type, and different stream elements may have different types. If the
  3176. @code{stream-car} is never accessed, the object stored there is never
  3177. evaluated. Likewise, the @code{stream-cdr} is a promise to return a
  3178. stream, and is only forced on demand.
  3179. @node SRFI-41 Stream Primitives
  3180. @subsubsection SRFI-41 Stream Primitives
  3181. This library provides eight operators: constructors for
  3182. @code{stream-null} and @code{stream-pair}s, type predicates for streams
  3183. and the two kinds of streams, accessors for both fields of a
  3184. @code{stream-pair}, and a lambda that creates procedures that return
  3185. streams.
  3186. @defvr {Scheme Variable} stream-null
  3187. A promise that, when forced, is a single object, distinguishable from
  3188. all other objects, that represents the null stream. @code{stream-null}
  3189. is immutable and unique.
  3190. @end defvr
  3191. @deffn {Scheme Syntax} stream-cons object-expr stream-expr
  3192. Creates a newly-allocated stream containing a promise that, when forced,
  3193. is a @code{stream-pair} with @var{object-expr} in its @code{stream-car}
  3194. and @var{stream-expr} in its @code{stream-cdr}. Neither
  3195. @var{object-expr} nor @var{stream-expr} is evaluated when
  3196. @code{stream-cons} is called.
  3197. Once created, a @code{stream-pair} is immutable; there is no
  3198. @code{stream-set-car!} or @code{stream-set-cdr!} that modifies an
  3199. existing stream-pair. There is no dotted-pair or improper stream as
  3200. with lists.
  3201. @end deffn
  3202. @deffn {Scheme Procedure} stream? object
  3203. Returns true if @var{object} is a stream, otherwise returns false. If
  3204. @var{object} is a stream, its promise will not be forced. If
  3205. @code{(stream? obj)} returns true, then one of @code{(stream-null? obj)}
  3206. or @code{(stream-pair? obj)} will return true and the other will return
  3207. false.
  3208. @end deffn
  3209. @deffn {Scheme Procedure} stream-null? object
  3210. Returns true if @var{object} is the distinguished null stream, otherwise
  3211. returns false. If @var{object} is a stream, its promise will be forced.
  3212. @end deffn
  3213. @deffn {Scheme Procedure} stream-pair? object
  3214. Returns true if @var{object} is a @code{stream-pair} constructed by
  3215. @code{stream-cons}, otherwise returns false. If @var{object} is a
  3216. stream, its promise will be forced.
  3217. @end deffn
  3218. @deffn {Scheme Procedure} stream-car stream
  3219. Returns the object stored in the @code{stream-car} of @var{stream}. An
  3220. error is signaled if the argument is not a @code{stream-pair}. This
  3221. causes the @var{object-expr} passed to @code{stream-cons} to be
  3222. evaluated if it had not yet been; the value is cached in case it is
  3223. needed again.
  3224. @end deffn
  3225. @deffn {Scheme Procedure} stream-cdr stream
  3226. Returns the stream stored in the @code{stream-cdr} of @var{stream}. An
  3227. error is signaled if the argument is not a @code{stream-pair}.
  3228. @end deffn
  3229. @deffn {Scheme Syntax} stream-lambda formals body @dots{}
  3230. Creates a procedure that returns a promise to evaluate the @var{body} of
  3231. the procedure. The last @var{body} expression to be evaluated must
  3232. yield a stream. As with normal @code{lambda}, @var{formals} may be a
  3233. single variable name, in which case all the formal arguments are
  3234. collected into a single list, or a list of variable names, which may be
  3235. null if there are no arguments, proper if there are an exact number of
  3236. arguments, or dotted if a fixed number of arguments is to be followed by
  3237. zero or more arguments collected into a list. @var{Body} must contain
  3238. at least one expression, and may contain internal definitions preceding
  3239. any expressions to be evaluated.
  3240. @end deffn
  3241. @example
  3242. (define strm123
  3243. (stream-cons 1
  3244. (stream-cons 2
  3245. (stream-cons 3
  3246. stream-null))))
  3247. (stream-car strm123) @result{} 1
  3248. (stream-car (stream-cdr strm123) @result{} 2
  3249. (stream-pair?
  3250. (stream-cdr
  3251. (stream-cons (/ 1 0) stream-null))) @result{} #f
  3252. (stream? (list 1 2 3)) @result{} #f
  3253. (define iter
  3254. (stream-lambda (f x)
  3255. (stream-cons x (iter f (f x)))))
  3256. (define nats (iter (lambda (x) (+ x 1)) 0))
  3257. (stream-car (stream-cdr nats)) @result{} 1
  3258. (define stream-add
  3259. (stream-lambda (s1 s2)
  3260. (stream-cons
  3261. (+ (stream-car s1) (stream-car s2))
  3262. (stream-add (stream-cdr s1)
  3263. (stream-cdr s2)))))
  3264. (define evens (stream-add nats nats))
  3265. (stream-car evens) @result{} 0
  3266. (stream-car (stream-cdr evens)) @result{} 2
  3267. (stream-car (stream-cdr (stream-cdr evens))) @result{} 4
  3268. @end example
  3269. @node SRFI-41 Stream Library
  3270. @subsubsection SRFI-41 Stream Library
  3271. @deffn {Scheme Syntax} define-stream (name args @dots{}) body @dots{}
  3272. Creates a procedure that returns a stream, and may appear anywhere a
  3273. normal @code{define} may appear, including as an internal definition.
  3274. It may contain internal definitions of its own. The defined procedure
  3275. takes arguments in the same way as @code{stream-lambda}.
  3276. @code{define-stream} is syntactic sugar on @code{stream-lambda}; see
  3277. also @code{stream-let}, which is also a sugaring of
  3278. @code{stream-lambda}.
  3279. A simple version of @code{stream-map} that takes only a single input
  3280. stream calls itself recursively:
  3281. @example
  3282. (define-stream (stream-map proc strm)
  3283. (if (stream-null? strm)
  3284. stream-null
  3285. (stream-cons
  3286. (proc (stream-car strm))
  3287. (stream-map proc (stream-cdr strm))))))
  3288. @end example
  3289. @end deffn
  3290. @deffn {Scheme Procedure} list->stream list
  3291. Returns a newly-allocated stream containing the elements from
  3292. @var{list}.
  3293. @end deffn
  3294. @deffn {Scheme Procedure} port->stream [port]
  3295. Returns a newly-allocated stream containing in its elements the
  3296. characters on the port. If @var{port} is not given it defaults to the
  3297. current input port. The returned stream has finite length and is
  3298. terminated by @code{stream-null}.
  3299. It looks like one use of @code{port->stream} would be this:
  3300. @example
  3301. (define s ;wrong!
  3302. (with-input-from-file filename
  3303. (lambda () (port->stream))))
  3304. @end example
  3305. But that fails, because @code{with-input-from-file} is eager, and closes
  3306. the input port prematurely, before the first character is read. To read
  3307. a file into a stream, say:
  3308. @example
  3309. (define-stream (file->stream filename)
  3310. (let ((p (open-input-file filename)))
  3311. (stream-let loop ((c (read-char p)))
  3312. (if (eof-object? c)
  3313. (begin (close-input-port p)
  3314. stream-null)
  3315. (stream-cons c
  3316. (loop (read-char p)))))))
  3317. @end example
  3318. @end deffn
  3319. @deffn {Scheme Syntax} stream object-expr @dots{}
  3320. Creates a newly-allocated stream containing in its elements the objects,
  3321. in order. The @var{object-expr}s are evaluated when they are accessed,
  3322. not when the stream is created. If no objects are given, as in
  3323. (stream), the null stream is returned. See also @code{list->stream}.
  3324. @example
  3325. (define strm123 (stream 1 2 3))
  3326. ; (/ 1 0) not evaluated when stream is created
  3327. (define s (stream 1 (/ 1 0) -1))
  3328. @end example
  3329. @end deffn
  3330. @deffn {Scheme Procedure} stream->list [n] stream
  3331. Returns a newly-allocated list containing in its elements the first
  3332. @var{n} items in @var{stream}. If @var{stream} has less than @var{n}
  3333. items, all the items in the stream will be included in the returned
  3334. list. If @var{n} is not given it defaults to infinity, which means that
  3335. unless @var{stream} is finite @code{stream->list} will never return.
  3336. @example
  3337. (stream->list 10
  3338. (stream-map (lambda (x) (* x x))
  3339. (stream-from 0)))
  3340. @result{} (0 1 4 9 16 25 36 49 64 81)
  3341. @end example
  3342. @end deffn
  3343. @deffn {Scheme Procedure} stream-append stream @dots{}
  3344. Returns a newly-allocated stream containing in its elements those
  3345. elements contained in its input @var{stream}s, in order of input. If
  3346. any of the input streams is infinite, no elements of any of the
  3347. succeeding input streams will appear in the output stream. See also
  3348. @code{stream-concat}.
  3349. @end deffn
  3350. @deffn {Scheme Procedure} stream-concat stream
  3351. Takes a @var{stream} consisting of one or more streams and returns a
  3352. newly-allocated stream containing all the elements of the input streams.
  3353. If any of the streams in the input @var{stream} is infinite, any
  3354. remaining streams in the input stream will never appear in the output
  3355. stream. See also @code{stream-append}.
  3356. @end deffn
  3357. @deffn {Scheme Procedure} stream-constant object @dots{}
  3358. Returns a newly-allocated stream containing in its elements the
  3359. @var{object}s, repeating in succession forever.
  3360. @example
  3361. (stream-constant 1) @result{} 1 1 1 @dots{}
  3362. (stream-constant #t #f) @result{} #t #f #t #f #t #f @dots{}
  3363. @end example
  3364. @end deffn
  3365. @deffn {Scheme Procedure} stream-drop n stream
  3366. Returns the suffix of the input @var{stream} that starts at the next
  3367. element after the first @var{n} elements. The output stream shares
  3368. structure with the input @var{stream}; thus, promises forced in one
  3369. instance of the stream are also forced in the other instance of the
  3370. stream. If the input @var{stream} has less than @var{n} elements,
  3371. @code{stream-drop} returns the null stream. See also
  3372. @code{stream-take}.
  3373. @end deffn
  3374. @deffn {Scheme Procedure} stream-drop-while pred stream
  3375. Returns the suffix of the input @var{stream} that starts at the first
  3376. element @var{x} for which @code{(pred x)} returns false. The output
  3377. stream shares structure with the input @var{stream}. See also
  3378. @code{stream-take-while}.
  3379. @end deffn
  3380. @deffn {Scheme Procedure} stream-filter pred stream
  3381. Returns a newly-allocated stream that contains only those elements
  3382. @var{x} of the input @var{stream} which satisfy the predicate
  3383. @code{pred}.
  3384. @example
  3385. (stream-filter odd? (stream-from 0))
  3386. @result{} 1 3 5 7 9 @dots{}
  3387. @end example
  3388. @end deffn
  3389. @deffn {Scheme Procedure} stream-fold proc base stream
  3390. Applies a binary procedure @var{proc} to @var{base} and the first
  3391. element of @var{stream} to compute a new @var{base}, then applies the
  3392. procedure to the new @var{base} and the next element of @var{stream} to
  3393. compute a succeeding @var{base}, and so on, accumulating a value that is
  3394. finally returned as the value of @code{stream-fold} when the end of the
  3395. stream is reached. @var{stream} must be finite, or @code{stream-fold}
  3396. will enter an infinite loop. See also @code{stream-scan}, which is
  3397. similar to @code{stream-fold}, but useful for infinite streams. For
  3398. readers familiar with other functional languages, this is a left-fold;
  3399. there is no corresponding right-fold, since right-fold relies on finite
  3400. streams that are fully-evaluated, in which case they may as well be
  3401. converted to a list.
  3402. @end deffn
  3403. @deffn {Scheme Procedure} stream-for-each proc stream @dots{}
  3404. Applies @var{proc} element-wise to corresponding elements of the input
  3405. @var{stream}s for side-effects; it returns nothing.
  3406. @code{stream-for-each} stops as soon as any of its input streams is
  3407. exhausted.
  3408. @end deffn
  3409. @deffn {Scheme Procedure} stream-from first [step]
  3410. Creates a newly-allocated stream that contains @var{first} as its first
  3411. element and increments each succeeding element by @var{step}. If
  3412. @var{step} is not given it defaults to 1. @var{first} and @var{step}
  3413. may be of any numeric type. @code{stream-from} is frequently useful as
  3414. a generator in @code{stream-of} expressions. See also
  3415. @code{stream-range} for a similar procedure that creates finite streams.
  3416. @end deffn
  3417. @deffn {Scheme Procedure} stream-iterate proc base
  3418. Creates a newly-allocated stream containing @var{base} in its first
  3419. element and applies @var{proc} to each element in turn to determine the
  3420. succeeding element. See also @code{stream-unfold} and
  3421. @code{stream-unfolds}.
  3422. @end deffn
  3423. @deffn {Scheme Procedure} stream-length stream
  3424. Returns the number of elements in the @var{stream}; it does not evaluate
  3425. its elements. @code{stream-length} may only be used on finite streams;
  3426. it enters an infinite loop with infinite streams.
  3427. @end deffn
  3428. @deffn {Scheme Syntax} stream-let tag ((var expr) @dots{}) body @dots{}
  3429. Creates a local scope that binds each variable to the value of its
  3430. corresponding expression. It additionally binds @var{tag} to a
  3431. procedure which takes the bound variables as arguments and @var{body} as
  3432. its defining expressions, binding the @var{tag} with
  3433. @code{stream-lambda}. @var{tag} is in scope within body, and may be
  3434. called recursively. When the expanded expression defined by the
  3435. @code{stream-let} is evaluated, @code{stream-let} evaluates the
  3436. expressions in its @var{body} in an environment containing the
  3437. newly-bound variables, returning the value of the last expression
  3438. evaluated, which must yield a stream.
  3439. @code{stream-let} provides syntactic sugar on @code{stream-lambda}, in
  3440. the same manner as normal @code{let} provides syntactic sugar on normal
  3441. @code{lambda}. However, unlike normal @code{let}, the @var{tag} is
  3442. required, not optional, because unnamed @code{stream-let} is
  3443. meaningless.
  3444. For example, @code{stream-member} returns the first @code{stream-pair}
  3445. of the input @var{strm} with a @code{stream-car} @var{x} that satisfies
  3446. @code{(eql? obj x)}, or the null stream if @var{x} is not present in
  3447. @var{strm}.
  3448. @example
  3449. (define-stream (stream-member eql? obj strm)
  3450. (stream-let loop ((strm strm))
  3451. (cond ((stream-null? strm) strm)
  3452. ((eql? obj (stream-car strm)) strm)
  3453. (else (loop (stream-cdr strm))))))
  3454. @end example
  3455. @end deffn
  3456. @deffn {Scheme Procedure} stream-map proc stream @dots{}
  3457. Applies @var{proc} element-wise to corresponding elements of the input
  3458. @var{stream}s, returning a newly-allocated stream containing elements
  3459. that are the results of those procedure applications. The output stream
  3460. has as many elements as the minimum-length input stream, and may be
  3461. infinite.
  3462. @end deffn
  3463. @deffn {Scheme Syntax} stream-match stream clause @dots{}
  3464. Provides pattern-matching for streams. The input @var{stream} is an
  3465. expression that evaluates to a stream. Clauses are of the form
  3466. @code{(pattern [fender] expression)}, consisting of a @var{pattern} that
  3467. matches a stream of a particular shape, an optional @var{fender} that
  3468. must succeed if the pattern is to match, and an @var{expression} that is
  3469. evaluated if the pattern matches. There are four types of patterns:
  3470. @itemize @bullet
  3471. @item
  3472. () matches the null stream.
  3473. @item
  3474. (@var{pat0} @var{pat1} @dots{}) matches a finite stream with length
  3475. exactly equal to the number of pattern elements.
  3476. @item
  3477. (@var{pat0} @var{pat1} @dots{} @code{.} @var{pat-rest}) matches an
  3478. infinite stream, or a finite stream with length at least as great as the
  3479. number of pattern elements before the literal dot.
  3480. @item
  3481. @var{pat} matches an entire stream. Should always appear last in the
  3482. list of clauses; it's not an error to appear elsewhere, but subsequent
  3483. clauses could never match.
  3484. @end itemize
  3485. Each pattern element may be either:
  3486. @itemize @bullet
  3487. @item
  3488. An identifier, which matches any stream element. Additionally, the
  3489. value of the stream element is bound to the variable named by the
  3490. identifier, which is in scope in the @var{fender} and @var{expression}
  3491. of the corresponding @var{clause}. Each identifier in a single pattern
  3492. must be unique.
  3493. @item
  3494. A literal underscore (@code{_}), which matches any stream element but
  3495. creates no bindings.
  3496. @end itemize
  3497. The @var{pattern}s are tested in order, left-to-right, until a matching
  3498. pattern is found; if @var{fender} is present, it must evaluate to a true
  3499. value for the match to be successful. Pattern variables are bound in
  3500. the corresponding @var{fender} and @var{expression}. Once the matching
  3501. @var{pattern} is found, the corresponding @var{expression} is evaluated
  3502. and returned as the result of the match. An error is signaled if no
  3503. pattern matches the input @var{stream}.
  3504. @code{stream-match} is often used to distinguish null streams from
  3505. non-null streams, binding @var{head} and @var{tail}:
  3506. @example
  3507. (define (len strm)
  3508. (stream-match strm
  3509. (() 0)
  3510. ((head . tail) (+ 1 (len tail)))))
  3511. @end example
  3512. Fenders can test the common case where two stream elements must be
  3513. identical; the @code{else} pattern is an identifier bound to the entire
  3514. stream, not a keyword as in @code{cond}.
  3515. @example
  3516. (stream-match strm
  3517. ((x y . _) (equal? x y) 'ok)
  3518. (else 'error))
  3519. @end example
  3520. A more complex example uses two nested matchers to match two different
  3521. stream arguments; @code{(stream-merge lt? . strms)} stably merges two or
  3522. more streams ordered by the @code{lt?} predicate:
  3523. @example
  3524. (define-stream (stream-merge lt? . strms)
  3525. (define-stream (merge xx yy)
  3526. (stream-match xx (() yy) ((x . xs)
  3527. (stream-match yy (() xx) ((y . ys)
  3528. (if (lt? y x)
  3529. (stream-cons y (merge xx ys))
  3530. (stream-cons x (merge xs yy))))))))
  3531. (stream-let loop ((strms strms))
  3532. (cond ((null? strms) stream-null)
  3533. ((null? (cdr strms)) (car strms))
  3534. (else (merge (car strms)
  3535. (apply stream-merge lt?
  3536. (cdr strms)))))))
  3537. @end example
  3538. @end deffn
  3539. @deffn {Scheme Syntax} stream-of expr clause @dots{}
  3540. Provides the syntax of stream comprehensions, which generate streams by
  3541. means of looping expressions. The result is a stream of objects of the
  3542. type returned by @var{expr}. There are four types of clauses:
  3543. @itemize @bullet
  3544. @item
  3545. (@var{var} @code{in} @var{stream-expr}) loops over the elements of
  3546. @var{stream-expr}, in order from the start of the stream, binding each
  3547. element of the stream in turn to @var{var}. @code{stream-from} and
  3548. @code{stream-range} are frequently useful as generators for
  3549. @var{stream-expr}.
  3550. @item
  3551. (@var{var} @code{is} @var{expr}) binds @var{var} to the value obtained
  3552. by evaluating @var{expr}.
  3553. @item
  3554. (@var{pred} @var{expr}) includes in the output stream only those
  3555. elements @var{x} which satisfy the predicate @var{pred}.
  3556. @end itemize
  3557. The scope of variables bound in the stream comprehension is the clauses
  3558. to the right of the binding clause (but not the binding clause itself)
  3559. plus the result expression.
  3560. When two or more generators are present, the loops are processed as if
  3561. they are nested from left to right; that is, the rightmost generator
  3562. varies fastest. A consequence of this is that only the first generator
  3563. may be infinite and all subsequent generators must be finite. If no
  3564. generators are present, the result of a stream comprehension is a stream
  3565. containing the result expression; thus, @samp{(stream-of 1)} produces a
  3566. finite stream containing only the element 1.
  3567. @example
  3568. (stream-of (* x x)
  3569. (x in (stream-range 0 10))
  3570. (even? x))
  3571. @result{} 0 4 16 36 64
  3572. (stream-of (list a b)
  3573. (a in (stream-range 1 4))
  3574. (b in (stream-range 1 3)))
  3575. @result{} (1 1) (1 2) (2 1) (2 2) (3 1) (3 2)
  3576. (stream-of (list i j)
  3577. (i in (stream-range 1 5))
  3578. (j in (stream-range (+ i 1) 5)))
  3579. @result{} (1 2) (1 3) (1 4) (2 3) (2 4) (3 4)
  3580. @end example
  3581. @end deffn
  3582. @deffn {Scheme Procedure} stream-range first past [step]
  3583. Creates a newly-allocated stream that contains @var{first} as its first
  3584. element and increments each succeeding element by @var{step}. The
  3585. stream is finite and ends before @var{past}, which is not an element of
  3586. the stream. If @var{step} is not given it defaults to 1 if @var{first}
  3587. is less than past and -1 otherwise. @var{first}, @var{past} and
  3588. @var{step} may be of any real numeric type. @code{stream-range} is
  3589. frequently useful as a generator in @code{stream-of} expressions. See
  3590. also @code{stream-from} for a similar procedure that creates infinite
  3591. streams.
  3592. @example
  3593. (stream-range 0 10) @result{} 0 1 2 3 4 5 6 7 8 9
  3594. (stream-range 0 10 2) @result{} 0 2 4 6 8
  3595. @end example
  3596. Successive elements of the stream are calculated by adding @var{step} to
  3597. @var{first}, so if any of @var{first}, @var{past} or @var{step} are
  3598. inexact, the length of the output stream may differ from
  3599. @code{(ceiling (- (/ (- past first) step) 1)}.
  3600. @end deffn
  3601. @deffn {Scheme Procedure} stream-ref stream n
  3602. Returns the @var{n}th element of stream, counting from zero. An error
  3603. is signaled if @var{n} is greater than or equal to the length of stream.
  3604. @example
  3605. (define (fact n)
  3606. (stream-ref
  3607. (stream-scan * 1 (stream-from 1))
  3608. n))
  3609. @end example
  3610. @end deffn
  3611. @deffn {Scheme Procedure} stream-reverse stream
  3612. Returns a newly-allocated stream containing the elements of the input
  3613. @var{stream} but in reverse order. @code{stream-reverse} may only be
  3614. used with finite streams; it enters an infinite loop with infinite
  3615. streams. @code{stream-reverse} does not force evaluation of the
  3616. elements of the stream.
  3617. @end deffn
  3618. @deffn {Scheme Procedure} stream-scan proc base stream
  3619. Accumulates the partial folds of an input @var{stream} into a
  3620. newly-allocated output stream. The output stream is the @var{base}
  3621. followed by @code{(stream-fold proc base (stream-take i stream))} for
  3622. each of the first @var{i} elements of @var{stream}.
  3623. @example
  3624. (stream-scan + 0 (stream-from 1))
  3625. @result{} (stream 0 1 3 6 10 15 @dots{})
  3626. (stream-scan * 1 (stream-from 1))
  3627. @result{} (stream 1 1 2 6 24 120 @dots{})
  3628. @end example
  3629. @end deffn
  3630. @deffn {Scheme Procedure} stream-take n stream
  3631. Returns a newly-allocated stream containing the first @var{n} elements
  3632. of the input @var{stream}. If the input @var{stream} has less than
  3633. @var{n} elements, so does the output stream. See also
  3634. @code{stream-drop}.
  3635. @end deffn
  3636. @deffn {Scheme Procedure} stream-take-while pred stream
  3637. Takes a predicate and a @code{stream} and returns a newly-allocated
  3638. stream containing those elements @code{x} that form the maximal prefix
  3639. of the input stream which satisfy @var{pred}. See also
  3640. @code{stream-drop-while}.
  3641. @end deffn
  3642. @deffn {Scheme Procedure} stream-unfold map pred gen base
  3643. The fundamental recursive stream constructor. It constructs a stream by
  3644. repeatedly applying @var{gen} to successive values of @var{base}, in the
  3645. manner of @code{stream-iterate}, then applying @var{map} to each of the
  3646. values so generated, appending each of the mapped values to the output
  3647. stream as long as @code{(pred? base)} returns a true value. See also
  3648. @code{stream-iterate} and @code{stream-unfolds}.
  3649. The expression below creates the finite stream @samp{0 1 4 9 16 25 36 49
  3650. 64 81}. Initially the @var{base} is 0, which is less than 10, so
  3651. @var{map} squares the @var{base} and the mapped value becomes the first
  3652. element of the output stream. Then @var{gen} increments the @var{base}
  3653. by 1, so it becomes 1; this is less than 10, so @var{map} squares the
  3654. new @var{base} and 1 becomes the second element of the output stream.
  3655. And so on, until the base becomes 10, when @var{pred} stops the
  3656. recursion and stream-null ends the output stream.
  3657. @example
  3658. (stream-unfold
  3659. (lambda (x) (expt x 2)) ; map
  3660. (lambda (x) (< x 10)) ; pred?
  3661. (lambda (x) (+ x 1)) ; gen
  3662. 0) ; base
  3663. @end example
  3664. @end deffn
  3665. @deffn {Scheme Procedure} stream-unfolds proc seed
  3666. Returns @var{n} newly-allocated streams containing those elements
  3667. produced by successive calls to the generator @var{proc}, which takes
  3668. the current @var{seed} as its argument and returns @var{n}+1 values
  3669. (@var{proc} @var{seed}) @result{} @var{seed} @var{result_0} @dots{} @var{result_n-1}
  3670. where the returned @var{seed} is the input @var{seed} to the next call
  3671. to the generator and @var{result_i} indicates how to produce the next
  3672. element of the @var{i}th result stream:
  3673. @itemize @bullet
  3674. @item
  3675. (@var{value}): @var{value} is the next car of the result stream.
  3676. @item
  3677. @code{#f}: no value produced by this iteration of the generator
  3678. @var{proc} for the result stream.
  3679. @item
  3680. (): the end of the result stream.
  3681. @end itemize
  3682. It may require multiple calls of @var{proc} to produce the next element
  3683. of any particular result stream. See also @code{stream-iterate} and
  3684. @code{stream-unfold}.
  3685. @example
  3686. (define (stream-partition pred? strm)
  3687. (stream-unfolds
  3688. (lambda (s)
  3689. (if (stream-null? s)
  3690. (values s '() '())
  3691. (let ((a (stream-car s))
  3692. (d (stream-cdr s)))
  3693. (if (pred? a)
  3694. (values d (list a) #f)
  3695. (values d #f (list a))))))
  3696. strm))
  3697. (call-with-values
  3698. (lambda ()
  3699. (stream-partition odd?
  3700. (stream-range 1 6)))
  3701. (lambda (odds evens)
  3702. (list (stream->list odds)
  3703. (stream->list evens))))
  3704. @result{} ((1 3 5) (2 4))
  3705. @end example
  3706. @end deffn
  3707. @deffn {Scheme Procedure} stream-zip stream @dots{}
  3708. Returns a newly-allocated stream in which each element is a list (not a
  3709. stream) of the corresponding elements of the input @var{stream}s. The
  3710. output stream is as long as the shortest input @var{stream}, if any of
  3711. the input @var{stream}s is finite, or is infinite if all the input
  3712. @var{stream}s are infinite.
  3713. @end deffn
  3714. @node SRFI-42
  3715. @subsection SRFI-42 - Eager Comprehensions
  3716. @cindex SRFI-42
  3717. See @uref{http://srfi.schemers.org/srfi-42/srfi-42.html, the
  3718. specification of SRFI-42}.
  3719. @node SRFI-43
  3720. @subsection SRFI-43 - Vector Library
  3721. @cindex SRFI-43
  3722. This subsection is based on the
  3723. @uref{http://srfi.schemers.org/srfi-43/srfi-43.html, specification of
  3724. SRFI-43} by Taylor Campbell.
  3725. @c The copyright notice and license text of the SRFI-43 specification is
  3726. @c reproduced below:
  3727. @c Copyright (C) Taylor Campbell (2003). All Rights Reserved.
  3728. @c Permission is hereby granted, free of charge, to any person obtaining a
  3729. @c copy of this software and associated documentation files (the
  3730. @c "Software"), to deal in the Software without restriction, including
  3731. @c without limitation the rights to use, copy, modify, merge, publish,
  3732. @c distribute, sublicense, and/or sell copies of the Software, and to
  3733. @c permit persons to whom the Software is furnished to do so, subject to
  3734. @c the following conditions:
  3735. @c The above copyright notice and this permission notice shall be included
  3736. @c in all copies or substantial portions of the Software.
  3737. @c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3738. @c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3739. @c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  3740. @c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  3741. @c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  3742. @c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  3743. @c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  3744. @noindent
  3745. SRFI-43 implements a comprehensive library of vector operations. It can
  3746. be made available with:
  3747. @example
  3748. (use-modules (srfi srfi-43))
  3749. @end example
  3750. @menu
  3751. * SRFI-43 Constructors::
  3752. * SRFI-43 Predicates::
  3753. * SRFI-43 Selectors::
  3754. * SRFI-43 Iteration::
  3755. * SRFI-43 Searching::
  3756. * SRFI-43 Mutators::
  3757. * SRFI-43 Conversion::
  3758. @end menu
  3759. @node SRFI-43 Constructors
  3760. @subsubsection SRFI-43 Constructors
  3761. @deffn {Scheme Procedure} make-vector size [fill]
  3762. Create and return a vector of size @var{size}, optionally filling it
  3763. with @var{fill}. The default value of @var{fill} is unspecified.
  3764. @example
  3765. (make-vector 5 3) @result{} #(3 3 3 3 3)
  3766. @end example
  3767. @end deffn
  3768. @deffn {Scheme Procedure} vector x @dots{}
  3769. Create and return a vector whose elements are @var{x} @enddots{}.
  3770. @example
  3771. (vector 0 1 2 3 4) @result{} #(0 1 2 3 4)
  3772. @end example
  3773. @end deffn
  3774. @deffn {Scheme Procedure} vector-unfold f length initial-seed @dots{}
  3775. The fundamental vector constructor. Create a vector whose length
  3776. is @var{length} and iterates across each index k from 0 up to
  3777. @var{length} - 1, applying @var{f} at each iteration to the current
  3778. index and current seeds, in that order, to receive n + 1 values: the
  3779. element to put in the kth slot of the new vector, and n new seeds for
  3780. the next iteration. It is an error for the number of seeds to vary
  3781. between iterations.
  3782. @example
  3783. (vector-unfold (lambda (i x) (values x (- x 1)))
  3784. 10 0)
  3785. @result{} #(0 -1 -2 -3 -4 -5 -6 -7 -8 -9)
  3786. (vector-unfold values 10)
  3787. @result{} #(0 1 2 3 4 5 6 7 8 9)
  3788. @end example
  3789. @end deffn
  3790. @deffn {Scheme Procedure} vector-unfold-right f length initial-seed @dots{}
  3791. Like @code{vector-unfold}, but it uses @var{f} to generate elements from
  3792. right-to-left, rather than left-to-right.
  3793. @example
  3794. (vector-unfold-right (lambda (i x) (values x (+ x 1)))
  3795. 10 0)
  3796. @result{} #(9 8 7 6 5 4 3 2 1 0)
  3797. @end example
  3798. @end deffn
  3799. @deffn {Scheme Procedure} vector-copy vec [start [end [fill]]]
  3800. Allocate a new vector whose length is @var{end} - @var{start} and fills
  3801. it with elements from @var{vec}, taking elements from @var{vec} starting
  3802. at index @var{start} and stopping at index @var{end}. @var{start}
  3803. defaults to 0 and @var{end} defaults to the value of
  3804. @code{(vector-length vec)}. If @var{end} extends beyond the length of
  3805. @var{vec}, the slots in the new vector that obviously cannot be filled
  3806. by elements from @var{vec} are filled with @var{fill}, whose default
  3807. value is unspecified.
  3808. @example
  3809. (vector-copy '#(a b c d e f g h i))
  3810. @result{} #(a b c d e f g h i)
  3811. (vector-copy '#(a b c d e f g h i) 6)
  3812. @result{} #(g h i)
  3813. (vector-copy '#(a b c d e f g h i) 3 6)
  3814. @result{} #(d e f)
  3815. (vector-copy '#(a b c d e f g h i) 6 12 'x)
  3816. @result{} #(g h i x x x)
  3817. @end example
  3818. @end deffn
  3819. @deffn {Scheme Procedure} vector-reverse-copy vec [start [end]]
  3820. Like @code{vector-copy}, but it copies the elements in the reverse order
  3821. from @var{vec}.
  3822. @example
  3823. (vector-reverse-copy '#(5 4 3 2 1 0) 1 5)
  3824. @result{} #(1 2 3 4)
  3825. @end example
  3826. @end deffn
  3827. @deffn {Scheme Procedure} vector-append vec @dots{}
  3828. Return a newly allocated vector that contains all elements in order from
  3829. the subsequent locations in @var{vec} @enddots{}.
  3830. @example
  3831. (vector-append '#(a) '#(b c d))
  3832. @result{} #(a b c d)
  3833. @end example
  3834. @end deffn
  3835. @deffn {Scheme Procedure} vector-concatenate list-of-vectors
  3836. Append each vector in @var{list-of-vectors}. Equivalent to
  3837. @code{(apply vector-append list-of-vectors)}.
  3838. @example
  3839. (vector-concatenate '(#(a b) #(c d)))
  3840. @result{} #(a b c d)
  3841. @end example
  3842. @end deffn
  3843. @node SRFI-43 Predicates
  3844. @subsubsection SRFI-43 Predicates
  3845. @deffn {Scheme Procedure} vector? obj
  3846. Return true if @var{obj} is a vector, else return false.
  3847. @end deffn
  3848. @deffn {Scheme Procedure} vector-empty? vec
  3849. Return true if @var{vec} is empty, i.e. its length is 0, else return
  3850. false.
  3851. @end deffn
  3852. @deffn {Scheme Procedure} vector= elt=? vec @dots{}
  3853. Return true if the vectors @var{vec} @dots{} have equal lengths and
  3854. equal elements according to @var{elt=?}. @var{elt=?} is always applied
  3855. to two arguments. Element comparison must be consistent with @code{eq?}
  3856. in the following sense: if @code{(eq? a b)} returns true, then
  3857. @code{(elt=? a b)} must also return true. The order in which
  3858. comparisons are performed is unspecified.
  3859. @end deffn
  3860. @node SRFI-43 Selectors
  3861. @subsubsection SRFI-43 Selectors
  3862. @deffn {Scheme Procedure} vector-ref vec i
  3863. Return the element at index @var{i} in @var{vec}. Indexing is based on
  3864. zero.
  3865. @end deffn
  3866. @deffn {Scheme Procedure} vector-length vec
  3867. Return the length of @var{vec}.
  3868. @end deffn
  3869. @node SRFI-43 Iteration
  3870. @subsubsection SRFI-43 Iteration
  3871. @deffn {Scheme Procedure} vector-fold kons knil vec1 vec2 @dots{}
  3872. The fundamental vector iterator. @var{kons} is iterated over each index
  3873. in all of the vectors, stopping at the end of the shortest; @var{kons}
  3874. is applied as
  3875. @smalllisp
  3876. (kons i state (vector-ref vec1 i) (vector-ref vec2 i) ...)
  3877. @end smalllisp
  3878. where @var{state} is the current state value, and @var{i} is the current
  3879. index. The current state value begins with @var{knil}, and becomes
  3880. whatever @var{kons} returned at the respective iteration. The iteration
  3881. is strictly left-to-right.
  3882. @end deffn
  3883. @deffn {Scheme Procedure} vector-fold-right kons knil vec1 vec2 @dots{}
  3884. Similar to @code{vector-fold}, but it iterates right-to-left instead of
  3885. left-to-right.
  3886. @end deffn
  3887. @deffn {Scheme Procedure} vector-map f vec1 vec2 @dots{}
  3888. Return a new vector of the shortest size of the vector arguments. Each
  3889. element at index i of the new vector is mapped from the old vectors by
  3890. @smalllisp
  3891. (f i (vector-ref vec1 i) (vector-ref vec2 i) ...)
  3892. @end smalllisp
  3893. The dynamic order of application of @var{f} is unspecified.
  3894. @end deffn
  3895. @deffn {Scheme Procedure} vector-map! f vec1 vec2 @dots{}
  3896. Similar to @code{vector-map}, but rather than mapping the new elements
  3897. into a new vector, the new mapped elements are destructively inserted
  3898. into @var{vec1}. The dynamic order of application of @var{f} is
  3899. unspecified.
  3900. @end deffn
  3901. @deffn {Scheme Procedure} vector-for-each f vec1 vec2 @dots{}
  3902. Call @code{(f i (vector-ref vec1 i) (vector-ref vec2 i) ...)} for each
  3903. index i less than the length of the shortest vector passed. The
  3904. iteration is strictly left-to-right.
  3905. @end deffn
  3906. @deffn {Scheme Procedure} vector-count pred? vec1 vec2 @dots{}
  3907. Count the number of parallel elements in the vectors that satisfy
  3908. @var{pred?}, which is applied, for each index i less than the length of
  3909. the smallest vector, to i and each parallel element in the vectors at
  3910. that index, in order.
  3911. @example
  3912. (vector-count (lambda (i elt) (even? elt))
  3913. '#(3 1 4 1 5 9 2 5 6))
  3914. @result{} 3
  3915. (vector-count (lambda (i x y) (< x y))
  3916. '#(1 3 6 9) '#(2 4 6 8 10 12))
  3917. @result{} 2
  3918. @end example
  3919. @end deffn
  3920. @node SRFI-43 Searching
  3921. @subsubsection SRFI-43 Searching
  3922. @deffn {Scheme Procedure} vector-index pred? vec1 vec2 @dots{}
  3923. Find and return the index of the first elements in @var{vec1} @var{vec2}
  3924. @dots{} that satisfy @var{pred?}. If no matching element is found by
  3925. the end of the shortest vector, return @code{#f}.
  3926. @example
  3927. (vector-index even? '#(3 1 4 1 5 9))
  3928. @result{} 2
  3929. (vector-index < '#(3 1 4 1 5 9 2 5 6) '#(2 7 1 8 2))
  3930. @result{} 1
  3931. (vector-index = '#(3 1 4 1 5 9 2 5 6) '#(2 7 1 8 2))
  3932. @result{} #f
  3933. @end example
  3934. @end deffn
  3935. @deffn {Scheme Procedure} vector-index-right pred? vec1 vec2 @dots{}
  3936. Like @code{vector-index}, but it searches right-to-left, rather than
  3937. left-to-right. Note that the SRFI 43 specification requires that all
  3938. the vectors must have the same length, but both the SRFI 43 reference
  3939. implementation and Guile's implementation allow vectors with unequal
  3940. lengths, and start searching from the last index of the shortest vector.
  3941. @end deffn
  3942. @deffn {Scheme Procedure} vector-skip pred? vec1 vec2 @dots{}
  3943. Find and return the index of the first elements in @var{vec1} @var{vec2}
  3944. @dots{} that do not satisfy @var{pred?}. If no matching element is
  3945. found by the end of the shortest vector, return @code{#f}. Equivalent
  3946. to @code{vector-index} but with the predicate inverted.
  3947. @example
  3948. (vector-skip number? '#(1 2 a b 3 4 c d)) @result{} 2
  3949. @end example
  3950. @end deffn
  3951. @deffn {Scheme Procedure} vector-skip-right pred? vec1 vec2 @dots{}
  3952. Like @code{vector-skip}, but it searches for a non-matching element
  3953. right-to-left, rather than left-to-right. Note that the SRFI 43
  3954. specification requires that all the vectors must have the same length,
  3955. but both the SRFI 43 reference implementation and Guile's implementation
  3956. allow vectors with unequal lengths, and start searching from the last
  3957. index of the shortest vector.
  3958. @end deffn
  3959. @deffn {Scheme Procedure} vector-binary-search vec value cmp [start [end]]
  3960. Find and return an index of @var{vec} between @var{start} and @var{end}
  3961. whose value is @var{value} using a binary search. If no matching
  3962. element is found, return @code{#f}. The default @var{start} is 0 and
  3963. the default @var{end} is the length of @var{vec}.
  3964. @var{cmp} must be a procedure of two arguments such that @code{(cmp a
  3965. b)} returns a negative integer if @math{a < b}, a positive integer if
  3966. @math{a > b}, or zero if @math{a = b}. The elements of @var{vec} must
  3967. be sorted in non-decreasing order according to @var{cmp}.
  3968. Note that SRFI 43 does not document the @var{start} and @var{end}
  3969. arguments, but both its reference implementation and Guile's
  3970. implementation support them.
  3971. @example
  3972. (define (char-cmp c1 c2)
  3973. (cond ((char<? c1 c2) -1)
  3974. ((char>? c1 c2) 1)
  3975. (else 0)))
  3976. (vector-binary-search '#(#\a #\b #\c #\d #\e #\f #\g #\h)
  3977. #\g
  3978. char-cmp)
  3979. @result{} 6
  3980. @end example
  3981. @end deffn
  3982. @deffn {Scheme Procedure} vector-any pred? vec1 vec2 @dots{}
  3983. Find the first parallel set of elements from @var{vec1} @var{vec2}
  3984. @dots{} for which @var{pred?} returns a true value. If such a parallel
  3985. set of elements exists, @code{vector-any} returns the value that
  3986. @var{pred?} returned for that set of elements. The iteration is
  3987. strictly left-to-right.
  3988. @end deffn
  3989. @deffn {Scheme Procedure} vector-every pred? vec1 vec2 @dots{}
  3990. If, for every index i between 0 and the length of the shortest vector
  3991. argument, the set of elements @code{(vector-ref vec1 i)}
  3992. @code{(vector-ref vec2 i)} @dots{} satisfies @var{pred?},
  3993. @code{vector-every} returns the value that @var{pred?} returned for the
  3994. last set of elements, at the last index of the shortest vector.
  3995. Otherwise it returns @code{#f}. The iteration is strictly
  3996. left-to-right.
  3997. @end deffn
  3998. @node SRFI-43 Mutators
  3999. @subsubsection SRFI-43 Mutators
  4000. @deffn {Scheme Procedure} vector-set! vec i value
  4001. Assign the contents of the location at @var{i} in @var{vec} to
  4002. @var{value}.
  4003. @end deffn
  4004. @deffn {Scheme Procedure} vector-swap! vec i j
  4005. Swap the values of the locations in @var{vec} at @var{i} and @var{j}.
  4006. @end deffn
  4007. @deffn {Scheme Procedure} vector-fill! vec fill [start [end]]
  4008. Assign the value of every location in @var{vec} between @var{start} and
  4009. @var{end} to @var{fill}. @var{start} defaults to 0 and @var{end}
  4010. defaults to the length of @var{vec}.
  4011. @end deffn
  4012. @deffn {Scheme Procedure} vector-reverse! vec [start [end]]
  4013. Destructively reverse the contents of @var{vec} between @var{start} and
  4014. @var{end}. @var{start} defaults to 0 and @var{end} defaults to the
  4015. length of @var{vec}.
  4016. @end deffn
  4017. @deffn {Scheme Procedure} vector-copy! target tstart source [sstart [send]]
  4018. Copy a block of elements from @var{source} to @var{target}, both of
  4019. which must be vectors, starting in @var{target} at @var{tstart} and
  4020. starting in @var{source} at @var{sstart}, ending when (@var{send} -
  4021. @var{sstart}) elements have been copied. It is an error for
  4022. @var{target} to have a length less than (@var{tstart} + @var{send} -
  4023. @var{sstart}). @var{sstart} defaults to 0 and @var{send} defaults to
  4024. the length of @var{source}.
  4025. @end deffn
  4026. @deffn {Scheme Procedure} vector-reverse-copy! target tstart source [sstart [send]]
  4027. Like @code{vector-copy!}, but this copies the elements in the reverse
  4028. order. It is an error if @var{target} and @var{source} are identical
  4029. vectors and the @var{target} and @var{source} ranges overlap; however,
  4030. if @var{tstart} = @var{sstart}, @code{vector-reverse-copy!} behaves as
  4031. @code{(vector-reverse! target tstart send)} would.
  4032. @end deffn
  4033. @node SRFI-43 Conversion
  4034. @subsubsection SRFI-43 Conversion
  4035. @deffn {Scheme Procedure} vector->list vec [start [end]]
  4036. Return a newly allocated list containing the elements in @var{vec}
  4037. between @var{start} and @var{end}. @var{start} defaults to 0 and
  4038. @var{end} defaults to the length of @var{vec}.
  4039. @end deffn
  4040. @deffn {Scheme Procedure} reverse-vector->list vec [start [end]]
  4041. Like @code{vector->list}, but the resulting list contains the specified
  4042. range of elements of @var{vec} in reverse order.
  4043. @end deffn
  4044. @deffn {Scheme Procedure} list->vector proper-list [start [end]]
  4045. Return a newly allocated vector of the elements from @var{proper-list}
  4046. with indices between @var{start} and @var{end}. @var{start} defaults to
  4047. 0 and @var{end} defaults to the length of @var{proper-list}. Note that
  4048. SRFI 43 does not document the @var{start} and @var{end} arguments, but
  4049. both its reference implementation and Guile's implementation support
  4050. them.
  4051. @end deffn
  4052. @deffn {Scheme Procedure} reverse-list->vector proper-list [start [end]]
  4053. Like @code{list->vector}, but the resulting vector contains the specified
  4054. range of elements of @var{proper-list} in reverse order. Note that SRFI
  4055. 43 does not document the @var{start} and @var{end} arguments, but both
  4056. its reference implementation and Guile's implementation support them.
  4057. @end deffn
  4058. @node SRFI-45
  4059. @subsection SRFI-45 - Primitives for Expressing Iterative Lazy Algorithms
  4060. @cindex SRFI-45
  4061. This subsection is based on @uref{http://srfi.schemers.org/srfi-45/srfi-45.html, the
  4062. specification of SRFI-45} written by Andr@'e van Tonder.
  4063. @c Copyright (C) André van Tonder (2003). All Rights Reserved.
  4064. @c Permission is hereby granted, free of charge, to any person obtaining a
  4065. @c copy of this software and associated documentation files (the
  4066. @c "Software"), to deal in the Software without restriction, including
  4067. @c without limitation the rights to use, copy, modify, merge, publish,
  4068. @c distribute, sublicense, and/or sell copies of the Software, and to
  4069. @c permit persons to whom the Software is furnished to do so, subject to
  4070. @c the following conditions:
  4071. @c The above copyright notice and this permission notice shall be included
  4072. @c in all copies or substantial portions of the Software.
  4073. @c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4074. @c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4075. @c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  4076. @c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  4077. @c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  4078. @c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  4079. @c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  4080. Lazy evaluation is traditionally simulated in Scheme using @code{delay}
  4081. and @code{force}. However, these primitives are not powerful enough to
  4082. express a large class of lazy algorithms that are iterative. Indeed, it
  4083. is folklore in the Scheme community that typical iterative lazy
  4084. algorithms written using delay and force will often require unbounded
  4085. memory.
  4086. This SRFI provides set of three operations: @{@code{lazy}, @code{delay},
  4087. @code{force}@}, which allow the programmer to succinctly express lazy
  4088. algorithms while retaining bounded space behavior in cases that are
  4089. properly tail-recursive. A general recipe for using these primitives is
  4090. provided. An additional procedure @code{eager} is provided for the
  4091. construction of eager promises in cases where efficiency is a concern.
  4092. Although this SRFI redefines @code{delay} and @code{force}, the
  4093. extension is conservative in the sense that the semantics of the subset
  4094. @{@code{delay}, @code{force}@} in isolation (i.e., as long as the
  4095. program does not use @code{lazy}) agrees with that in R5RS. In other
  4096. words, no program that uses the R5RS definitions of delay and force will
  4097. break if those definition are replaced by the SRFI-45 definitions of
  4098. delay and force.
  4099. Guile also adds @code{promise?} to the list of exports, which is not
  4100. part of the official SRFI-45.
  4101. @deffn {Scheme Procedure} promise? obj
  4102. Return true if @var{obj} is an SRFI-45 promise, otherwise return false.
  4103. @end deffn
  4104. @deffn {Scheme Syntax} delay expression
  4105. Takes an expression of arbitrary type @var{a} and returns a promise of
  4106. type @code{(Promise @var{a})} which at some point in the future may be
  4107. asked (by the @code{force} procedure) to evaluate the expression and
  4108. deliver the resulting value.
  4109. @end deffn
  4110. @deffn {Scheme Syntax} lazy expression
  4111. Takes an expression of type @code{(Promise @var{a})} and returns a
  4112. promise of type @code{(Promise @var{a})} which at some point in the
  4113. future may be asked (by the @code{force} procedure) to evaluate the
  4114. expression and deliver the resulting promise.
  4115. @end deffn
  4116. @deffn {Scheme Procedure} force expression
  4117. Takes an argument of type @code{(Promise @var{a})} and returns a value
  4118. of type @var{a} as follows: If a value of type @var{a} has been computed
  4119. for the promise, this value is returned. Otherwise, the promise is
  4120. first evaluated, then overwritten by the obtained promise or value, and
  4121. then force is again applied (iteratively) to the promise.
  4122. @end deffn
  4123. @deffn {Scheme Procedure} eager expression
  4124. Takes an argument of type @var{a} and returns a value of type
  4125. @code{(Promise @var{a})}. As opposed to @code{delay}, the argument is
  4126. evaluated eagerly. Semantically, writing @code{(eager expression)} is
  4127. equivalent to writing
  4128. @lisp
  4129. (let ((value expression)) (delay value)).
  4130. @end lisp
  4131. However, the former is more efficient since it does not require
  4132. unnecessary creation and evaluation of thunks. We also have the
  4133. equivalence
  4134. @lisp
  4135. (delay expression) = (lazy (eager expression))
  4136. @end lisp
  4137. @end deffn
  4138. The following reduction rules may be helpful for reasoning about these
  4139. primitives. However, they do not express the memoization and memory
  4140. usage semantics specified above:
  4141. @lisp
  4142. (force (delay expression)) -> expression
  4143. (force (lazy expression)) -> (force expression)
  4144. (force (eager value)) -> value
  4145. @end lisp
  4146. @subsubheading Correct usage
  4147. We now provide a general recipe for using the primitives @{@code{lazy},
  4148. @code{delay}, @code{force}@} to express lazy algorithms in Scheme. The
  4149. transformation is best described by way of an example: Consider the
  4150. stream-filter algorithm, expressed in a hypothetical lazy language as
  4151. @lisp
  4152. (define (stream-filter p? s)
  4153. (if (null? s) '()
  4154. (let ((h (car s))
  4155. (t (cdr s)))
  4156. (if (p? h)
  4157. (cons h (stream-filter p? t))
  4158. (stream-filter p? t)))))
  4159. @end lisp
  4160. This algorithm can be expressed as follows in Scheme:
  4161. @lisp
  4162. (define (stream-filter p? s)
  4163. (lazy
  4164. (if (null? (force s)) (delay '())
  4165. (let ((h (car (force s)))
  4166. (t (cdr (force s))))
  4167. (if (p? h)
  4168. (delay (cons h (stream-filter p? t)))
  4169. (stream-filter p? t))))))
  4170. @end lisp
  4171. In other words, we
  4172. @itemize @bullet
  4173. @item
  4174. wrap all constructors (e.g., @code{'()}, @code{cons}) with @code{delay},
  4175. @item
  4176. apply @code{force} to arguments of deconstructors (e.g., @code{car},
  4177. @code{cdr} and @code{null?}),
  4178. @item
  4179. wrap procedure bodies with @code{(lazy ...)}.
  4180. @end itemize
  4181. @node SRFI-46
  4182. @subsection SRFI-46 Basic syntax-rules Extensions
  4183. @cindex SRFI-46
  4184. Guile's core @code{syntax-rules} supports the extensions specified by
  4185. SRFI-46/R7RS. Tail patterns have been supported since at least Guile
  4186. 2.0, and custom ellipsis identifiers have been supported since Guile
  4187. 2.0.10. @xref{Syntax Rules}.
  4188. @node SRFI-55
  4189. @subsection SRFI-55 - Requiring Features
  4190. @cindex SRFI-55
  4191. SRFI-55 provides @code{require-extension} which is a portable
  4192. mechanism to load selected SRFI modules. This is implemented in the
  4193. Guile core, there's no module needed to get SRFI-55 itself.
  4194. @deffn {library syntax} require-extension clause1 clause2 @dots{}
  4195. Require the features of @var{clause1} @var{clause2} @dots{} , throwing
  4196. an error if any are unavailable.
  4197. A @var{clause} is of the form @code{(@var{identifier} arg...)}. The
  4198. only @var{identifier} currently supported is @code{srfi} and the
  4199. arguments are SRFI numbers. For example to get SRFI-1 and SRFI-6,
  4200. @example
  4201. (require-extension (srfi 1 6))
  4202. @end example
  4203. @code{require-extension} can only be used at the top-level.
  4204. A Guile-specific program can simply @code{use-modules} to load SRFIs
  4205. not already in the core, @code{require-extension} is for programs
  4206. designed to be portable to other Scheme implementations.
  4207. @end deffn
  4208. @node SRFI-60
  4209. @subsection SRFI-60 - Integers as Bits
  4210. @cindex SRFI-60
  4211. @cindex integers as bits
  4212. @cindex bitwise logical
  4213. This SRFI provides various functions for treating integers as bits and
  4214. for bitwise manipulations. These functions can be obtained with,
  4215. @example
  4216. (use-modules (srfi srfi-60))
  4217. @end example
  4218. Integers are treated as infinite precision twos-complement, the same
  4219. as in the core logical functions (@pxref{Bitwise Operations}). And
  4220. likewise bit indexes start from 0 for the least significant bit. The
  4221. following functions in this SRFI are already in the Guile core,
  4222. @quotation
  4223. @code{logand},
  4224. @code{logior},
  4225. @code{logxor},
  4226. @code{lognot},
  4227. @code{logtest},
  4228. @code{logcount},
  4229. @code{integer-length},
  4230. @code{logbit?},
  4231. @code{ash}
  4232. @end quotation
  4233. @sp 1
  4234. @defun bitwise-and n1 ...
  4235. @defunx bitwise-ior n1 ...
  4236. @defunx bitwise-xor n1 ...
  4237. @defunx bitwise-not n
  4238. @defunx any-bits-set? j k
  4239. @defunx bit-set? index n
  4240. @defunx arithmetic-shift n count
  4241. @defunx bit-field n start end
  4242. @defunx bit-count n
  4243. Aliases for @code{logand}, @code{logior}, @code{logxor},
  4244. @code{lognot}, @code{logtest}, @code{logbit?}, @code{ash},
  4245. @code{bit-extract} and @code{logcount} respectively.
  4246. Note that the name @code{bit-count} conflicts with @code{bit-count} in
  4247. the core (@pxref{Bit Vectors}).
  4248. @end defun
  4249. @defun bitwise-if mask n1 n0
  4250. @defunx bitwise-merge mask n1 n0
  4251. Return an integer with bits selected from @var{n1} and @var{n0}
  4252. according to @var{mask}. Those bits where @var{mask} has 1s are taken
  4253. from @var{n1}, and those where @var{mask} has 0s are taken from
  4254. @var{n0}.
  4255. @example
  4256. (bitwise-if 3 #b0101 #b1010) @result{} 9
  4257. @end example
  4258. @end defun
  4259. @defun log2-binary-factors n
  4260. @defunx first-set-bit n
  4261. Return a count of how many factors of 2 are present in @var{n}. This
  4262. is also the bit index of the lowest 1 bit in @var{n}. If @var{n} is
  4263. 0, the return is @math{-1}.
  4264. @example
  4265. (log2-binary-factors 6) @result{} 1
  4266. (log2-binary-factors -8) @result{} 3
  4267. @end example
  4268. @end defun
  4269. @defun copy-bit index n newbit
  4270. Return @var{n} with the bit at @var{index} set according to
  4271. @var{newbit}. @var{newbit} should be @code{#t} to set the bit to 1,
  4272. or @code{#f} to set it to 0. Bits other than at @var{index} are
  4273. unchanged in the return.
  4274. @example
  4275. (copy-bit 1 #b0101 #t) @result{} 7
  4276. @end example
  4277. @end defun
  4278. @defun copy-bit-field n newbits start end
  4279. Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
  4280. (exclusive) changed to the value @var{newbits}.
  4281. The least significant bit in @var{newbits} goes to @var{start}, the
  4282. next to @math{@var{start}+1}, etc. Anything in @var{newbits} past the
  4283. @var{end} given is ignored.
  4284. @example
  4285. (copy-bit-field #b10000 #b11 1 3) @result{} #b10110
  4286. @end example
  4287. @end defun
  4288. @defun rotate-bit-field n count start end
  4289. Return @var{n} with the bit field from @var{start} (inclusive) to
  4290. @var{end} (exclusive) rotated upwards by @var{count} bits.
  4291. @var{count} can be positive or negative, and it can be more than the
  4292. field width (it'll be reduced modulo the width).
  4293. @example
  4294. (rotate-bit-field #b0110 2 1 4) @result{} #b1010
  4295. @end example
  4296. @end defun
  4297. @defun reverse-bit-field n start end
  4298. Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
  4299. (exclusive) reversed.
  4300. @example
  4301. (reverse-bit-field #b101001 2 4) @result{} #b100101
  4302. @end example
  4303. @end defun
  4304. @defun integer->list n [len]
  4305. Return bits from @var{n} in the form of a list of @code{#t} for 1 and
  4306. @code{#f} for 0. The least significant @var{len} bits are returned,
  4307. and the first list element is the most significant of those bits. If
  4308. @var{len} is not given, the default is @code{(integer-length @var{n})}
  4309. (@pxref{Bitwise Operations}).
  4310. @example
  4311. (integer->list 6) @result{} (#t #t #f)
  4312. (integer->list 1 4) @result{} (#f #f #f #t)
  4313. @end example
  4314. @end defun
  4315. @defun list->integer lst
  4316. @defunx booleans->integer bool@dots{}
  4317. Return an integer formed bitwise from the given @var{lst} list of
  4318. booleans, or for @code{booleans->integer} from the @var{bool}
  4319. arguments.
  4320. Each boolean is @code{#t} for a 1 and @code{#f} for a 0. The first
  4321. element becomes the most significant bit in the return.
  4322. @example
  4323. (list->integer '(#t #f #t #f)) @result{} 10
  4324. @end example
  4325. @end defun
  4326. @node SRFI-61
  4327. @subsection SRFI-61 - A more general @code{cond} clause
  4328. This SRFI extends RnRS @code{cond} to support test expressions that
  4329. return multiple values, as well as arbitrary definitions of test
  4330. success. SRFI 61 is implemented in the Guile core; there's no module
  4331. needed to get SRFI-61 itself. Extended @code{cond} is documented in
  4332. @ref{Conditionals,, Simple Conditional Evaluation}.
  4333. @node SRFI-62
  4334. @subsection SRFI-62 - S-expression comments.
  4335. @cindex SRFI-62
  4336. Starting from version 2.0, Guile's @code{read} supports SRFI-62/R7RS
  4337. S-expression comments by default.
  4338. @node SRFI-64
  4339. @subsection SRFI-64 - A Scheme API for test suites.
  4340. @cindex SRFI-64
  4341. See @uref{http://srfi.schemers.org/srfi-64/srfi-64.html, the
  4342. specification of SRFI-64}.
  4343. @node SRFI-67
  4344. @subsection SRFI-67 - Compare procedures
  4345. @cindex SRFI-67
  4346. See @uref{http://srfi.schemers.org/srfi-67/srfi-67.html, the
  4347. specification of SRFI-67}.
  4348. @node SRFI-69
  4349. @subsection SRFI-69 - Basic hash tables
  4350. @cindex SRFI-69
  4351. This is a portable wrapper around Guile's built-in hash table and weak
  4352. table support. @xref{Hash Tables}, for information on that built-in
  4353. support. Above that, this hash-table interface provides association
  4354. of equality and hash functions with tables at creation time, so
  4355. variants of each function are not required, as well as a procedure
  4356. that takes care of most uses for Guile hash table handles, which this
  4357. SRFI does not provide as such.
  4358. Access it with:
  4359. @lisp
  4360. (use-modules (srfi srfi-69))
  4361. @end lisp
  4362. @menu
  4363. * SRFI-69 Creating hash tables::
  4364. * SRFI-69 Accessing table items::
  4365. * SRFI-69 Table properties::
  4366. * SRFI-69 Hash table algorithms::
  4367. @end menu
  4368. @node SRFI-69 Creating hash tables
  4369. @subsubsection Creating hash tables
  4370. @deffn {Scheme Procedure} make-hash-table [equal-proc hash-proc #:weak weakness start-size]
  4371. Create and answer a new hash table with @var{equal-proc} as the
  4372. equality function and @var{hash-proc} as the hashing function.
  4373. By default, @var{equal-proc} is @code{equal?}. It can be any
  4374. two-argument procedure, and should answer whether two keys are the
  4375. same for this table's purposes.
  4376. By default @var{hash-proc} assumes that @code{equal-proc} is no
  4377. coarser than @code{equal?} unless it is literally @code{string-ci=?}.
  4378. If provided, @var{hash-proc} should be a two-argument procedure that
  4379. takes a key and the current table size, and answers a reasonably good
  4380. hash integer between 0 (inclusive) and the size (exclusive).
  4381. @var{weakness} should be @code{#f} or a symbol indicating how ``weak''
  4382. the hash table is:
  4383. @table @code
  4384. @item #f
  4385. An ordinary non-weak hash table. This is the default.
  4386. @item key
  4387. When the key has no more non-weak references at GC, remove that entry.
  4388. @item value
  4389. When the value has no more non-weak references at GC, remove that
  4390. entry.
  4391. @item key-or-value
  4392. When either has no more non-weak references at GC, remove the
  4393. association.
  4394. @end table
  4395. As a legacy of the time when Guile couldn't grow hash tables,
  4396. @var{start-size} is an optional integer argument that specifies the
  4397. approximate starting size for the hash table, which will be rounded to
  4398. an algorithmically-sounder number.
  4399. @end deffn
  4400. By @dfn{coarser} than @code{equal?}, we mean that for all @var{x} and
  4401. @var{y} values where @code{(@var{equal-proc} @var{x} @var{y})},
  4402. @code{(equal? @var{x} @var{y})} as well. If that does not hold for
  4403. your @var{equal-proc}, you must provide a @var{hash-proc}.
  4404. In the case of weak tables, remember that @dfn{references} above
  4405. always refers to @code{eq?}-wise references. Just because you have a
  4406. reference to some string @code{"foo"} doesn't mean that an association
  4407. with key @code{"foo"} in a weak-key table @emph{won't} be collected;
  4408. it only counts as a reference if the two @code{"foo"}s are @code{eq?},
  4409. regardless of @var{equal-proc}. As such, it is usually only sensible
  4410. to use @code{eq?} and @code{hashq} as the equivalence and hash
  4411. functions for a weak table. @xref{Weak References}, for more
  4412. information on Guile's built-in weak table support.
  4413. @deffn {Scheme Procedure} alist->hash-table alist [equal-proc hash-proc #:weak weakness start-size]
  4414. As with @code{make-hash-table}, but initialize it with the
  4415. associations in @var{alist}. Where keys are repeated in @var{alist},
  4416. the leftmost association takes precedence.
  4417. @end deffn
  4418. @node SRFI-69 Accessing table items
  4419. @subsubsection Accessing table items
  4420. @deffn {Scheme Procedure} hash-table-ref table key [default-thunk]
  4421. @deffnx {Scheme Procedure} hash-table-ref/default table key default
  4422. Answer the value associated with @var{key} in @var{table}. If
  4423. @var{key} is not present, answer the result of invoking the thunk
  4424. @var{default-thunk}, which signals an error instead by default.
  4425. @code{hash-table-ref/default} is a variant that requires a third
  4426. argument, @var{default}, and answers @var{default} itself instead of
  4427. invoking it.
  4428. @end deffn
  4429. @deffn {Scheme Procedure} hash-table-set! table key new-value
  4430. Set @var{key} to @var{new-value} in @var{table}.
  4431. @end deffn
  4432. @deffn {Scheme Procedure} hash-table-delete! table key
  4433. Remove the association of @var{key} in @var{table}, if present. If
  4434. absent, do nothing.
  4435. @end deffn
  4436. @deffn {Scheme Procedure} hash-table-exists? table key
  4437. Answer whether @var{key} has an association in @var{table}.
  4438. @end deffn
  4439. @deffn {Scheme Procedure} hash-table-update! table key modifier [default-thunk]
  4440. @deffnx {Scheme Procedure} hash-table-update!/default table key modifier default
  4441. Replace @var{key}'s associated value in @var{table} by invoking
  4442. @var{modifier} with one argument, the old value.
  4443. If @var{key} is not present, and @var{default-thunk} is provided,
  4444. invoke it with no arguments to get the ``old value'' to be passed to
  4445. @var{modifier} as above. If @var{default-thunk} is not provided in
  4446. such a case, signal an error.
  4447. @code{hash-table-update!/default} is a variant that requires the
  4448. fourth argument, which is used directly as the ``old value'' rather
  4449. than as a thunk to be invoked to retrieve the ``old value''.
  4450. @end deffn
  4451. @node SRFI-69 Table properties
  4452. @subsubsection Table properties
  4453. @deffn {Scheme Procedure} hash-table-size table
  4454. Answer the number of associations in @var{table}. This is guaranteed
  4455. to run in constant time for non-weak tables.
  4456. @end deffn
  4457. @deffn {Scheme Procedure} hash-table-keys table
  4458. Answer an unordered list of the keys in @var{table}.
  4459. @end deffn
  4460. @deffn {Scheme Procedure} hash-table-values table
  4461. Answer an unordered list of the values in @var{table}.
  4462. @end deffn
  4463. @deffn {Scheme Procedure} hash-table-walk table proc
  4464. Invoke @var{proc} once for each association in @var{table}, passing
  4465. the key and value as arguments.
  4466. @end deffn
  4467. @deffn {Scheme Procedure} hash-table-fold table proc init
  4468. Invoke @code{(@var{proc} @var{key} @var{value} @var{previous})} for
  4469. each @var{key} and @var{value} in @var{table}, where @var{previous} is
  4470. the result of the previous invocation, using @var{init} as the first
  4471. @var{previous} value. Answer the final @var{proc} result.
  4472. @end deffn
  4473. @deffn {Scheme Procedure} hash-table->alist table
  4474. Answer an alist where each association in @var{table} is an
  4475. association in the result.
  4476. @end deffn
  4477. @node SRFI-69 Hash table algorithms
  4478. @subsubsection Hash table algorithms
  4479. Each hash table carries an @dfn{equivalence function} and a @dfn{hash
  4480. function}, used to implement key lookups. Beginning users should
  4481. follow the rules for consistency of the default @var{hash-proc}
  4482. specified above. Advanced users can use these to implement their own
  4483. equivalence and hash functions for specialized lookup semantics.
  4484. @deffn {Scheme Procedure} hash-table-equivalence-function hash-table
  4485. @deffnx {Scheme Procedure} hash-table-hash-function hash-table
  4486. Answer the equivalence and hash function of @var{hash-table}, respectively.
  4487. @end deffn
  4488. @deffn {Scheme Procedure} hash obj [size]
  4489. @deffnx {Scheme Procedure} string-hash obj [size]
  4490. @deffnx {Scheme Procedure} string-ci-hash obj [size]
  4491. @deffnx {Scheme Procedure} hash-by-identity obj [size]
  4492. Answer a hash value appropriate for equality predicate @code{equal?},
  4493. @code{string=?}, @code{string-ci=?}, and @code{eq?}, respectively.
  4494. @end deffn
  4495. @code{hash} is a backwards-compatible replacement for Guile's built-in
  4496. @code{hash}.
  4497. @node SRFI-71
  4498. @subsection SRFI-71 - Extended let-syntax for multiple values
  4499. @cindex SRFI-71
  4500. This SRFI shadows the forms for @code{let}, @code{let*}, and @code{letrec}
  4501. so that they may accept multiple values. For example:
  4502. @example
  4503. (use-modules (srfi srfi-71))
  4504. (let* ((x y (values 1 2))
  4505. (z (+ x y)))
  4506. (* z 2))
  4507. @result{} 6
  4508. @end example
  4509. See @uref{http://srfi.schemers.org/srfi-71/srfi-71.html, the
  4510. specification of SRFI-71}.
  4511. @node SRFI-87
  4512. @subsection SRFI-87 => in case clauses
  4513. @cindex SRFI-87
  4514. Starting from version 2.0.6, Guile's core @code{case} syntax supports
  4515. @code{=>} in clauses, as specified by SRFI-87/R7RS.
  4516. @xref{Conditionals}.
  4517. @node SRFI-88
  4518. @subsection SRFI-88 Keyword Objects
  4519. @cindex SRFI-88
  4520. @cindex keyword objects
  4521. @uref{http://srfi.schemers.org/srfi-88/srfi-88.html, SRFI-88} provides
  4522. @dfn{keyword objects}, which are equivalent to Guile's keywords
  4523. (@pxref{Keywords}). SRFI-88 keywords can be entered using the
  4524. @dfn{postfix keyword syntax}, which consists of an identifier followed
  4525. by @code{:} (@pxref{Scheme Read, @code{postfix} keyword syntax}).
  4526. SRFI-88 can be made available with:
  4527. @example
  4528. (use-modules (srfi srfi-88))
  4529. @end example
  4530. Doing so installs the right reader option for keyword syntax, using
  4531. @code{(read-set! keywords 'postfix)}. It also provides the procedures
  4532. described below.
  4533. @deffn {Scheme Procedure} keyword? obj
  4534. Return @code{#t} if @var{obj} is a keyword. This is the same procedure
  4535. as the same-named built-in procedure (@pxref{Keyword Procedures,
  4536. @code{keyword?}}).
  4537. @example
  4538. (keyword? foo:) @result{} #t
  4539. (keyword? 'foo:) @result{} #t
  4540. (keyword? "foo") @result{} #f
  4541. @end example
  4542. @end deffn
  4543. @deffn {Scheme Procedure} keyword->string kw
  4544. Return the name of @var{kw} as a string, i.e., without the trailing
  4545. colon. The returned string may not be modified, e.g., with
  4546. @code{string-set!}.
  4547. @example
  4548. (keyword->string foo:) @result{} "foo"
  4549. @end example
  4550. @end deffn
  4551. @deffn {Scheme Procedure} string->keyword str
  4552. Return the keyword object whose name is @var{str}.
  4553. @example
  4554. (keyword->string (string->keyword "a b c")) @result{} "a b c"
  4555. @end example
  4556. @end deffn
  4557. @node SRFI-98
  4558. @subsection SRFI-98 Accessing environment variables.
  4559. @cindex SRFI-98
  4560. @cindex environment variables
  4561. This is a portable wrapper around Guile's built-in support for
  4562. interacting with the current environment, @xref{Runtime Environment}.
  4563. @deffn {Scheme Procedure} get-environment-variable name
  4564. Returns a string containing the value of the environment variable
  4565. given by the string @code{name}, or @code{#f} if the named
  4566. environment variable is not found. This is equivalent to
  4567. @code{(getenv name)}.
  4568. @end deffn
  4569. @deffn {Scheme Procedure} get-environment-variables
  4570. Returns the names and values of all the environment variables as an
  4571. association list in which both the keys and the values are strings.
  4572. @end deffn
  4573. @node SRFI-105
  4574. @subsection SRFI-105 Curly-infix expressions.
  4575. @cindex SRFI-105
  4576. @cindex curly-infix
  4577. @cindex curly-infix-and-bracket-lists
  4578. Guile's built-in reader includes support for SRFI-105 curly-infix
  4579. expressions. See @uref{http://srfi.schemers.org/srfi-105/srfi-105.html,
  4580. the specification of SRFI-105}. Some examples:
  4581. @example
  4582. @{n <= 5@} @result{} (<= n 5)
  4583. @{a + b + c@} @result{} (+ a b c)
  4584. @{a * @{b + c@}@} @result{} (* a (+ b c))
  4585. @{(- a) / b@} @result{} (/ (- a) b)
  4586. @{-(a) / b@} @result{} (/ (- a) b) as well
  4587. @{(f a b) + (g h)@} @result{} (+ (f a b) (g h))
  4588. @{f(a b) + g(h)@} @result{} (+ (f a b) (g h)) as well
  4589. @{f[a b] + g(h)@} @result{} (+ ($bracket-apply$ f a b) (g h))
  4590. '@{a + f(b) + x@} @result{} '(+ a (f b) x)
  4591. @{length(x) >= 6@} @result{} (>= (length x) 6)
  4592. @{n-1 + n-2@} @result{} (+ n-1 n-2)
  4593. @{n * factorial@{n - 1@}@} @result{} (* n (factorial (- n 1)))
  4594. @{@{a > 0@} and @{b >= 1@}@} @result{} (and (> a 0) (>= b 1))
  4595. @{f@{n - 1@}(x)@} @result{} ((f (- n 1)) x)
  4596. @{a . z@} @result{} ($nfx$ a . z)
  4597. @{a + b - c@} @result{} ($nfx$ a + b - c)
  4598. @end example
  4599. To enable curly-infix expressions within a file, place the reader
  4600. directive @code{#!curly-infix} before the first use of curly-infix
  4601. notation. To globally enable curly-infix expressions in Guile's reader,
  4602. set the @code{curly-infix} read option.
  4603. Guile also implements the following non-standard extension to SRFI-105:
  4604. if @code{curly-infix} is enabled and there is no other meaning assigned
  4605. to square brackets (i.e. the @code{square-brackets} read option is
  4606. turned off), then lists within square brackets are read as normal lists
  4607. but with the special symbol @code{$bracket-list$} added to the front.
  4608. To enable this combination of read options within a file, use the reader
  4609. directive @code{#!curly-infix-and-bracket-lists}. For example:
  4610. @example
  4611. [a b] @result{} ($bracket-list$ a b)
  4612. [a . b] @result{} ($bracket-list$ a . b)
  4613. @end example
  4614. For more information on reader options, @xref{Scheme Read}.
  4615. @node SRFI-111
  4616. @subsection SRFI-111 Boxes.
  4617. @cindex SRFI-111
  4618. @uref{http://srfi.schemers.org/srfi-111/srfi-111.html, SRFI-111}
  4619. provides boxes: objects with a single mutable cell.
  4620. @deffn {Scheme Procedure} box value
  4621. Return a newly allocated box whose contents is initialized to
  4622. @var{value}.
  4623. @end deffn
  4624. @deffn {Scheme Procedure} box? obj
  4625. Return true if @var{obj} is a box, otherwise return false.
  4626. @end deffn
  4627. @deffn {Scheme Procedure} unbox box
  4628. Return the current contents of @var{box}.
  4629. @end deffn
  4630. @deffn {Scheme Procedure} set-box! box value
  4631. Set the contents of @var{box} to @var{value}.
  4632. @end deffn
  4633. @node SRFI-125
  4634. @subsection SRFI-125 Intermediate hash tables
  4635. @cindex SRFI-125
  4636. @cindex hash tables
  4637. This SRFI defines an interface to hash tables, which are widely
  4638. recognized as a fundamental data structure for a wide variety of
  4639. applications. A hash table is a data structure that:
  4640. @itemize
  4641. @item
  4642. Is disjoint from all other types.
  4643. @item
  4644. Provides a mapping from objects known as keys to corresponding objects
  4645. known as values.
  4646. @itemize
  4647. @item
  4648. Keys may be any Scheme objects in some kinds of hash tables, but are
  4649. restricted in other kinds.
  4650. @item
  4651. Values may be any Scheme objects.
  4652. @end itemize
  4653. @item
  4654. Has no intrinsic order for the key-value associations it contains.
  4655. @item
  4656. Provides an equality predicate which defines when a proposed key is the
  4657. same as an existing key. No table may contain more than one value for a
  4658. given key.
  4659. @item
  4660. Provides a hash function which maps a candidate key into a non-negative
  4661. exact integer.
  4662. @item
  4663. Supports mutation as the primary means of setting the contents of a
  4664. table.
  4665. @item
  4666. Provides key lookup and destructive update in (expected) amortized
  4667. constant time, provided a satisfactory hash function is available.
  4668. @item
  4669. Does not guarantee that whole-table operations work in the presence of
  4670. concurrent mutation of the whole hash table (values may be safely
  4671. mutated).
  4672. @end itemize
  4673. @node SRFI-125 Rationale
  4674. @subsubsection SRFI-125 Rationale
  4675. Hash tables themselves don't really need defending: almost all
  4676. dynamically typed languages, from awk to JavaScript to Lua to Perl to
  4677. Python to Common Lisp, and including many Scheme implementations,
  4678. provide them in some form as a fundamental data structure. Therefore,
  4679. what needs to be defended is not the data structure but the procedures.
  4680. This SRFI is at an intermediate level. It supports a great many
  4681. convenience procedures on top of the basic hash table interfaces
  4682. provided by SRFI 69 and R6RS. Nothing in it adds power to what those
  4683. interfaces provide, but it does add convenience in the form of
  4684. pre-debugged routines to do various common things, and even some things
  4685. not so commonly done but useful.
  4686. There is no mandated support for thread safety, immutability, or
  4687. weakness, though there are portable hooks for specifying these features.
  4688. While the specification of this SRFI accepts separate equality
  4689. predicates and hash functions for backward compatibility, it strongly
  4690. encourages the use of SRFI 128 comparators, which package a type test,
  4691. an equality predicate, and a hash function into a single bundle.
  4692. @subheading SRFI 69 compatibility
  4693. This SRFI is downward compatible with SRFI 69. Some procedures have
  4694. been given new preferred names for compatibility with other SRFIs, but
  4695. in all cases the SRFI 69 names have been retained as deprecated
  4696. synonyms; in Guile, these deprecated procedures have their name prefixed
  4697. with @code{deprecated:}.
  4698. There is one absolute incompatibility with SRFI 69: the reflective
  4699. procedure @code{hash-table-hash-function} may return @code{#f}, which is
  4700. not permitted by SRFI 69.
  4701. @subheading R6RS compatibility
  4702. The relatively few hash table procedures in R6RS are all available in
  4703. this SRFI under somewhat different names. The only substantive
  4704. difference is that R6RS @code{hashtable-values} and
  4705. @code{hashtable-entries} return vectors, whereas in this SRFI
  4706. @code{hash-table-value} and @code{hash-table-entries} return lists.
  4707. This SRFI adopts SRFI 69's term hash-table rather than R6RS's hashtable,
  4708. because of the universal use of ``hash table'' rather than ``hashtable''
  4709. in other computer languages and in technical prose generally. Besides,
  4710. the English word hashtable obviously means something that can be@dots{}
  4711. hashted.
  4712. In addition, the @code{hashtable-ref} and @code{hashtable-update!} of
  4713. R6RS correspond to the @code{hash-table-ref/default} and
  4714. @code{hash-table-update!/default} of both SRFI 69 and this SRFI.
  4715. @subheading Common Lisp compatibility
  4716. As usual, the Common Lisp names are completely different from the Scheme
  4717. names. Common Lisp provides the following capabilities that are
  4718. @emph{not} in this SRFI:
  4719. @itemize
  4720. @item
  4721. The constructor allows specifying the rehash size and rehash threshold
  4722. of the new hash table. There are also accessors and mutators for these
  4723. and for the current capacity (as opposed to size).
  4724. @item
  4725. There are hash tables based on @code{equalp} (which does not exist in
  4726. Scheme).
  4727. @item
  4728. @code{with-hash-table-iterator} is a hash table external iterator
  4729. implemented as a local macro.
  4730. @item
  4731. @code{sxhash} is an implementation-specific hash function for the equal
  4732. predicate. It has the property that objects in different instantiations
  4733. of the same Lisp implementation that are similar, a concept analogous to
  4734. e@code{qual} but defined across all instantiations, always return the
  4735. same value from @code{sxhash}; for example, the symbol @code{xyz} will
  4736. have the same @code{sxhash} result in all instantiations.
  4737. @end itemize
  4738. @subheading Sources
  4739. The procedures in this SRFI are drawn primarily from SRFI 69 and
  4740. R6RS. In addition, the following sources are acknowledged:
  4741. @itemize
  4742. @item
  4743. The @code{hash-table-mutable?} procedure and the second argument of
  4744. @code{hash-table-copy} (which allows the creation of immutable hash
  4745. tables) are from R6RS, renamed in the style of this SRFI.
  4746. @item
  4747. The @code{hash-table-intern!} procedure is from
  4748. @url{https://docs.racket-lang.org/reference/hashtables.html, Racket},
  4749. renamed in the style of this SRFI.
  4750. @item
  4751. The @code{hash-table-find} procedure is a modified version of
  4752. @code{table-search} in Gambit.
  4753. @item
  4754. The procedures @code{hash-table-unfold} and @code{hash-table-count} were
  4755. suggested by SRFI-1.
  4756. @item
  4757. The procedures @code{hash-table=?} and @code{hash-table-map} were
  4758. suggested by Haskell's @code{Data.Map.Strict} module.
  4759. @item
  4760. The procedure @code{hash-table-map->list} is from Guile.
  4761. @end itemize
  4762. The procedures @code{hash-table-empty?,} @code{hash-table-empty-copy,
  4763. hash-table-pop!,} @code{hash-table-map!,}
  4764. @code{hash-table-intersection!, hash-table-difference!,} and
  4765. @code{hash-table-xor!} were added for convenience and completeness.
  4766. The native hash tables of MIT, SISC, Bigloo, Scheme48, SLIB, RScheme,
  4767. Scheme 7, Scheme 9, Rep, and FemtoLisp were also investigated, but no
  4768. additional procedures were incorporated.
  4769. @subheading Pronunciation
  4770. The slash in the names of some procedures can be pronounced ``with''.
  4771. @node SRFI-125 Constructors
  4772. @subsubsection SRFI-125 Constructors
  4773. @deffn {Scheme Procedure} make-hash-table comparator [ arg @dots{} ]
  4774. @deffnx {Scheme Procedure} make-hash-table equality-predicate [ hash-function ] [ arg @dots{} ])
  4775. Return a newly allocated hash table whose equality predicate and hash
  4776. function are extracted from comparator. Alternatively, for backward
  4777. compatibility with SRFI 69 the equality predicate and hash function can
  4778. be passed as separate arguments; this usage is deprecated.
  4779. These procedures relate to R6RS @code{make-eq-hashtable},
  4780. @code{make-eqv-hashtable} and @code{make-hashtable} ones, and
  4781. @code{make-hash-table} from Common Lisp.
  4782. @end deffn
  4783. @deffn {Scheme Procedure} hash-table comparator [ key value ] @dots{}
  4784. Return a newly allocated hash table, created as if by
  4785. @code{make-hash-table} using @var{comparator}. For each pair of
  4786. arguments, an association is added to the new hash table with @var{key}
  4787. as its key and @var{value} as its value. This procedure returns an
  4788. immutable hash table. If the same key (in the sense of the equality
  4789. predicate) is specified more than once, it is an error.
  4790. @end deffn
  4791. @deffn {Scheme Procedure} hash-table-unfold stop? mapper successor seed comparator arg @dots{}
  4792. Create a new hash table as if by @var{make-hash-table} using
  4793. @var{comparator} and the @var{args}. If the result of applying the
  4794. predicate @code{stop?} to @var{seed} is true, return the hash table.
  4795. Otherwise, apply the procedure @var{mapper} to @var{seed}. @var{mapper}
  4796. returns two values, which are inserted into the hash table as the key
  4797. and the value respectively. Then get a new seed by applying the
  4798. procedure @var{successor} to @var{seed}, and repeat this algorithm.
  4799. @end deffn
  4800. @deffn {Scheme Procedure} alist->hash-table alist comparator arg @dots{}
  4801. @deffnx {Scheme Procedure} alist->hash-table alist equality-predicate [ hash-function ] arg @dots{}
  4802. Return a newly allocated hash table as if by @code{make-hash-table}
  4803. using @var{comparator} and the @var{args}. It is then initialized from
  4804. the associations of @var{alist}. Associations earlier in the list take
  4805. precedence over those that come later. The second form is for
  4806. compatibility with SRFI 69, and is deprecated.
  4807. @end deffn
  4808. @node SRFI-125 Predicates
  4809. @subsubsection SRFI-125 Predicates
  4810. @deffn {Scheme Procedure} hash-table? obj
  4811. Return @code{#t} if @var{obj} is a hash table, and @code{#f} otherwise.
  4812. (R6RS @code{hashtable?}; Common Lisp @code{hash-table-p})
  4813. @end deffn
  4814. @deffn {Scheme Procedure} hash-table-contains? hash-table key
  4815. @deffnx {Scheme Procedure} hash-table-exists? hash-table key
  4816. Return @code{#t} if there is any association to key in @var{hash-table},
  4817. and @code{#f} otherwise. Execute in amortized constant time. The
  4818. @code{hash-table-exists?} procedure is the same as
  4819. @code{hash-table-contains?}; it is provided for backward compatibility
  4820. with SRFI 69, and is deprecated. (R6RS @code{hashtable-contains?})
  4821. @end deffn
  4822. @deffn {Scheme Procedure} hash-table-empty? hash-table
  4823. Return @code{#t} if @var{hash-table} contains no associations, and
  4824. @code{#f} otherwise.
  4825. @end deffn
  4826. @deffn {Scheme Procedure} hash-table=? value-comparator hash-table@sub{1} hash-table@sub{2}
  4827. Return @code{#t} if @var{hash-table@sub{1}} and @var{hash-table@sub{2}}
  4828. have the same keys (in the sense of their common equality predicate) and
  4829. each key has the same value (in the sense of @var{value-comparator)},
  4830. and @code{#f} otherwise.
  4831. @end deffn
  4832. @deffn {Scheme Procedure} hash-table-mutable? hash-table
  4833. Return @code{#t} if @var{hash-table} is mutable. (R6RS
  4834. @code{hashtable-mutable?})
  4835. @end deffn
  4836. @node SRFI-125 Accessors
  4837. @subsubsection SRFI-125 Accessors
  4838. The following procedures, given a key, return the corresponding value.
  4839. @deffn {Scheme Procedure} hash-table-ref hash-table key [ failure [ success ] ]
  4840. Extract the value associated to key in @var{hash-table}, invoke the
  4841. procedure success on it, and return its result; if @var{success} is not
  4842. provided, then the value itself is returned. If @var{key} is not
  4843. contained in @var{hash-table} and @var{failure} is supplied, then
  4844. @var{failure} is called with no arguments and its result is returned.
  4845. Otherwise, it is an error. Execute in expected amortized constant time,
  4846. not counting the time to call the procedures. SRFI 69 does not support
  4847. the @var{success} procedure.
  4848. @end deffn
  4849. @deffn {Scheme Procedure} hash-table-ref/default hash-table key default
  4850. Semantically equivalent to, but may be more efficient than, the
  4851. following code:
  4852. @lisp
  4853. (hash-table-ref @var{hash-table} @var{key} (lambda () @var{default}))
  4854. @end lisp
  4855. (R6RS @code{hashtable-ref}; Common Lisp @code{gethash})
  4856. @end deffn
  4857. @node SRFI-125 Mutators
  4858. @subsubsection SRFI-125 Mutators
  4859. The following procedures alter the associations in a hash table either
  4860. unconditionally, or conditionally on the presence or absence of a
  4861. specified key. It is an error to add an association to a hash table
  4862. whose key does not satisfy the type test predicate of the comparator
  4863. used to create the hash table.
  4864. @deffn {Scheme Procedure} hash-table-set! hash-table arg @dots{}
  4865. Repeatedly mutates @code{hash-table}, creating new associations in it by
  4866. processing the arguments from left to right. The @var{args} alternate
  4867. between keys and values. Whenever there is a previous association for a
  4868. key, it is deleted. It is an error if the type check procedure of the
  4869. comparator of @var{hash-table}, when invoked on a key, does not return
  4870. @code{#t}. Likewise, it is an error if a key is not a valid argument to
  4871. the equality predicate of @var{hash-table}. Return an unspecified
  4872. value. Execute in expected amortized constant time per key.
  4873. SRFI 69, R6RS @code{hashtable-set!} and Common Lisp (@samp{setf
  4874. gethash}) do not handle multiple associations.
  4875. @end deffn
  4876. @deffn {Scheme Procedure} hash-table-delete! hash-table key @dots{}
  4877. Delete any association to each key in @var{hash-table} and returns the
  4878. number of keys that had associations. Execute in expected amortized
  4879. constant time per key. SRFI 69, R6RS @code{hashtable-delete!}, and
  4880. Common Lisp @var{remhash} do not handle multiple associations.
  4881. @end deffn
  4882. @deffn {Scheme Procedure} hash-table-intern! hash-table key failure
  4883. Effectively invoke @code{hash-table-ref} with the given arguments and
  4884. return what it returns. If @var{key} was not found in @var{hash-table},
  4885. its value is set to the result of calling @var{failure}. Execute in
  4886. expected amortized constant time.
  4887. @end deffn
  4888. @deffn {Scheme Procedure} hash-table-update! hash-table key updater [ failure [ success ] ]
  4889. Semantically equivalent to, but may be more efficient than, the
  4890. following code:
  4891. @lisp
  4892. (hash-table-set! @var{hash-table} @var{key}
  4893. (@var{updater} (hash-table-ref @var{hash-table} @var{key} @var{failure} @var{success})))
  4894. @end lisp
  4895. Execute in expected amortized constant time. Return an unspecified
  4896. value. (SRFI 69 and R6RS @code{hashtable-update!} do not support
  4897. the @var{success} procedure)
  4898. @end deffn
  4899. @deffn {Scheme Procedure} hash-table-update!/default hash-table key updater default
  4900. Semantically equivalent to, but may be more efficient than, the
  4901. following code:
  4902. @lisp
  4903. (hash-table-set! @var{hash-table} @var{key}
  4904. (@var{updater} (hash-table-ref/default @var{hash-table} @var{key} @var{default})))
  4905. @end lisp
  4906. Execute in expected amortized constant time. Return an unspecified value.
  4907. @end deffn
  4908. @deffn {Scheme Procedure} hash-table-pop! hash-table
  4909. Choose an arbitrary association from @var{hash-table} and removes it,
  4910. returning the key and value as two values. It is an error if
  4911. @var{hash-table} is empty.
  4912. @end deffn
  4913. @deffn {Scheme Procedure} hash-table-clear! hash-table
  4914. Delete all the associations from @var{hash-table}. (R6RS
  4915. @code{hashtable-clear!}; Common Lisp @code{clrhash}.)
  4916. @end deffn
  4917. @node SRFI-125 The whole hash table
  4918. @subsubsection SRFI-125 The whole hash table
  4919. These procedures process the associations of the hash table in an
  4920. unspecified order.
  4921. @deffn {Scheme Procedure} hash-table-size hash-table
  4922. Return the number of associations in @var{hash-table} as an exact
  4923. integer. Execute in constant time. (R6RS @code{hashtable-size}; Common
  4924. Lisp @code{hash-table-count}.)
  4925. @end deffn
  4926. @deffn {Scheme Procedure} hash-table-keys hash-table
  4927. Return a newly allocated list of all the keys in @var{hash-table}. R6RS
  4928. @code{hashtable-keys} returns a vector.
  4929. @end deffn
  4930. @deffn {Scheme Procedure} hash-table-values hash-table
  4931. Return a newly allocated list of all the keys in @var{hash-table}.
  4932. @end deffn
  4933. @deffn {Scheme Procedure} hash-table-entries hash-table
  4934. Return two values, a newly allocated list of all the keys in
  4935. @var{hash-table} and a newly allocated list of all the values in
  4936. @var{hash-table} in the corresponding order. R6RS
  4937. @code{hash-table-entries} returns vectors.
  4938. @end deffn
  4939. @deffn {Scheme Procedure} hash-table-find proc hash-table failure
  4940. For each association of @var{hash-table}, invoke @var{proc} on its key
  4941. and value. If @var{proc} returns true, then @code{hash-table-find}
  4942. returns what @var{proc} returns. If all the calls to @var{proc} return
  4943. @code{#f}, return the result of invoking the thunk @var{failure}.
  4944. @end deffn
  4945. @deffn {Scheme Procedure} hash-table-count pred hash-table
  4946. For each association of @var{hash-table}, invoke @var{pred} on its key
  4947. and value. Return the number of calls to @var{pred} which returned
  4948. true.
  4949. @end deffn
  4950. @node SRFI-125 Mapping and folding
  4951. @subsubsection SRFI-125 Mapping and folding
  4952. These procedures process the associations of the hash table in an
  4953. unspecified order.
  4954. @deffn {Scheme Procedure} hash-table-map proc comparator hash-table
  4955. Return a newly allocated hash table as if by @samp{(make-hash-table
  4956. comparator)}. Calls @var{proc} for every association in
  4957. @var{hash-table} with the value of the association. The key of the
  4958. association and the result of invoking @var{proc} are entered into the
  4959. new hash table. Note that this is not the result of lifting mapping
  4960. over the domain of hash tables, but it is considered more useful.
  4961. If @var{comparator} recognizes multiple keys in the @var{hash-table} as
  4962. equivalent, any one of such associations is taken.
  4963. @end deffn
  4964. @deffn {Scheme Procedure} hash-table-for-each proc hash-table
  4965. @deffnx {Scheme Procedure} hash-table-walk hash-table proc
  4966. Call @var{proc} for every association in @var{hash-table} with two
  4967. arguments: the key of the association and the value of the association.
  4968. The value returned by @var{proc} is discarded. Return an unspecified
  4969. value. The @code{hash-table-walk} procedure is equivalent to
  4970. @code{hash-table-for-each} with the arguments reversed, is provided for
  4971. backward compatibility with SRFI 69, and is deprecated. (Common
  4972. Lisp @code{maphash})
  4973. @end deffn
  4974. @deffn {Scheme Procedure} hash-table-map! proc hash-table
  4975. Call @var{proc} for every association in @var{hash-table} with two
  4976. arguments: the key of the association and the value of the association.
  4977. The value returned by @var{proc} is used to update the value of the
  4978. association. Return an unspecified value.
  4979. @end deffn
  4980. @deffn {Scheme Procedure} hash-table-map->list proc hash-table
  4981. Call @var{proc} for every association in @var{hash-table} with two
  4982. arguments: the key of the association and the value of the association.
  4983. The values returned by the invocations of @var{proc} are accumulated
  4984. into a list, which is returned.
  4985. @end deffn
  4986. @deffn {Scheme Procedure} hash-table-fold proc seed hash-table
  4987. @deffnx {Scheme Procedure} hash-table-fold hash-table proc seed
  4988. Call @var{proc} for every association in @var{hash-table} with three
  4989. arguments: the key of the association, the value of the association, and
  4990. an accumulated value @var{val}. @var{val} is the seed for the first
  4991. invocation of @var{proc}, and for subsequent invocations of @var{proc},
  4992. the returned value of the previous invocation. The value returned by
  4993. @code{hash-table-fold} is the return value of the last invocation of
  4994. @var{proc}. The order of arguments with @var{hash-table} as the first
  4995. argument is provided for SRFI 69 compatibility, and is deprecated.
  4996. @end deffn
  4997. @deffn {Scheme Procedure} hash-table-prune! proc hash-table
  4998. Call @var{proc} for every association in @var{hash-table} with two
  4999. arguments, the key and the value of the association, and removes all
  5000. associations from @var{hash-table} for which @var{proc} returns true.
  5001. Return an unspecified value.
  5002. @end deffn
  5003. @node SRFI-125 Copying and conversion
  5004. @subsubsection SRFI-125 Copying and conversion
  5005. @deffn {Scheme Procedure} hash-table-copy hash-table [ mutable? ]
  5006. Return a newly allocated hash table with the same properties and
  5007. associations as @var{hash-table}. If the second argument is present and
  5008. is true, the new hash table is mutable. Otherwise it is immutable.
  5009. SRFI 69 @code{hash-table-copy} does not support a second argument.
  5010. (R6RS @code{hashtable-copy})
  5011. @end deffn
  5012. @deffn {Scheme Procedure} hash-table-empty-copy hash-table
  5013. Return a newly allocated mutable hash table with the same properties as
  5014. @var{hash-table}, but with no associations.
  5015. @end deffn
  5016. @deffn {Scheme Procedure} hash-table->alist hash-table
  5017. Return an alist with the same associations as @var{hash-table} in an
  5018. unspecified order.
  5019. @end deffn
  5020. @node SRFI-125 Hash tables as sets
  5021. @subsubsection SRFI-125 Hash tables as sets
  5022. @deffn {Scheme Procedure} hash-table-union! hash-table@sub{1} hash-table@sub{2}
  5023. @deffnx {Scheme Procedure} hash-table-merge! hash-table@sub{1} hash-table@sub{2}
  5024. Add the associations of @var{hash-table@sub{2}} to
  5025. @var{hash-table@sub{1}} and return @var{hash-table@sub{1}}. If a key
  5026. appears in both hash tables, its value is set to the value appearing in
  5027. @var{hash-table@sub{1}}. Return @var{hash-table@sub{1}}. The
  5028. @code{hash-table-merge!} procedure is the same as
  5029. @code{hash-table-union!}, is provided for compatibility with SRFI 69,
  5030. and is deprecated.
  5031. @end deffn
  5032. @deffn {Scheme Procedure} hash-table-intersection! hash-table@sub{1} hash-table@sub{2}
  5033. Delete the associations from @var{hash-table@sub{1}} whose keys don't
  5034. also appear in @var{hash-table@sub{2}} and return
  5035. @var{hash-table@sub{1}}.
  5036. @end deffn
  5037. @deffn {Scheme Procedure} hash-table-difference! hash-table@sub{1} hash-table@sub{2}
  5038. Delete the associations of @var{hash-table@sub{1}} whose keys are also
  5039. present in @var{hash-table@sub{2}} and return @var{hash-table@sub{1}}.
  5040. @end deffn
  5041. @deffn {Scheme Procedure} hash-table-xor! hash-table@sub{1} hash-table@sub{2}
  5042. Delete the associations of @var{hash-table@sub{1}} whose keys are also
  5043. present in @var{hash-table@sub{2}}, and then adds the associations of
  5044. @var{hash-table@sub{2}} whose keys are not present in
  5045. @var{hash-table@sub{1}} to @var{hash-table@sub{1}}. Return
  5046. @var{hash-table@sub{1}}.
  5047. @end deffn
  5048. @node SRFI-125 Hash functions and reflectivity
  5049. @subsubsection SRFI-125 Hash functions and reflectivity
  5050. These functions are made part of this SRFI solely for compatibility with
  5051. SRFI 69, and are deprecated.
  5052. @quotation note
  5053. While the SRFI 125 specifies that these deprecated procedures should be
  5054. exported using their original names, which forces its users to rename
  5055. these procedures to something else to avoid clashing with the SRFI 126
  5056. and SRFI 128 variants that should be preferred instead, Guile exports
  5057. them with the @code{deprecated:} prefix.
  5058. @end quotation
  5059. @deffn {Scheme Procedure} deprecated:hash obj [ arg ]
  5060. The same as SRFI 128's @code{default-hash} procedure, except that it
  5061. must accept (and should ignore) an optional second argument.
  5062. @end deffn
  5063. @deffn {Scheme Procedure} deprecated:string-hash obj [ arg ]
  5064. Similar to SRFI 128's @code{string-hash} procedure, except that it must
  5065. accept (and should ignore) an optional second argument. It is
  5066. incompatible with the procedure of the same name exported by SRFI 128
  5067. and SRFI 126.
  5068. @end deffn
  5069. @deffn {Scheme Procedure} deprecated:hash-by-identity obj [ arg ]
  5070. The same as SRFI 128's @code{default-hash} procedure, except that it
  5071. must accept (and should ignore) an optional second argument.
  5072. @end deffn
  5073. @deffn {Scheme Procedure} deprecated:hash-table-equivalence-function hash-table
  5074. Return the equivalence procedure used to create @var{hash-table}.
  5075. @end deffn
  5076. @deffn {Scheme Procedure} deprecated:hash-table-hash-function hash-table
  5077. Return the hash function used to create @var{hash-table}.
  5078. @end deffn
  5079. @node SRFI-126
  5080. @subsection SRFI-126 R6RS-based hash tables
  5081. @cindex SRFI-126
  5082. @cindex hash tables, r6rs-based
  5083. @uref{http://srfi.schemers.org/srfi-126/srfi-126.html, SRFI-126}
  5084. provides hash tables API that takes the R6RS hash tables API as a basis
  5085. and makes backwards compatible additions such as support for weak hash
  5086. tables, external representation, API support for double hashing
  5087. implementations, and utility procedures. As an alternative to SRFI 125,
  5088. it builds on the R6RS hash tables API instead of SRFI 69, with only
  5089. fully backwards compatible additions such as weak and ephemeral hash
  5090. tables, an external representation, and API support for hashing
  5091. strategies that require a pair of hash functions. This SRFI does not
  5092. attempt to specify thread-safety because typical multi-threaded
  5093. use-cases will most likely involve locking more than just accesses and
  5094. mutations of hash tables.
  5095. @noindent
  5096. The R6RS hash tables API is favored over SRFI 69 because the latter
  5097. contains a crucial flaw: exposing the hash functions for the @code{eq?}
  5098. and @code{eqv?} procedures is a hindrance for Scheme implementations
  5099. with a moving garbage collector. SRFI 125 works around this by allowing
  5100. the user-provided hash function passed to @code{make-hash-table} to be
  5101. ignored by the implementation, and allowing the
  5102. @code{hash-table-hash-function} procedure to return @code{#f} instead of
  5103. the hash function passed to @code{make-hash-table}. R6RS avoids the
  5104. issue by providing dedicated constructors for @code{eq?} and @code{eqv?}
  5105. based hash tables, and returning @code{#f} when their hash function is
  5106. queried.
  5107. While the SRFI is based on the R6RS hash tables API instead of SRFI 69,
  5108. the provided utility procedures nevertheless make it relatively
  5109. straightforward to change code written for SRFI 69 to use the API
  5110. specified herein. The utility procedures provided by this SRFI in
  5111. addition to the R6RS API may be categorized as follows:
  5112. @table @asis
  5113. @item Constructors
  5114. alist->eq-hashtable, alist->eqv-hashtable, alist->hashtable
  5115. @item Access and mutation
  5116. hashtable-lookup, hashtable-intern!
  5117. @item Copying
  5118. hashtable-empty-copy
  5119. @item Key/value collections
  5120. hashtable-values, hashtable-key-list, hashtable-value-list,
  5121. hashtable-entry-lists
  5122. @item Iteration
  5123. hashtable-walk, hashtable-update-all!, hashtable-prune!,
  5124. hashtable-merge!, hashtable-sum, hashtable-map->lset, hashtable-find
  5125. @item Miscellaneous
  5126. hashtable-empty?, hashtable-pop!, hashtable-inc!, hashtable-dec!
  5127. @end table
  5128. Additionally, this specification adheres to the R7RS rule of specifying
  5129. a single return value for procedures which don't have meaningful return
  5130. values.
  5131. @menu
  5132. * SRFI-126 API::
  5133. * SRFI-126 Constructors::
  5134. * SRFI-126 Procedures::
  5135. * SRFI-126 Inspection::
  5136. * SRFI-126 Hash functions::
  5137. @end menu
  5138. @node SRFI-126 API
  5139. @subsubsection SRFI-126 API
  5140. The @code{(srfi srfi-126)} library provides a set of operations on hash
  5141. tables. A hash table is of a disjoint type that associates keys with
  5142. values. Any object can be used as a key, provided a hash function or a
  5143. pair of hash functions, and a suitable equivalence function, are
  5144. available. A hash function is a procedure that maps keys to
  5145. non-negative exact integer objects. It is the programmer's
  5146. responsibility to ensure that the hash functions are compatible with the
  5147. equivalence function, which is a procedure that accepts two keys and
  5148. returns true if they are equivalent and @code{#f} otherwise. Standard
  5149. hash tables for arbitrary objects based on the @code{eq?} and
  5150. @code{eqv?} predicates (see R7RS section on “Equivalence predicates”)
  5151. are provided. Also, hash functions for arbitrary objects, strings, and
  5152. symbols are provided.
  5153. Hash tables can store their key, value, or key and value weakly.
  5154. Storing an object weakly means that the storage location of the object
  5155. does not count towards the total storage locations in the program which
  5156. refer to the object, meaning the object can be reclaimed as soon as no
  5157. non-weak storage locations referring to the object remain. Weakly
  5158. stored objects referring to each other in a cycle will be reclaimed as
  5159. well if none of them are referred to from outside the cycle. When a
  5160. weakly stored object is reclaimed, associations in the hash table which
  5161. have the object as their key or value are deleted.
  5162. Hash tables can also store their key and value in ephemeral storage
  5163. pairs. The objects in an ephemeral storage pair are stored weakly, but
  5164. both protected from reclamation as long as there remain non-weak
  5165. references to the first object from outside the ephemeral storage pair.
  5166. In particular, an @code{ephemeral-key} hash table (where the keys are
  5167. the first objects in the ephemeral storage pairs), with an association
  5168. mapping an element of a vector to the vector itself, may delete said
  5169. association when no non-weak references remain to the vector nor its
  5170. element in the rest of the program. If it were a @code{weak-key} hash
  5171. table, the reference to the key from within the vector would cyclically
  5172. protect the key and value from reclamation, even when no non-weak
  5173. references to the key and value remained from outside the hash table.
  5174. At the absence of such references between the key and value,
  5175. @code{ephemeral-key} and @code{ephemeral-value} hash tables behave
  5176. effectively equivalent to @code{weak-key} and @code{weak-value} hash
  5177. tables.
  5178. @code{ephemeral-key-and-value} hash tables use a pair of ephemeral
  5179. storage pairs for each association: one where the key is the first
  5180. object and one where the value is. This means that the key and value
  5181. are protected from reclamation until no references remain to neither the
  5182. key nor value from outside the hash table. In contrast, a
  5183. @code{weak-key-and-value} hash table will delete an association as soon
  5184. as either the key or value is reclaimed.
  5185. This document uses the @var{hashtable} parameter name for arguments that
  5186. must be hash tables, and the @var{key} parameter name for arguments that
  5187. must be hash table keys.
  5188. @node SRFI-126 Constructors
  5189. @subsubsection SRFI-126 Constructors
  5190. @deffn {Scheme Procedure} make-eq-hashtable
  5191. @deffnx {Scheme Procedure} make-eq-hashtable capacity
  5192. @deffnx {Scheme Procedure} make-eq-hashtable capacity weakness
  5193. Return a newly allocated mutable hash table that accepts arbitrary
  5194. objects as keys, and compares those keys with @code{eq?}. If the
  5195. @var{capacity} argument is provided and not @code{#f}, it must be an
  5196. exact non-negative integer and the initial capacity of the hash table is
  5197. set to approximately @var{capacity} elements. The @var{weakness}
  5198. argument, if provided, must be one of: @code{#f}, @code{weak-key},
  5199. @code{weak-value}, @code{weak-key-and-value}, @code{ephemeral-key},
  5200. @code{ephemeral-value}, and @code{ephemeral-key-and-value}, and
  5201. determines the weakness or ephemeral status for the keys and values in
  5202. the hash table.
  5203. @end deffn
  5204. @deffn {Scheme Procedure} make-eqv-hashtable
  5205. @deffnx {Scheme Procedure} make-eqv-hashtable capacity
  5206. @deffnx {Scheme Procedure} make-eqv-hashtable capacity weakness
  5207. Return a newly allocated mutable hash table that accepts arbitrary
  5208. objects as keys, and compares those keys with @code{eqv?}. The
  5209. semantics of the optional arguments are as in @code{make-eq-hashtable}.
  5210. @end deffn
  5211. @deffn {Scheme Procedure} make-hashtable hash equiv
  5212. @deffnx {Scheme Procedure} make-hashtable hash equiv capacity
  5213. @deffnx {Scheme Procedure} make-hashtable hash equiv capacity weakness
  5214. If @var{hash} is @code{#f} and @var{equiv} is the @code{eq?} procedure,
  5215. the semantics of @code{make-eq-hashtable} apply to the rest of the
  5216. arguments. If @var{hash} is @code{#f} and @var{equiv} is the
  5217. @code{eqv?} procedure, the semantics of @code{make-eqv-hashtable} apply
  5218. to the rest of the arguments.
  5219. Otherwise, @var{hash} must be a pair of hash functions or a hash
  5220. function, and @var{equiv} must be a procedure. @var{equiv} should
  5221. accept two keys as arguments and return a single value. None of the
  5222. procedures should mutate the hash table returned by
  5223. @code{make-hashtable}. The @code{make-hashtable} procedure returns a
  5224. newly allocated mutable hash table using the function(s) specified by
  5225. @var{hash} as its hash function(s), and @var{equiv} as the equivalence
  5226. function used to compare keys. The semantics of the remaining arguments
  5227. are as in @code{make-eq-hashtable} and @code{make-eqv-hashtable}.
  5228. The @var{hash} functions and @var{equiv} should behave like pure
  5229. functions on the domain of keys. For example, the @code{string-hash}
  5230. and @code{string=?} procedures are permissible only if all keys are
  5231. strings and the contents of those strings are never changed so long as
  5232. any of them continues to serve as a key in the hash table. Furthermore,
  5233. any pair of keys for which @var{equiv} returns true should be hashed to
  5234. the same exact integer objects by the given @var{hash} function(s).
  5235. @quotation Note
  5236. Hash tables are allowed to cache the results of calling a hash function
  5237. and equivalence function, so programs cannot rely on a hash function
  5238. being called for every lookup or update. Furthermore any hash table
  5239. operation may call a hash function more than once.
  5240. @end quotation
  5241. @end deffn
  5242. @deffn {Scheme Procedure} alist->eq-hashtable alist
  5243. @deffnx {Scheme Procedure} alist->eq-hashtable capacity alist
  5244. @deffnx {Scheme Procedure} alist->eq-hashtable capacity weakness alist
  5245. The semantics of this procedure can be described as:
  5246. @lisp
  5247. (let ((ht (make-eq-hashtable @var{capacity} @var{weakness})))
  5248. (for-each (lambda (entry)
  5249. (hashtable-set! ht (car entry) (cdr entry)))
  5250. (reverse alist))
  5251. ht)
  5252. @end lisp
  5253. where omission of the @var{capacity} and/or @var{weakness} arguments
  5254. corresponds to their omission in the call to @code{make-eq-hashtable}.
  5255. @end deffn
  5256. @deffn {Scheme Procedure} alist->eqv-hashtable alist
  5257. @deffnx {Scheme Procedure} alist->eqv-hashtable capacity alist
  5258. @deffnx {Scheme Procedure} alist->eqv-hashtable capacity weakness alist
  5259. This procedure is equivalent to @code{alist->eq-hashtable} except that
  5260. @code{make-eqv-hashtable} is used to construct the hash table.
  5261. @end deffn
  5262. @deffn {Scheme Procedure} alist->hashtable hash equiv alist
  5263. @deffnx {Scheme Procedure} alist->hashtable hash equiv capacity alist
  5264. @deffnx {Scheme Procedure} alist->hashtable hash equiv capacity weakness alist
  5265. This procedure is equivalent to @code{alist->eq-hashtable} except that
  5266. @code{make-hashtable} is used to construct the hash table, with the
  5267. given @var{hash} and @var{equiv} arguments.
  5268. @end deffn
  5269. @deffn {Scheme Syntax} weakness weakness-symbol
  5270. The @var{weakness-symbol} must correspond to one of the non-#f values
  5271. accepted for the @var{weakness} argument of the constructor procedures,
  5272. that is, @code{'weak-key}, @code{'weak-value},
  5273. @code{'weak-key-and-value}, @code{'ephemeral-key},
  5274. @code{'ephemeral-value}, or @code{'ephemeral-key-and-value}. Given such
  5275. a symbol, it is returned as a datum. Passing any other argument is an
  5276. error.
  5277. @end deffn
  5278. @node SRFI-126 Procedures
  5279. @subsubsection SRFI-126 Procedures
  5280. @deffn {Scheme Procedure} hashtable? obj
  5281. Return @code{#t} if @var{obj} is a hash table, @code{#f} otherwise.
  5282. @end deffn
  5283. @deffn {Scheme Procedure} hashtable-size hashtable
  5284. Return the number of keys contained in @var{hashtable} as an exact
  5285. integer object.
  5286. @end deffn
  5287. @deffn {Scheme Procedure} hashtable-ref hashtable key
  5288. @deffnx {Scheme Procedure} hashtable-ref hashtable key default
  5289. Return the value in @var{hashtable} associated with @var{key}. If
  5290. @var{hashtable} does not contain an association for key, @var{default}
  5291. is returned. If @var{hashtable} does not contain an association for key
  5292. and the @var{default} argument is not provided, an error is signaled.
  5293. @end deffn
  5294. @deffn {Scheme Procedure} hashtable-set! hashtable key obj
  5295. Change @var{hashtable} to associate @var{key} with @var{obj}, adding a
  5296. new association or replacing any existing association for @var{key}, and
  5297. return an unspecified value.
  5298. @end deffn
  5299. @deffn {Scheme Procedure} hashtable-delete! hashtable key
  5300. Remove any association for @var{key} within @var{hashtable} and return
  5301. an unspecified value.
  5302. @end deffn
  5303. @deffn {Scheme Procedure} hashtable-contains? hashtable key
  5304. Return @code{#t} if @var{hashtable} contains an association for
  5305. @var{key}, @code{#f} otherwise.
  5306. @end deffn
  5307. @deffn {Scheme Procedure} hashtable-lookup hashtable key
  5308. Return two values: the value in @var{hashtable} associated with
  5309. @var{key} or an unspecified value if there is none, and a boolean
  5310. indicating whether an association was found.
  5311. @end deffn
  5312. @deffn {Scheme Procedure} hashtable-update! hashtable key proc
  5313. @deffnx {Scheme Procedure} hashtable-update! hashtable key proc default
  5314. @var{proc} should accept one argument, should return a single value, and
  5315. should not mutate hashtable. The @code{hashtable-update!} procedure
  5316. applies @var{proc} to the value in @var{hashtable} associated with
  5317. @var{key}, or to @var{default} if @var{hashtable} does not contain an
  5318. association for @var{key}. The @var{hashtable} is then changed to
  5319. associate @var{key} with the value returned by @var{proc}. If
  5320. @var{hashtable} does not contain an association for @var{key} and the
  5321. @var{default} argument is not provided, an error should be signaled.
  5322. @var{hashtable-update!} returns the value of the new association for
  5323. @var{key} in @var{hashtable}.
  5324. @end deffn
  5325. @deffn {Scheme Procedure} hashtable-intern! hashtable key default-proc
  5326. @var{default-proc} should accept zero arguments, should return a single
  5327. value, and should not mutate @var{hashtable}. The
  5328. @code{hashtable-intern!} procedure returns the association for key in
  5329. @var{hashtable} if there is one, otherwise it calls @var{default-proc}
  5330. with zero arguments, associates its return value with @var{key} in
  5331. @var{hashtable}, and returns that value.
  5332. @end deffn
  5333. @deffn {Scheme Procedure} hashtable-copy hashtable
  5334. @deffnx {Scheme Procedure} hashtable-copy hashtable mutable
  5335. @deffnx {Scheme Procedure} hashtable-copy hashtable mutable weakness
  5336. Return a copy of @var{hashtable}. If the @var{mutable} argument is
  5337. provided and is true, the returned @var{hashtable} is mutable; otherwise
  5338. it is immutable. If the optional @var{weakness} argument is provided,
  5339. it determines the weakness of the copy, otherwise the weakness attribute
  5340. of @var{hashtable} is used.
  5341. @end deffn
  5342. @deffn {Scheme Procedure} hashtable-clear! hashtable
  5343. @deffnx {Scheme Procedure} hashtable-clear! hashtable capacity
  5344. Remove all associations from @var{hashtable} and return an unspecified
  5345. value. If @var{capacity} is provided and not @code{#f}, it must be an
  5346. exact non-negative integer and the current capacity of the
  5347. @var{hashtable} is reset to approximately @var{capacity} elements.
  5348. @end deffn
  5349. @deffn {Scheme Procedure} hashtable-empty-copy hashtable
  5350. @deffnx {Scheme Procedure} hashtable-empty-copy hashtable capacity
  5351. Return a newly allocated mutable @var{hashtable} that has the same hash
  5352. and equivalence functions and weakness attribute as @var{hashtable}.
  5353. The @var{capacity} argument may be @code{#t} to set the initial capacity
  5354. of the copy to approximately @samp{(hashtable-size @var{hashtable})}
  5355. elements; otherwise the semantics of @code{make-eq-hashtable} apply to
  5356. the @var{capacity} argument.
  5357. @end deffn
  5358. @deffn {Scheme Procedure} hashtable-keys hashtable
  5359. Return a vector of all keys in @var{hashtable}. The order of the vector
  5360. is unspecified.
  5361. @end deffn
  5362. @deffn {Scheme Procedure} hashtable-values hashtable
  5363. Return a vector of all values in @var{hashtable}. The order of the
  5364. vector is unspecified, and is not guaranteed to match the order of keys
  5365. in the result of @code{hashtable-keys}.
  5366. @end deffn
  5367. @deffn {Scheme Procedure} hashtable-entries hashtable
  5368. Return two values, a vector of the keys in @var{hashtable}, and a vector
  5369. of the corresponding values.
  5370. @end deffn
  5371. @deffn {Scheme Procedure} hashtable-key-list hashtable
  5372. Return a list of all keys in @var{hashtable}. The order of the list is
  5373. unspecified.
  5374. @end deffn
  5375. @deffn {Scheme Procedure} hashtable-value-list hashtable
  5376. Return a list of all values in @var{hashtable}. The order of the list
  5377. is unspecified, and is not guaranteed to match the order of keys in the
  5378. result of @code{hashtable-key-list}.
  5379. @end deffn
  5380. @deffn {Scheme Procedure} hashtable-entry-lists hashtable
  5381. Return two values, a list of the keys in @var{hashtable}, and a list of
  5382. the corresponding values.
  5383. @end deffn
  5384. @deffn {Scheme Procedure} hashtable-walk hashtable proc
  5385. @var{proc} should accept two arguments, and should not mutate
  5386. @var{hashtable}. The @code{hashtable-walk} procedure applies @var{proc}
  5387. once for every association in @var{hashtable}, passing it the key and
  5388. value as arguments. The order in which @var{proc} is applied to the
  5389. associations is unspecified. Return values of @var{proc} are ignored.
  5390. @code{hashtable-walk} returns an unspecified value.
  5391. @end deffn
  5392. @deffn {Scheme Procedure} hashtable-update-all! hashtable proc
  5393. @var{proc} should accept two arguments, should return a single value,
  5394. and should not mutate @var{hashtable}. The @code{hashtable-update-all!}
  5395. procedure applies @var{proc} once for every association in
  5396. @var{hashtable}, passing it the key and value as arguments, and changes
  5397. the value of the association to the return value of @var{proc}. The
  5398. order in which @var{proc} is applied to the associations is unspecified.
  5399. @code{hashtable-update-all!} returns an unspecified value.
  5400. @end deffn
  5401. @deffn {Scheme Procedure} hashtable-prune! hashtable proc
  5402. @var{proc} should accept two arguments, should return a single value,
  5403. and should not mutate @var{hashtable}. The @code{hashtable-prune!}
  5404. procedure applies @var{proc} once for every association in
  5405. @var{hashtable}, passing it the key and value as arguments, and deletes
  5406. the association if @var{proc} returns a true value. The order in which
  5407. @var{proc} is applied to the associations is unspecified.
  5408. @code{hashtable-prune!} returns an unspecified value.
  5409. @end deffn
  5410. @deffn {Scheme Procedure} hashtable-merge! hashtable-dest hashtable-source
  5411. Effectively equivalent to:
  5412. @lisp
  5413. (begin
  5414. (hashtable-walk @var{hashtable-source}
  5415. (lambda (key value)
  5416. (hashtable-set! @var{hashtable-dest} key value)))
  5417. hashtable-dest)
  5418. @end lisp
  5419. @end deffn
  5420. @deffn {Scheme Procedure} hashtable-sum hashtable init proc
  5421. @var{proc} should accept three arguments, should return a single value,
  5422. and should not mutate @var{hashtable}. The @code{hashtable-sum}
  5423. procedure accumulates a result by applying @var{proc} once for every
  5424. association in @var{hashtable}, passing it as arguments: the key, the
  5425. value, and the result of the previous application or @var{init} at the
  5426. first application. The order in which @var{proc} is applied to the
  5427. associations is unspecified.
  5428. @end deffn
  5429. @deffn {Scheme Procedure} hashtable-map->lset hashtable proc
  5430. @var{proc} should accept two arguments, should return a single value,
  5431. and should not mutate @var{hashtable}. The @code{hashtable-map->lset}
  5432. procedure applies @var{proc} once for every association in
  5433. @var{hashtable}, passing it the key and value as arguments, and
  5434. accumulates the returned values into a list. The order in which
  5435. @var{proc} is applied to the associations, and the order of the results
  5436. in the returned list, are unspecified.
  5437. @quotation note
  5438. This procedure can trivially imitate @code{hashtable->alist}:
  5439. @samp{(hashtable-map->lset @var{hashtable} cons)}.
  5440. @end quotation
  5441. @quotation warning
  5442. Since the order of the results is unspecified, the returned list should
  5443. be treated as a set or multi-set. Relying on the order of results will
  5444. produce unpredictable programs.
  5445. @end quotation
  5446. @end deffn
  5447. @deffn {Scheme Procedure} hashtable-find hashtable proc
  5448. @var{proc} should accept two arguments, should return a single value,
  5449. and should not mutate @var{hashtable}. The @code{hashtable-find}
  5450. procedure applies @var{proc} to associations in @var{hashtable} in an
  5451. unspecified order until one of the applications returns a true value or
  5452. the associations are exhausted. Three values are returned: the key and
  5453. value of the matching association or two unspecified values if none
  5454. matched, and a boolean indicating whether any association matched.
  5455. @end deffn
  5456. @deffn {Scheme Procedure} hashtable-empty? hashtable
  5457. Effectively equivalent to @samp{(zero? (hashtable-size @var{hashtable}))}.
  5458. @end deffn
  5459. @deffn {Scheme Procedure} hashtable-pop! hashtable
  5460. Effectively equivalent to:
  5461. @lisp
  5462. (let-values (((key value found?)
  5463. (hashtable-find @var{hashtable} (lambda (k v) #t))))
  5464. (when (not found?)
  5465. (error))
  5466. (hashtable-delete! @var{hashtable} key)
  5467. (values key value))
  5468. @end lisp
  5469. @end deffn
  5470. @deffn {Scheme Procedure} hashtable-inc! hashtable key
  5471. @deffnx {Scheme Procedure} hashtable-inc! hashtable key number
  5472. Effectively equivalent to:
  5473. @lisp
  5474. (hashtable-update! @var{hashtable} @var{key} (lambda (v) (+ v @var{number})) 0)
  5475. @end lisp
  5476. where @var{number} is 1 when not provided.
  5477. @end deffn
  5478. @deffn {Scheme Procedure} hashtable-dec! hashtable key
  5479. @deffnx {Scheme Procedure} hashtable-dec! hashtable key number
  5480. Effectively equivalent to:
  5481. @lisp
  5482. (hashtable-update! @var{hashtable} @var{key} (lambda (v) (- v @var{number})) 0)
  5483. @end lisp
  5484. where @var{number} is 1 when not provided.
  5485. @end deffn
  5486. @node SRFI-126 Inspection
  5487. @subsubsection SRFI-126 Inspection
  5488. @deffn {Scheme Procedure} hashtable-equivalence-function hashtable
  5489. Return the equivalence function used by @var{hashtable} to compare
  5490. keys. For hash tables created with @code{make-eq-hashtable} and
  5491. @code{make-eqv-hashtable}, returns @code{eq?} and @code{eqv?}
  5492. respectively.
  5493. @end deffn
  5494. @deffn {Scheme Procedure} hashtable-hash-function hashtable
  5495. Return the hash function(s) used by @var{hashtable}, that is, either a
  5496. procedure, or a pair of procedures. For hash tables created by
  5497. @code{make-eq-hashtable} or @code{make-eqv-hashtable}, @code{#f} is
  5498. returned.
  5499. @end deffn
  5500. @deffn {Scheme Procedure} hashtable-weakness hashtable
  5501. Return the weakness attribute of @var{hashtable}. The same values that
  5502. are accepted as the weakness argument in the constructor procedures are
  5503. returned. This procedure may expose the fact that @code{weak-key} and
  5504. @code{weak-value} hash tables are implemented as @var{ephemeral-key} and
  5505. @var{ephemeral-value} hash tables, returning symbols indicating the
  5506. latter even when the former were used to construct the hash table.
  5507. @end deffn
  5508. @deffn {Scheme Procedure} hashtable-mutable? hashtable
  5509. Return @code{#t} if @var{hashtable} is mutable, otherwise @code{#f}.
  5510. @end deffn
  5511. @node SRFI-126 Hash functions
  5512. @subsubsection SRFI-126 Hash functions
  5513. The @code{equal-hash}, @code{string-hash}, and @code{string-ci-hash}
  5514. procedures of this section are acceptable as the hash functions of a
  5515. hash table only if the keys on which they are called are not mutated
  5516. while they remain in use as keys in the hash table.
  5517. An implementation may initialize its hash functions with a random salt
  5518. value at program startup, meaning they are not guaranteed to return the
  5519. same values for the same inputs across multiple runs of a program. If
  5520. however the environment variable @env{SRFI_126_HASH_SEED} is set to a
  5521. non-empty string before program startup, then the salt value is derived
  5522. from that string in a deterministic manner.
  5523. @deffn {Scheme Syntax} hash-salt
  5524. Expand to a form evaluating to an exact non-negative integer that lies
  5525. within the fixnum range of the implementation. The value the expanded
  5526. form evaluates to remains constant throughout the execution of the
  5527. program. It is random for every run of the program, except when the
  5528. environment variable @env{SRFI_126_HASH_SEED} is set to a non-empty
  5529. string before program startup, in which case it is derived from the
  5530. value of that environment variable in a deterministic manner.
  5531. @end deffn
  5532. @deffn {Scheme Procedure} equal-hash obj
  5533. Return an integer hash value for @var{obj}, based on its structure and
  5534. current contents. This hash function is suitable for use with
  5535. @code{equal?} as an equivalence function.
  5536. @end deffn
  5537. @deffn {Scheme Procedure} string-hash string
  5538. Return an integer hash value for @var{string}, based on its current
  5539. contents. This hash function is suitable for use with @code{string=?}
  5540. as an equivalence function.
  5541. @end deffn
  5542. @deffn {Scheme Procedure} string-ci-hash string
  5543. Return an integer hash value for @var{string} based on its current
  5544. contents, ignoring case. This hash function is suitable for use with
  5545. @code{string-ci=?} as an equivalence function.
  5546. @end deffn
  5547. @deffn {Scheme Procedure} symbol-hash symbol
  5548. Return an integer hash value for @var{symbol}.
  5549. @end deffn
  5550. @node SRFI-128
  5551. @subsection Comparators
  5552. @cindex SRFI-128
  5553. @cindex comparators
  5554. @uref{https://srfi.schemers.org/srfi-128/srfi-128.html, SRFI-128}
  5555. provides comparators, which bundle a @emph{type test predicate}, an
  5556. @emph{equality predicate}, an @emph{ordering predicate}, and a @emph{hash
  5557. function} into a single Scheme object. By packaging these procedures
  5558. together, they can be treated as a single item for use in the
  5559. implementation of data structures.
  5560. @noindent
  5561. The four procedures above have complex dependencies on one another, and
  5562. it is inconvenient to have to pass them individually to other procedures
  5563. that might or might not make use of all of them. For example, a set
  5564. implementation by its nature requires only an equality predicate, but if
  5565. it is implemented using a hash table, an appropriate hash function is
  5566. also required if the implementation does not provide one; alternatively,
  5567. if it is implemented using a tree, procedures specifying a total order
  5568. are required. By passing a comparator rather than a bare equality
  5569. predicate, the set implementation can make use of whatever procedures
  5570. are available and useful to it.
  5571. @subheading Definitions
  5572. A comparator is an object of a disjoint type. It is a bundle of
  5573. procedures that are useful for comparing two objects in a total order.
  5574. It is an error if any of the procedures have side effects. There are
  5575. four procedures in the bundle:
  5576. @enumerate
  5577. @item
  5578. The @emph{type test predicate} returns @code{#t} if its argument has the
  5579. correct type to be passed as an argument to the other three procedures,
  5580. and @code{#f} otherwise.
  5581. @item
  5582. The @emph{equality predicate} returns @code{#t} if the two objects are the
  5583. same in the sense of the comparator, and @code{#f} otherwise. It is the
  5584. programmer's responsibility to ensure that it is reflexive, symmetric,
  5585. transitive, and can handle any arguments that satisfy the type test
  5586. predicate.
  5587. @item
  5588. The @emph{ordering predicate} returns @code{#t} if the first object
  5589. precedes the second in a total order, and @code{#f} otherwise. Note
  5590. that if it is true, the equality predicate must be false. It is the
  5591. programmer's responsibility to ensure that it is irreflexive,
  5592. anti-symmetric, transitive, and can handle any arguments that satisfy
  5593. the type test predicate.
  5594. @item
  5595. The @emph{hash function} takes an object and returns an exact non-negative
  5596. integer. It is the programmer's responsibility to ensure that it can
  5597. handle any argument that satisfies the type test predicate, and that it
  5598. returns the same value on two objects if the equality predicate says
  5599. they are the same (but not necessarily the converse).
  5600. @end enumerate
  5601. It is also the programmer's responsibility to ensure that all four
  5602. procedures provide the same result whenever they are applied to the same
  5603. object(s) (in the sense of @code{eqv?}), unless the object(s) have been
  5604. mutated since the last invocation.
  5605. @subheading Limitations
  5606. The comparator objects defined in SRFI 128 are not applicable to
  5607. circular structures or to NaNs, or to objects containing any of these.
  5608. Attempts to pass any such objects to any procedure defined here, or to
  5609. any procedure that is part of a comparator defined here, is an error
  5610. except as otherwise noted.
  5611. @menu
  5612. * SRFI-128 Predicates::
  5613. * SRFI-128 Constructors::
  5614. * SRFI-128 Standard hash functions::
  5615. * SRFI-128 Bounds and salt::
  5616. * SRFI-128 Default comparators::
  5617. * SRFI-128 Accessors and Invokers::
  5618. * SRFI-128 Comparison predicates::
  5619. * SRFI-128 Syntax::
  5620. @end menu
  5621. @node SRFI-128 Predicates
  5622. @subsubsection SRFI-128 Predicates
  5623. @deffn {Scheme Procedure} comparator? obj
  5624. Return @code{#t} if @var{obj} is a comparator, and @code{#f} otherwise.
  5625. @end deffn
  5626. @deffn {Scheme Procedure} comparator-ordered? comparator
  5627. Return @code{#t} if @var{comparator} has a supplied ordering predicate,
  5628. and @code{#f} otherwise.
  5629. @end deffn
  5630. @deffn {Scheme Procedure} comparator-hashable? comparator
  5631. Return @code{#t} if @var{comparator} has a supplied hash function, and
  5632. @code{#f} otherwise.
  5633. @end deffn
  5634. @node SRFI-128 Constructors
  5635. @subsubsection SRFI-128 Constructors
  5636. The following comparator constructors all supply appropriate type test
  5637. predicates, equality predicates, ordering predicates, and hash functions
  5638. based on the supplied arguments. They are allowed to cache their
  5639. results: they need not return a newly allocated object, since
  5640. comparators are pure and functional. In addition, the procedures in a
  5641. comparator are likewise pure and functional.
  5642. @deffn {Scheme Procedure} make-comparator type-test equality ordering hash
  5643. Return a comparator which bundles the @var{type-test}, @var{equality},
  5644. @var{ordering}, and @var{hash} procedures provided. However, if
  5645. @var{ordering} or @var{hash} is @code{#f}, a procedure is provided that
  5646. signals an error on application. The predicates
  5647. @code{comparator-ordered?} and/or @code{comparator-hashable?},
  5648. respectively, will return @code{#f} in these cases.
  5649. Here are calls on @code{make-comparator} that will return useful
  5650. comparators for standard Scheme types:
  5651. @itemize
  5652. @item
  5653. @samp{(make-comparator boolean? boolean=? (lambda (x y) (and (not x) y))
  5654. boolean-hash)} will return a comparator for booleans, expressing the
  5655. ordering @samp{#f < #t} and the standard hash function for booleans.
  5656. @item
  5657. @samp{(make-comparator real? = < (lambda (x) (exact (abs x))))} will
  5658. return a comparator expressing the natural ordering of real numbers and
  5659. a plausible (but not optimal) hash function.
  5660. @item
  5661. @samp{(make-comparator string? string=? string<? string-hash)} will
  5662. return a comparator expressing the ordering of strings and the standard
  5663. hash function.
  5664. @item
  5665. @samp{(make-comparator string? string-ci=? string-ci<? string-ci-hash)}
  5666. will return a comparator expressing the case-insensitive ordering of
  5667. strings and the standard case-insensitive hash function.
  5668. @end itemize
  5669. @end deffn
  5670. @deffn {Scheme Procedure} make-pair-comparator car-comparator cdr-comparator
  5671. This procedure returns comparators whose functions behave as follows:
  5672. @itemize
  5673. @item
  5674. The type test returns @code{#t} if its argument is a pair, if the car
  5675. satisfies the type test predicate of @var{car-comparator}, and the cdr
  5676. satisfies the type test predicate of @var{cdr-comparator}.
  5677. @item
  5678. The equality function returns @code{#t} if the cars are equal according
  5679. to @var{car-comparator} and the cdrs are equal according to
  5680. @var{cdr-comparator}, and @code{#f} otherwise.
  5681. @item
  5682. The ordering function first compares the cars of its pairs using the
  5683. equality predicate of @var{car-comparator}. If they are not equal, then
  5684. the ordering predicate of @var{car-comparator} is applied to the cars
  5685. and its value is returned. Otherwise, the predicate compares the cdrs
  5686. using the equality predicate of @var{cdr-comparator}. If they are not
  5687. equal, then the ordering predicate of @var{cdr-comparator} is applied to
  5688. the cdrs and its value is returned.
  5689. @item
  5690. The hash function computes the hash values of the car and the cdr using
  5691. the hash functions of @var{car-comparator} and @var{cdr-comparator}
  5692. respectively and then hashes them together.
  5693. @end itemize
  5694. @end deffn
  5695. @deffn {Scheme Procedure} make-list-comparator element-comparator type-test empty? head tail
  5696. This procedure returns comparators whose functions behave as follows:
  5697. @itemize
  5698. @item
  5699. The type test returns @code{#t} if its argument satisfies
  5700. @var{type-test} and the elements satisfy the type test predicate of
  5701. @var{element-comparator}.
  5702. @item
  5703. The total order defined by the equality and ordering functions is as
  5704. follows (known as lexicographic order):
  5705. @itemize
  5706. @item
  5707. The empty sequence, as determined by calling @code{empty?}, compares
  5708. equal to itself.
  5709. @item
  5710. The empty sequence compares less than any non-empty sequence.
  5711. @item
  5712. Two non-empty sequences are compared by calling the @var{head} procedure
  5713. on each. If the heads are not equal when compared using
  5714. @var{element-comparator}, the result is the result of that comparison.
  5715. Otherwise, the results of calling the @var{tail} procedure are compared
  5716. recursively.
  5717. @end itemize
  5718. @item
  5719. The hash function computes the hash values of the elements using the
  5720. hash function of @var{element-comparator} and then hashes them together.
  5721. @end itemize
  5722. @end deffn
  5723. @deffn {Scheme Procedure} make-vector-comparator element-comparator type-test length ref
  5724. This procedure returns comparators whose functions behave as follows:
  5725. @itemize
  5726. @item
  5727. The type test returns @code{#t} if its argument satisfies
  5728. @var{type-test} and the elements satisfy the type test predicate of
  5729. @var{element-comparator}.
  5730. @item
  5731. The equality predicate returns @code{#t} if both of the following tests
  5732. are satisfied in order: the lengths of the vectors are the same in the
  5733. sense of @code{=}, and the elements of the vectors are the same in the
  5734. sense of the equality predicate of @var{element-comparator}.
  5735. @item
  5736. The ordering predicate returns @code{#t} if the results of applying
  5737. @var{length} to the first vector is less than the result of applying
  5738. length to the second vector. If the lengths are equal, then the
  5739. elements are examined pairwise using the ordering predicate of
  5740. @var{element-comparator}. If any pair of elements returns @code{#t},
  5741. then that is the result of the list comparator's ordering predicate;
  5742. otherwise the result is @code{#f}.
  5743. @item
  5744. The hash function computes the hash values of the elements using the
  5745. hash function of @var{element-comparator} and then hashes them together.
  5746. @end itemize
  5747. Here is an example, which returns a comparator for byte vectors:
  5748. @lisp
  5749. (make-vector-comparator
  5750. (make-comparator exact-integer? = < number-hash)
  5751. bytevector?
  5752. bytevector-length
  5753. bytevector-u8-ref)
  5754. @end lisp
  5755. @end deffn
  5756. @deffn {Scheme Procedure} make-eq-comparator
  5757. @deffnx {Scheme Procedure} make-eqv-comparator
  5758. @deffnx {Scheme Procedure} make-equal-comparator
  5759. These procedures return comparators whose functions behave as follows:
  5760. @itemize
  5761. @item
  5762. The type test returns @code{#t} in all cases.
  5763. @item
  5764. The equality functions are @code{eq?}, @code{eqv?}, and @code{equal?},
  5765. respectively.
  5766. @item
  5767. The ordering function is set @code{#f}, and attempting to use it will
  5768. cause an error with the message @code{"ordering is not supported"}.
  5769. @item
  5770. The hash function is @code{default-hash}.
  5771. @end itemize
  5772. @end deffn
  5773. @node SRFI-128 Standard hash functions
  5774. @subsubsection SRFI-128 Standard hash functions
  5775. These are hash functions for some standard Scheme types, suitable for
  5776. passing to @code{make-comparator}. Users may write their own hash
  5777. functions with the same signature. However, if programmers wish their
  5778. hash functions to be backward compatible with the reference
  5779. implementation of @uref{https://srfi.schemers.org/srfi-69/srfi-69.html,
  5780. SRFI 69}, they are advised to write their hash functions to accept a
  5781. second argument and ignore it.
  5782. @deffn {Scheme Procedure} boolean-hash obj
  5783. @deffnx {Scheme Procedure} char-hash obj
  5784. @deffnx {Scheme Procedure} string-hash obj
  5785. @deffnx {Scheme Procedure} string-ci-hash obj
  5786. @deffnx {Scheme Procedure} symbol-hash obj
  5787. @deffnx {Scheme Procedure} number-hash obj
  5788. @end deffn
  5789. These are suitable hash functions for the specified types. The hash
  5790. functions @code{char-ci-hash} and @code{string-ci-hash} treat their
  5791. argument case-insensitively. Note that while @code{symbol-hash} may
  5792. return the hashed value of applying @code{symbol->string} and then
  5793. @code{string-hash} to the symbol, this is not a requirement.
  5794. @node SRFI-128 Bounds and salt
  5795. @subsubsection SRFI-128 Bounds and salt
  5796. The following macros allow the callers of hash functions to affect their
  5797. behavior without interfering with the calling signature of a hash
  5798. function, which accepts a single argument (the object to be hashed) and
  5799. returns its hash value.
  5800. @deffn {Scheme Syntax} hash-bound
  5801. Hash functions should be written so as to return a number between
  5802. @code{0} and the largest reasonable number of elements (such as hash
  5803. buckets) a data structure in the implementation might have. This value
  5804. is defined as @math{2^25-1} or @code{33554432} in the reference
  5805. implementation used by Guile. This value provides the current bound as
  5806. a positive exact integer, typically for use by user-written hash
  5807. functions. However, they are not required to bound their results in
  5808. this way.
  5809. @end deffn
  5810. @deffn {Scheme Syntax} hash-salt
  5811. A salt is random data in the form of a non-negative exact integer used
  5812. as an additional input to a hash function in order to defend against
  5813. dictionary attacks, or (when used in hash tables) against
  5814. denial-of-service attacks that overcrowd certain hash buckets,
  5815. increasing the amortized O(1) lookup time to O(n). Salt can also be
  5816. used to specify which of a family of hash functions should be used for
  5817. purposes such as cuckoo hashing. This macro provides the current value
  5818. of the salt, typically for use by user-written hash functions. However,
  5819. they are not required to make use of the current salt.
  5820. The initial value is implementation-dependent, but must be less than the
  5821. value of @samp{(hash-bound)}, and should be distinct for distinct runs
  5822. of a program unless otherwise specified by the implementation. In the
  5823. reference implementation used by Guile, the initial salt value is
  5824. @code{16064047}.
  5825. @end deffn
  5826. @node SRFI-128 Default comparators
  5827. @subsubsection SRFI-128 Default comparators
  5828. @deffn {Scheme Procedure} make-default-comparator
  5829. Return a comparator known as a @emph{default comparator} that accepts
  5830. Scheme values and orders them in a way that respects the following
  5831. conditions:
  5832. @itemize
  5833. @item
  5834. Given disjoint types @code{a} and @code{b}, one of three conditions must
  5835. hold:
  5836. @itemize
  5837. @item
  5838. All objects of type @code{a} compare less than all objects of type
  5839. @code{b}.
  5840. @item
  5841. All objects of type @code{a} compare greater than all objects of type
  5842. @code{b}.
  5843. @item
  5844. All objects of both type @code{a} and type @code{b} compare equal to
  5845. each other. This is not permitted for any of the Scheme types mentioned
  5846. below.
  5847. @end itemize
  5848. @item
  5849. The empty list must be ordered before all pairs.
  5850. @item
  5851. When comparing booleans, it must use the total order @samp{#f < #t}.
  5852. @item
  5853. When comparing characters, @code{char=?} and @code{char<?} are used.
  5854. @item
  5855. When comparing pairs, it must behave the same as a comparator returned
  5856. by @code{make-pair-comparator} with default comparators as arguments.
  5857. @item
  5858. When comparing symbols, the total order produced with @code{symbol<?}
  5859. and @code{symbol<?} is used.
  5860. @item
  5861. When comparing bytevectors, it must behave the same as a comparator
  5862. created by the expression @samp{(make-vector-comparator (make-comparator
  5863. bytevector? = < number-hash) bytevector? bytevector-length
  5864. bytevector-u8-ref)}.
  5865. @item
  5866. When comparing numbers where either number is complex, since non-real
  5867. numbers cannot be compared with @code{<}, the following least-surprising
  5868. ordering is defined: If the real parts are @code{<} or @code{>}, so are
  5869. the numbers; otherwise, the numbers are ordered by their imaginary
  5870. parts. This can still produce somewhat surprising results if one real
  5871. part is exact and the other is inexact.
  5872. @item
  5873. When comparing real numbers, it must use @code{=} and @code{<}.
  5874. @item
  5875. When comparing strings, it must use @code{string=?} and @code{string<?}.
  5876. @item
  5877. When comparing vectors, it must behave the same as a comparator returned
  5878. by @samp{(make-vector-comparator (make-default-comparator) vector?
  5879. vector-length vector-ref)}.
  5880. @item
  5881. When comparing members of types registered with
  5882. @code{comparator-register-default!}, it must behave in the same way as
  5883. the comparator registered using that function.
  5884. @end itemize
  5885. Default comparators use @code{default-hash} as their hash function.
  5886. @end deffn
  5887. @deffn {Scheme Procedure} default-hash obj
  5888. This is the hash function used by default comparators, which accepts a
  5889. Scheme value and hashes it in a way that respects the following
  5890. conditions:
  5891. @itemize
  5892. @item
  5893. When applied to a pair, it must return the result of hashing together
  5894. the values returned by @code{default-hash} when applied to the car and
  5895. the cdr.
  5896. @item
  5897. When applied to a boolean, character, string, symbol, or number, it must
  5898. return the same result as @code{boolean-hash}, @code{char-hash},
  5899. @code{string-hash}, @code{symbol-hash}, or @code{number-hash}
  5900. respectively.
  5901. @item
  5902. When applied to a list or vector, it must return the result of hashing
  5903. together the values returned by @code{default-hash} when applied to each
  5904. of the elements.
  5905. @end itemize
  5906. @end deffn
  5907. @deffn {Scheme Procedure} comparator-register-default! comparator
  5908. Register @var{comparator} for use by default comparators, such that if
  5909. the objects being compared both satisfy the type test predicate of
  5910. @var{comparator}, it will be employed by default comparators to compare
  5911. them. Return an unspecified value. It is an error if any value
  5912. satisfies both the type test predicate of @var{comparator} and any of
  5913. the following type test predicates: @code{boolean?}, @code{char?},
  5914. @code{null?}, @code{pair?}, @code{symbol?}, @code{bytevector?},
  5915. @code{number?}, @code{string?}, @code{vector?}, or the type test
  5916. predicate of a comparator that has already been registered.
  5917. This procedure is intended only to extend default comparators into
  5918. territory that would otherwise be undefined, not to override their
  5919. existing behavior. In general, the ordering of calls to
  5920. @code{comparator-register-default!} should be irrelevant.
  5921. The comparators available from this library are not registered with the
  5922. @code{comparator-register-default!} procedure, because the default
  5923. comparator is meant to be under the control of the program author rather
  5924. than the library author. It is the program author's responsibility to
  5925. ensure that the registered comparators do not conflict with each other.
  5926. @end deffn
  5927. @node SRFI-128 Accessors and Invokers
  5928. @subsubsection SRFI-128 Accessors and Invokers
  5929. @deffn {Scheme Procedure} comparator-type-test-predicate comparator
  5930. @deffnx {Scheme Procedure} comparator-equality-predicate comparator
  5931. @deffnx {Scheme Procedure} comparator-ordering-predicate comparator
  5932. @deffnx {Scheme Procedure} comparator-hash-function comparator
  5933. @end deffn
  5934. Return the four procedures of @var{comparator}.
  5935. @deffn {Scheme Procedure} comparator-test-type comparator obj
  5936. Invoke the type test predicate of @var{comparator} on @var{obj} and
  5937. return what it returns. More convenient than
  5938. @code{comparator-type-test-predicate}, but less efficient when the
  5939. predicate is called repeatedly.
  5940. @end deffn
  5941. @deffn {Scheme Procedure} comparator-check-type comparator obj
  5942. Invoke the type test predicate of @var{comparator} on @var{obj} and
  5943. return true if it returns true, but signal an error otherwise. More
  5944. convenient than @code{comparator-type-test-predicate}, but less
  5945. efficient when the predicate is called repeatedly.
  5946. @end deffn
  5947. @deffn {Scheme Procedure} comparator-hash comparator obj
  5948. Invoke the hash function of @var{comparator} on @var{obj} and return
  5949. what it returns. More convenient than @code{comparator-hash-function},
  5950. but less efficient when the predicate is called repeatedly.
  5951. @quotation note
  5952. No invokers are required for the equality and ordering predicates,
  5953. because the @code{=?} and @code{<?} predicates described after serve
  5954. this function.
  5955. @end quotation
  5956. @end deffn
  5957. @node SRFI-128 Comparison predicates
  5958. @subsubsection SRFI-128 Comparison predicates
  5959. @deffn {Scheme Procedure} =? comparator object@sub{1} object@sub{2} object@sub{3} @dots{}
  5960. @deffnx {Scheme Procedure} <? comparator object@sub{1} object@sub{2} object@sub{3} @dots{}
  5961. @deffnx {Scheme Procedure} >? comparator object@sub{1} object@sub{2} object@sub{3} @dots{}
  5962. @deffnx {Scheme Procedure} <=? comparator object@sub{1} object@sub{2} object@sub{3} @dots{}
  5963. @deffnx {Scheme Procedure} >=? comparator object@sub{1} object@sub{2} object@sub{3} @dots{}
  5964. @end deffn
  5965. @noindent
  5966. These procedures are analogous to the number, character, and string
  5967. comparison predicates of Scheme. They allow the convenient use of
  5968. comparators to handle variable data types.
  5969. @noindent
  5970. These procedures apply the equality and ordering predicates of
  5971. @var{comparator} to the objects as follows. If the specified relation
  5972. returns @code{#t} for all @var{object@sub{i}} and @var{object@sub{j}}
  5973. where @var{n} is the number of objects and @math{1 <= @var{i} < @var{j}
  5974. <= @var{n}}, then the procedures return @code{#t}, but otherwise
  5975. @code{#f}. Because the relations are transitive, it suffices to compare
  5976. each object with its successor. The order in which the values are
  5977. compared is unspecified.
  5978. @node SRFI-128 Syntax
  5979. @subsubsection SRFI-128 Syntax
  5980. @deffn {Scheme Procedure} comparator-if<=> [ comparator ] object@sub{1} object@sub{2} less-than equal-to greater-than
  5981. It is an error unless @var{comparator} evaluates to a comparator and
  5982. @var{object@sub{1}} and @var{object@sub{2}} evaluate to objects that the
  5983. comparator can handle. If the ordering predicate returns true when
  5984. applied to the values of @var{object@sub{1}} and @var{object@sub{2}} in
  5985. that order, then @var{less-than} is evaluated and its value returned.
  5986. If the equality predicate returns true when applied in the same way,
  5987. then @var{equal-to} is evaluated and its value returned. If neither
  5988. returns true, @var{greater-than} is evaluated and its value returned.
  5989. If @var{comparator} is omitted, a default comparator is used.
  5990. @end deffn
  5991. @node SRFI-171
  5992. @subsection Transducers
  5993. @cindex SRFI-171
  5994. @cindex transducers
  5995. Some of the most common operations used in the Scheme language are those
  5996. transforming lists: map, filter, take and so on. They work well, are well
  5997. understood, and are used daily by most Scheme programmers. They are however not
  5998. general because they only work on lists, and they do not compose very well
  5999. since combining N of them builds @code{(- N 1)} intermediate lists.
  6000. Transducers are oblivious to what kind of process they are used in, and
  6001. are composable without building intermediate collections. This means we
  6002. can create a transducer that squares all odd numbers:
  6003. @example
  6004. (compose (tfilter odd?) (tmap (lambda (x) (* x x))))
  6005. @end example
  6006. and reuse it with lists, vectors, or in just about any context where
  6007. data flows in one direction. We could use it as a processing step for
  6008. asynchronous channels, with an event framework as a pre-processing step,
  6009. or even in lazy contexts where you pass a lazy collection and a
  6010. transducer to a function and get a new lazy collection back.
  6011. The traditional Scheme approach of having collection-specific procedures
  6012. is not changed. We instead specify a general form of transformations
  6013. that complement these procedures. The benefits are obvious: a clear,
  6014. well-understood way of describing common transformations in a way that
  6015. is faster than just chaining the collection-specific counterparts. For
  6016. guile in particular this means a lot better GC performance.
  6017. Notice however that @code{(compose @dots{})} composes transducers
  6018. left-to-right, due to how transducers are initiated.
  6019. @menu
  6020. * SRFI-171 General Discussion:: General information about transducers
  6021. * SRFI-171 Applying Transducers:: Documentation of collection-specific forms
  6022. * SRFI-171 Reducers:: Reducers specified by the SRFI
  6023. * SRFI-171 Transducers:: Transducers specified by the SRFI
  6024. * SRFI-171 Helpers:: Utilities for writing your own transducers
  6025. @end menu
  6026. @node SRFI-171 General Discussion
  6027. @subsubsection SRFI-171 General Discussion
  6028. @cindex transducers discussion
  6029. @subheading The concept of reducers
  6030. The central part of transducers are 3-arity reducing procedures.
  6031. @itemize
  6032. @item
  6033. no arguments: Produces the identity of the reducer.
  6034. @item
  6035. (result-so-far): completion. Returns @code{result-so-far} either with or
  6036. without transforming it first.
  6037. @item
  6038. (result-so-far input) combines @code{result-so-far} and @code{input} to produce
  6039. a new @code{result-so-far}.
  6040. @end itemize
  6041. In the case of a summing @code{+} reducer, the reducer would produce, in
  6042. arity order: @code{0}, @code{result-so-far}, @code{(+ result-so-far
  6043. input)}. This happens to be exactly what the regular @code{+} does.
  6044. @subheading The concept of transducers
  6045. A transducer is a one-arity procedure that takes a reducer and produces a
  6046. reducing function that behaves as follows:
  6047. @itemize
  6048. @item
  6049. no arguments: calls reducer with no arguments (producing its identity)
  6050. @item
  6051. (result-so-far): Maybe transform the result-so-far and call reducer with it.
  6052. @item
  6053. (result-so-far input) Maybe do something to input and maybe call the
  6054. reducer with result-so-far and the maybe-transformed input.
  6055. @end itemize
  6056. A simple example is as following:
  6057. @example
  6058. (list-transduce (tfilter odd?) + '(1 2 3 4 5)).
  6059. @end example
  6060. This first returns a transducer filtering all odd
  6061. elements, then it runs @code{+} without arguments to retrieve its
  6062. identity. It then starts the transduction by passing @code{+} to the
  6063. transducer returned by @code{(tfilter odd?)} which returns a reducing
  6064. function. It works not unlike reduce from SRFI 1, but also checks
  6065. whether one of the intermediate transducers returns a "reduced" value
  6066. (implemented as a SRFI 9 record), which means the reduction finished
  6067. early.
  6068. Because transducers compose and the final reduction is only executed in
  6069. the last step, composed transducers will not build any intermediate
  6070. result or collections. Although the normal way of thinking about
  6071. application of composed functions is right to left, due to how the
  6072. transduction is built it is applied left to right. @code{(compose
  6073. (tfilter odd?) (tmap sqrt))} will create a transducer that first filters
  6074. out any odd values and then computes the square root of the rest.
  6075. @subheading State
  6076. Even though transducers appear to be somewhat of a generalisation of
  6077. @code{map} and friends, this is not really true. Since transducers don't
  6078. know in which context they are being used, some transducers must keep
  6079. state where their collection-specific counterparts do not. The
  6080. transducers that keep state do so using hidden mutable state, and as
  6081. such all the caveats of mutation, parallelism, and multi-shot
  6082. continuations apply. Each transducer keeping state is clearly described
  6083. as doing so in the documentation.
  6084. @subheading Naming
  6085. Reducers exported from the transducers module are named as in their
  6086. SRFI-1 counterpart, but prepended with an r. Transducers also follow
  6087. that naming, but are prepended with a t.
  6088. @node SRFI-171 Applying Transducers
  6089. @subsubsection Applying Transducers
  6090. @cindex transducers applying
  6091. @deffn {Scheme Procedure} list-transduce xform f lst
  6092. @deffnx {Scheme Procedure} list-transduce xform f identity lst
  6093. Initialize the transducer @var{xform} by passing the reducer @var{f}
  6094. to it. If no identity is provided, @var{f} runs without arguments to
  6095. return the reducer identity. It then reduces over @var{lst} using the
  6096. identity as the seed.
  6097. If one of the transducers finishes early (such as @code{ttake} or
  6098. @code{tdrop}), it communicates this by returning a reduced value, which
  6099. in the guile implementation is just a value wrapped in a SRFI 9 record
  6100. type named ``reduced''. If such a value is returned by the transducer,
  6101. @code{list-transduce} must stop execution and return an unreduced value
  6102. immediately.
  6103. @end deffn
  6104. @deffn {Scheme Procedure} vector-transduce xform f vec
  6105. @deffnx {Scheme Procedure} vector-transduce xform f identity vec
  6106. @deffnx {Scheme Procedure} string-transduce xform f str
  6107. @deffnx {Scheme Procedure} string-transduce xform f identity str
  6108. @deffnx {Scheme Procedure} bytevector-u8-transduce xform f bv
  6109. @deffnx {Scheme Procedure} bytevector-u8-transduce xform f identity bv
  6110. @deffnx {Scheme Procedure} generator-transduce xform f gen
  6111. @deffnx {Scheme Procedure} generator-transduce xform f identity gen
  6112. Same as @code{list-transduce}, but for vectors, strings, u8-bytevectors
  6113. and SRFI-158-styled generators respectively.
  6114. @end deffn
  6115. @deffn {Scheme Procedure} port-transduce xform f reader
  6116. @deffnx {Scheme Procedure} port-transduce xform f reader port
  6117. @deffnx {Scheme Procedure} port-transduce xform f identity reader port
  6118. Same as @code{list-transduce} but for ports. Called without a port, it
  6119. reduces over the results of applying @var{reader} until the EOF-object
  6120. is returned, presumably to read from @code{current-input-port}. With a
  6121. port @var{reader} is applied to @var{port} instead of without any
  6122. arguments. If @var{identity} is provided, that is used as the initial
  6123. identity in the reduction.
  6124. @end deffn
  6125. @node SRFI-171 Reducers
  6126. @subsubsection Reducers
  6127. @cindex transducers reducers
  6128. @deffn {Scheme Procedure} rcons
  6129. a simple consing reducer. When called without values, it returns its
  6130. identity, @code{'()}. With one value, which will be a list, it reverses
  6131. the list (using @code{reverse!}). When called with two values, it conses
  6132. the second value to the first.
  6133. @example
  6134. (list-transduce (tmap (lambda (x) (+ x 1)) rcons (list 0 1 2 3))
  6135. @result{} (1 2 3 4)
  6136. @end example
  6137. @end deffn
  6138. @deffn {Scheme Procedure} reverse-rcons
  6139. same as rcons, but leaves the values in their reversed order.
  6140. @example
  6141. (list-transduce (tmap (lambda (x) (+ x 1))) reverse-rcons (list 0 1 2 3))
  6142. @result{} (4 3 2 1)
  6143. @end example
  6144. @end deffn
  6145. @deffn {Scheme Procedure} rany pred?
  6146. The reducer version of any. Returns @code{(reduced (pred? value))} if
  6147. any @code{(pred? value)} returns non-#f. The identity is #f.
  6148. @example
  6149. (list-transduce (tmap (lambda (x) (+ x 1))) (rany odd?) (list 1 3 5))
  6150. @result{} #f
  6151. (list-transduce (tmap (lambda (x) (+ x 1))) (rany odd?) (list 1 3 4 5))
  6152. @result{} #t
  6153. @end example
  6154. @end deffn
  6155. @deffn {Scheme Procedure} revery pred?
  6156. The reducer version of every. Stops the transduction and returns
  6157. @code{(reduced #f)} if any @code{(pred? value)} returns #f. If every
  6158. @code{(pred? value)} returns true, it returns the result of the last
  6159. invocation of @code{(pred? value)}. The identity is #t.
  6160. @example
  6161. (list-transduce
  6162. (tmap (lambda (x) (+ x 1)))
  6163. (revery (lambda (v) (if (odd? v) v #f)))
  6164. (list 2 4 6))
  6165. @result{} 7
  6166. (list-transduce (tmap (lambda (x) (+ x 1)) (revery odd?) (list 2 4 5 6))
  6167. @result{} #f
  6168. @end example
  6169. @end deffn
  6170. @deffn {Scheme Procedure} rcount
  6171. A simple counting reducer. Counts the values that pass through the
  6172. transduction.
  6173. @example
  6174. (list-transduce (tfilter odd?) rcount (list 1 2 3 4)) @result{} 2.
  6175. @end example
  6176. @end deffn
  6177. @node SRFI-171 Transducers
  6178. @subsubsection Transducers
  6179. @cindex transducers transducers
  6180. @deffn {Scheme Procedure} tmap proc
  6181. Returns a transducer that applies @var{proc} to all values. Stateless.
  6182. @end deffn
  6183. @deffn {Scheme Procedure} tfilter pred?
  6184. Returns a transducer that removes values for which @var{pred?} returns #f.
  6185. Stateless.
  6186. @end deffn
  6187. @deffn {Scheme Procedure} tremove pred?
  6188. Returns a transducer that removes values for which @var{pred?} returns non-#f.
  6189. Stateless
  6190. @end deffn
  6191. @deffn {Scheme Procedure} tfilter-map proc
  6192. The same as @code{(compose (tmap proc) (tfilter values))}. Stateless.
  6193. @end deffn
  6194. @deffn {Scheme Procedure} treplace mapping
  6195. The argument @var{mapping} is an association list (using @code{equal?}
  6196. to compare keys), a hash-table, a one-argument procedure taking one
  6197. argument and either producing that same argument or a replacement value.
  6198. Returns a transducer which checks for the presence of any value passed
  6199. through it in mapping. If a mapping is found, the value of that mapping
  6200. is returned, otherwise it just returns the original value.
  6201. Does not keep internal state, but modifying the mapping while it's in
  6202. use by treplace is an error.
  6203. @end deffn
  6204. @deffn {Scheme Procedure} tdrop n
  6205. Returns a transducer that discards the first @var{n} values.
  6206. Stateful.
  6207. @end deffn
  6208. @deffn {Scheme Procedure} ttake n
  6209. Returns a transducer that discards all values and stops the transduction
  6210. after the first @var{n} values have been let through. Any subsequent values
  6211. are ignored.
  6212. Stateful.
  6213. @end deffn
  6214. @deffn {Scheme Procedure} tdrop-while pred?
  6215. Returns a transducer that discards the first values for which
  6216. @var{pred?} returns true.
  6217. Stateful.
  6218. @end deffn
  6219. @deffn {Scheme Procedure} ttake-while pred?
  6220. @deffnx {Scheme Procedure} ttake-while pred? retf
  6221. Returns a transducer that stops the transduction after @var{pred?} has
  6222. returned #f. Any subsequent values are ignored and the last successful
  6223. value is returned. @var{retf} is a function that gets called whenever
  6224. @var{pred?} returns false. The arguments passed are the result so far
  6225. and the input for which pred? returns @code{#f}. The default function is
  6226. @code{(lambda (result input) result)}.
  6227. Stateful.
  6228. @end deffn
  6229. @deffn {Scheme Procedure} tconcatenate
  6230. tconcatenate @emph{is} a transducer that concatenates the content of
  6231. each value (that must be a list) into the reduction.
  6232. @example
  6233. (list-transduce tconcatenate rcons '((1 2) (3 4 5) (6 (7 8) 9)))
  6234. @result{} (1 2 3 4 5 6 (7 8) 9)
  6235. @end example
  6236. @end deffn
  6237. @deffn {Scheme Procedure} tappend-map proc
  6238. The same as @code{(compose (tmap proc) tconcatenate)}.
  6239. @end deffn
  6240. @deffn {Scheme Procedure} tflatten
  6241. tflatten @emph{is} a transducer that flattens an input consisting of lists.
  6242. @example
  6243. (list-transduce tflatten rcons '((1 2) 3 (4 (5 6) 7 8) 9)
  6244. @result{} (1 2 3 4 5 6 7 8 9)
  6245. @end example
  6246. @end deffn
  6247. @deffn {Scheme Procedure} tdelete-neighbor-duplicates
  6248. @deffnx {Scheme Procedure} tdelete-neighbor-duplicates equality-predicate
  6249. Returns a transducer that removes any directly following duplicate
  6250. elements. The default @var{equality-predicate} is @code{equal?}.
  6251. Stateful.
  6252. @end deffn
  6253. @deffn {Scheme Procedure} tdelete-duplicates
  6254. @deffnx {Scheme Procedure} tdelete-duplicates equality-predicate
  6255. Returns a transducer that removes any subsequent duplicate elements
  6256. compared using @var{equality-predicate}. The default
  6257. @var{equality-predicate} is @code{equal?}.
  6258. Stateful.
  6259. @end deffn
  6260. @deffn {Scheme Procedure} tsegment n
  6261. Returns a transducer that groups inputs into lists of @var{n} elements.
  6262. When the transduction stops, it flushes any remaining collection, even
  6263. if it contains fewer than @var{n} elements.
  6264. Stateful.
  6265. @end deffn
  6266. @deffn {Scheme Procedure} tpartition pred?
  6267. Returns a transducer that groups inputs in lists by whenever
  6268. @code{(pred? input)} changes value.
  6269. Stateful.
  6270. @end deffn
  6271. @deffn {Scheme Procedure} tadd-between value
  6272. Returns a transducer which interposes @var{value} between each value
  6273. and the next. This does not compose gracefully with transducers like
  6274. @code{ttake}, as you might end up ending the transduction on
  6275. @code{value}.
  6276. Stateful.
  6277. @end deffn
  6278. @deffn {Scheme Procedure} tenumerate
  6279. @deffnx {Scheme Procedure} tenumerate start
  6280. Returns a transducer that indexes values passed through it, starting at
  6281. @var{start}, which defaults to 0. The indexing is done through cons
  6282. pairs like @code{(index . input)}.
  6283. @example
  6284. (list-transduce (tenumerate 1) rcons (list 'first 'second 'third))
  6285. @result{} ((1 . first) (2 . second) (3 . third))
  6286. @end example
  6287. Stateful.
  6288. @end deffn
  6289. @deffn {Scheme Procedure} tlog
  6290. @deffnx {Scheme Procedure} tlog logger
  6291. Returns a transducer that can be used to log or print values and
  6292. results. The result of the @var{logger} procedure is discarded. The
  6293. default @var{logger} is @code{(lambda (result input) (write input)
  6294. (newline))}.
  6295. Stateless.
  6296. @end deffn
  6297. @subheading Guile-specific transducers
  6298. These transducers are available in the @code{(srfi srfi-171 gnu)}
  6299. library, and are provided outside the standard described by the SRFI-171
  6300. document.
  6301. @deffn {Scheme Procedure} tbatch reducer
  6302. @deffnx {Scheme Procedure} tbatch transducer reducer
  6303. A batching transducer that accumulates results using @var{reducer} or
  6304. @code{((transducer) reducer)} until it returns a reduced value. This can
  6305. be used to generalize something like @code{tsegment}:
  6306. @example
  6307. ;; This behaves exactly like (tsegment 4).
  6308. (list-transduce (tbatch (ttake 4) rcons) rcons (iota 10))
  6309. @result{} ((0 1 2 3) (4 5 6 7) (8 9))
  6310. @end example
  6311. @end deffn
  6312. @deffn {Scheme Procedure} tfold reducer
  6313. @deffnx {Scheme Procedure} tfold reducer seed
  6314. A folding transducer that yields the result of @code{(reducer seed
  6315. value)}, saving its result between iterations.
  6316. @example
  6317. (list-transduce (tfold +) rcons (iota 10))
  6318. @result{} (0 1 3 6 10 15 21 28 36 45)
  6319. @end example
  6320. @end deffn
  6321. @node SRFI-171 Helpers
  6322. @subsubsection Helper functions for writing transducers
  6323. @cindex transducers helpers
  6324. These functions are in the @code{(srfi srfi-171 meta)} module and are only
  6325. usable when you want to write your own transducers.
  6326. @deffn {Scheme Procedure} reduced value
  6327. Wraps a value in a @code{<reduced>} container, signalling that the
  6328. reduction should stop.
  6329. @end deffn
  6330. @deffn {Scheme Procedure} reduced? value
  6331. Returns #t if value is a @code{<reduced>} record.
  6332. @end deffn
  6333. @deffn {Scheme Procedure} unreduce reduced-container
  6334. Returns the value in reduced-container.
  6335. @end deffn
  6336. @deffn {Scheme Procedure} ensure-reduced value
  6337. Wraps value in a @code{<reduced>} container if it is not already reduced.
  6338. @end deffn
  6339. @deffn {Scheme Procedure} preserving-reduced reducer
  6340. Wraps @code{reducer} in another reducer that encapsulates any returned
  6341. reduced value in another reduced container. This is useful in places
  6342. where you re-use a reducer with [collection]-reduce. If the reducer
  6343. returns a reduced value, [collection]-reduce unwraps it. Unless handled,
  6344. this leads to the reduction continuing.
  6345. @end deffn
  6346. @deffn {Scheme Procedure} list-reduce f identity lst
  6347. The reducing function used internally by @code{list-transduce}. @var{f}
  6348. is a reducer as returned by a transducer. @var{identity} is the
  6349. identity (sometimes called "seed") of the reduction. @var{lst} is a
  6350. list. If @var{f} returns a reduced value, the reduction stops
  6351. immediately and the unreduced value is returned.
  6352. @end deffn
  6353. @deffn {Scheme Procedure} vector-reduce f identity vec
  6354. The vector version of list-reduce.
  6355. @end deffn
  6356. @deffn {Scheme Procedure} string-reduce f identity str
  6357. The string version of list-reduce.
  6358. @end deffn
  6359. @deffn {Scheme Procedure} bytevector-u8-reduce f identity bv
  6360. The bytevector-u8 version of list-reduce.
  6361. @end deffn
  6362. @deffn {Scheme Procedure} port-reduce f identity reader port
  6363. The port version of list-reduce. It reduces over port using reader
  6364. until reader returns the EOF object.
  6365. @end deffn
  6366. @deffn {Scheme Procedure} generator-reduce f identity gen
  6367. The generator version of list-reduce. It reduces over @code{gen} until
  6368. it returns the EOF object
  6369. @end deffn
  6370. @c srfi-modules.texi ends here
  6371. @c Local Variables:
  6372. @c TeX-master: "guile.texi"
  6373. @c End: