Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <!-- documentation for s7 -->
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
  6. <title>s7</title>
  7. <style type="text/css">
  8. EM.red {color:red; font-style:normal}
  9. EM.normal {font-style:normal}
  10. EM.redb {color:red; font-weight: bold; font-style: normal}
  11. EM.error {color:chocolate; font-style:normal}
  12. EM.emdef {font-weight: bold; font-style: normal}
  13. EM.green {color:green; font-style:normal}
  14. EM.gray {color:#505050; font-style:normal}
  15. EM.big {font-size: 20px;
  16. font-style: normal;
  17. }
  18. EM.bigger {font-size: 30px;
  19. font-style: normal;
  20. }
  21. EM.def {font-style: normal}
  22. H1 {text-align: center}
  23. UL {list-style-type: none}
  24. A {text-decoration:none}
  25. A:hover {text-decoration:underline}
  26. A.def {font-weight: bold;
  27. font-style: normal;
  28. text-decoration:none;
  29. text-color:black;
  30. }
  31. PRE.indented {padding-left: 1.0cm;}
  32. DIV.indented {background-color: #F8F8F0;
  33. padding-left: 0.5cm;
  34. padding-right: 0.5cm;
  35. padding-top: 0.5cm;
  36. padding-bottom: 0.5cm;
  37. margin-bottom: 0.5cm;
  38. border: 1px solid gray;
  39. border-radius: 20px;
  40. -moz-border-radius: 20px;
  41. -webkit-border-radius: 20px;
  42. }
  43. DIV.header {margin-top: 60px;
  44. margin-bottom: 30px;
  45. border: 4px solid #00ff00; /* green */
  46. background-color: #eefdee; /* lightgreen */
  47. padding-left: 30px;
  48. }
  49. DIV.topheader {margin-top: 10px;
  50. margin-bottom: 40px;
  51. border: 4px solid #00ff00; /* green */
  52. background-color: #f5f5dc; /* beige */
  53. font-family: 'Helvetica';
  54. font-size: 30px;
  55. text-align: center;
  56. padding-top: 10px;
  57. padding-bottom: 10px;
  58. }
  59. DIV.separator {margin-top: 30px;
  60. margin-bottom: 10px;
  61. border: 2px solid #00ff00; /* green */
  62. background-color: #f5f5dc; /* beige */
  63. padding-top: 4px;
  64. width: 30%;
  65. border-radius: 4px;
  66. -moz-border-radius: 4px;
  67. -webkit-border-radius: 4px;
  68. }
  69. DIV.bluishbordered {background-color: #f2f4ff;
  70. border: 1px solid #000000;
  71. padding-left: 10px;
  72. padding-right: 10px;
  73. padding-top: 10px;
  74. padding-bottom: 10px;
  75. }
  76. DIV.brownishbordered {background-color: #fbfbf0;
  77. border: 1px solid #000000;
  78. padding-left: 10px;
  79. padding-right: 10px;
  80. padding-top: 10px;
  81. padding-bottom: 10px;
  82. }
  83. BODY.body {background-color: #ffffff; /* white */
  84. margin-right: 20px;
  85. margin-left: 20px;
  86. }
  87. DIV.orange {background-color: #ffa500; /* orange */
  88. padding-left: 6px;
  89. padding-right: 6px;
  90. padding-top: 4px;
  91. padding-bottom: 4px;
  92. border: 4px solid #000000;
  93. font-family: 'Helvetica';
  94. font-size: 12px;
  95. font-weight: bold;
  96. text-align: center;
  97. margin-left: 0.5cm;
  98. margin-right: 1.0cm;
  99. float: right;
  100. border-radius: 8px;
  101. -moz-border-radius: 8px;
  102. -webkit-border-radius: 8px;
  103. }
  104. DIV.listener {background-color: #f0f8ff;
  105. font-family: 'Monospace';
  106. padding-left: 6px;
  107. padding-right: 6px;
  108. padding-bottom: 4px;
  109. margin-left: 1.0cm;
  110. margin-right: 4.0cm;
  111. border: 2px solid #a0a0a0;
  112. }
  113. LI.li_header {padding-top: 20px;}
  114. SUMMARY.indented {background-color: #F8F8F0;
  115. padding-top: 8px;
  116. padding-bottom: 8px;
  117. margin-bottom: 0.5cm;
  118. border: 1px solid gray;
  119. text-align: center;
  120. width: 30%;
  121. border-radius: 8px;
  122. -moz-border-radius: 8px;
  123. -webkit-border-radius: 8px;
  124. }
  125. </style>
  126. </head>
  127. <body class="body">
  128. <!-- INDEX s7doc:s7 scheme -->
  129. <div class="topheader" id="s7doc">s7
  130. </div>
  131. <p>s7 is a Scheme implementation intended as an extension language
  132. for other applications, primarily Snd, Radium, and Common Music. It exists as just two files, s7.c and
  133. s7.h, that want only to disappear into someone else's source tree. There are no libraries,
  134. no run-time init files, and no configuration scripts.
  135. It can be built as a stand-alone
  136. interpreter (see <a href="#repl">below</a>). s7test.scm is a regression test for s7.
  137. A tarball is available: <a href="ftp://ccrma-ftp.stanford.edu/pub/Lisp/s7.tar.gz">s7 tarball</a>.
  138. </p>
  139. <p>
  140. s7 is the default extension language of Snd and sndlib (<a href="http://ccrma.stanford.edu/software/snd/index.html">snd</a>),
  141. Rick Taube's Common Music (commonmusic at sourceforge), and Kjetil Matheussen's Radium music editor.
  142. There are X, Motif, Gtk, and openGL bindings
  143. in libxm in the Snd tarball, or at ftp://ccrma-ftp.stanford.edu/pub/Lisp/libxm.tar.gz.
  144. If you're running s7 in a context
  145. that has getenv, file-exists?, and system, you can use s7-slib-init.scm
  146. to gain easy access to slib. This init file is named "s7.init" in the slib distribution.
  147. </p>
  148. <p>Although it is a descendant of tinyScheme, s7 is closest as a Scheme dialect to Guile 1.8.
  149. I believe it is compatible with <a href="#s7vsr5rs">r5rs</a> and <a href="#r7rs">r7rs</a>: you can just ignore all the additions discussed in this file.
  150. It has continuations,
  151. ratios, complex numbers,
  152. macros, keywords, hash-tables,
  153. multiprecision arithmetic,
  154. generalized set!, unicode, and so on.
  155. It does not have syntax-rules or any of
  156. its friends, and it does not think there is any such thing
  157. as an inexact integer.
  158. </p>
  159. <p>This file assumes you know about Scheme and all its problems,
  160. and want a quick tour of where s7 is different. (Well, it was quick once upon a time).
  161. The main difference: if it's in s7, it's a first-class citizen of s7, and that includes
  162. macros, environments, and syntactic forms.
  163. </p>
  164. <br>
  165. <blockquote>
  166. <div class="indented">
  167. <p>I originally used a small font for scholia, but now I have to squint
  168. to read that tiny text, so less-than-vital commentaries are shown in the normal font, but
  169. indented and on a sort of brownish background.
  170. </p>
  171. </div>
  172. </blockquote>
  173. <br>
  174. <!--
  175. <div class="orange">
  176. <p>Danger!</p>
  177. <p>Men Working</p>
  178. <p>in Trees</p>
  179. </div>
  180. -->
  181. <ul>
  182. <li><a href="#multiprecision">arbitrary precision arithmetic</a>
  183. <li><a href="#math">math functions</a>
  184. <li><a href="#define*">define*, named let*</a>
  185. <li><a href="#macros">define-macro</a>
  186. <li><a href="#pws">procedure-setter</a>
  187. <li><a href="#generalizedset">generalized set!</a>
  188. <li><a href="#multidimensionalvectors">multidimensional vectors</a>
  189. <li><a href="#hashtables">hash tables</a>
  190. <li><a href="#environments">environments</a>
  191. <li><a href="#multiplevalues">multiple-values</a>
  192. <li><a href="#callwithexit1">call-with-exit</a>
  193. <li><a href="#format1">format</a>
  194. <li><a href="#hooks">hooks</a>
  195. <li><a href="#procedureinfo">procedure info</a>
  196. <li><a href="#evalstring">eval</a>
  197. <li><a href="#IO">IO and other OS functions</a>
  198. <li><a href="#errors">errors</a>
  199. <li><a href="#autoload">autoload</a>
  200. <li><a href="#constants">define-constant, symbol-access</a>
  201. <li><a href="#miscellanea">marvels and curiousities:</a>
  202. <ul>
  203. <li><a href="#loadpath">*load-path*</a>, <a href="#featureslist">*features*</a>, <a href="#sharpreaders">*#readers*</a>,
  204. <li><a href="#makelist">make-list</a>, <a href="#charposition">char-position</a>, <a href="#keywords">keywords</a>
  205. <li><a href="#symboltable">symbol-table</a>, <a href="#s7help">help</a>, <a href="#s7gc">gc</a>, <a href="#morallyequalp">morally-equal?</a>
  206. <li><a href="#expansion">define-expansion</a>, <a href="#s7env">*s7*</a>, <a href="#s7vsr5rs">r5rs</a>, <a href="#r7rs">r7rs</a>,
  207. <li><a href="#profiling">profiling</a>, <a href="#circle">circular lists</a>, <a href="#legolambda">legolambda</a>, etc...
  208. </ul>
  209. <li class="li_header"><a href="#FFIexamples">FFI examples</a>
  210. <ul>
  211. <li><a href="#repl">read-eval-print loop (and emacs)</a>
  212. <li><a href="#defun">define a function with arguments and a returned value, and define a variable </a>
  213. <li><a href="#defvar">call a Scheme function from C, and get/set Scheme variable values in C</a>
  214. <li><a href="#juce">C++ and Juce</a>
  215. <li><a href="#sndlib">load sndlib using the Xen functions and macros</a>
  216. <li><a href="#pwstype">add a new Scheme type and a procedure with a setter</a>
  217. <li><a href="#functionportexample">redirect display output to a C procedure</a>
  218. <li><a href="#extendop">extend a built-in operator ("+" in this case)</a>
  219. <li><a href="#definestar1">C-side define* (s7_define_function_star)</a>
  220. <li><a href="#definemacro1">C-side define-macro (s7_define_macro)</a>
  221. <li><a href="#definegeneric">define a generic function in C</a>
  222. <li><a href="#signal">signal handling (C-C to break out of an infinite loop)</a>
  223. <li><a href="#vector">direct multidimensional vector element access</a>
  224. <li><a href="#notify">notification in C that a Scheme variable has been set!</a>
  225. <li><a href="#namespace">Load C defined stuff into a separate namespace</a>
  226. <li><a href="#Cerrors">Error handling in C</a>
  227. <li><a href="#testhook">Hooks in C and Scheme</a>
  228. <li><a href="#dload">Load a C module dynamically</a>
  229. <li><a href="#gmpex">gmp and friends</a>
  230. <li><a href="#glistener">glistener.c</a>
  231. <li><a href="#gdb">gdb</a>
  232. </ul>
  233. <li class="li_header"><a href="#s7examples">s7 examples</a>
  234. <ul>
  235. <li><a href="#cload">cload.scm</a>
  236. <ul>
  237. <li><a href="#libc">libc</a>
  238. <li><a href="#libgsl">libgsl</a>
  239. <li><a href="#libgdbm">libgdbm</a>
  240. </ul>
  241. <li><a href="#schemerepl">repl.scm</a>
  242. <li><a href="#lint">lint.scm</a>
  243. </ul>
  244. </ul>
  245. <div class="header" id="multiprecision"><h4>multiprecision arithmetic</h4></div>
  246. <p>All numeric types, integers, ratios, reals, and complex numbers are supported.
  247. The basic integer and real
  248. types are defined in s7.h, defaulting to long long int and double.
  249. A ratio consists of two integers, a complex number two reals.
  250. pi is predefined, as are
  251. most-positive-fixnum and most-negative-fixnum.
  252. s7 can be built with multiprecision support
  253. for all types, using the gmp, mpfr, and mpc libraries (set WITH_GMP to 1 in s7.c).
  254. If multiprecision arithmetic is
  255. enabled, the following functions are included: bignum, and bignum?, and the variable (*s7* 'bignum-precision).
  256. (*s7* 'bignum-precision) defaults to 128; it sets the number of bits each float takes.
  257. pi automatically reflects the current (*s7* 'bignum-precision):
  258. </p>
  259. <pre class="indented">
  260. &gt; pi
  261. <em class="gray">3.141592653589793238462643383279502884195E0</em>
  262. &gt; (*s7* 'bignum-precision)
  263. <em class="gray">128</em>
  264. &gt; (set! (*s7* 'bignum-precision) 256)
  265. <em class="gray">256</em>
  266. &gt; pi
  267. <em class="gray">3.141592653589793238462643383279502884197169399375105820974944592307816406286198E0</em>
  268. </pre>
  269. <p>
  270. <em class=def id="bignump">bignum?</em> returns #t if its argument is a big number of some type; I use "bignum"
  271. for any big number, not just integers. To create a big number,
  272. either include enough digits to overflow the default types, or use the <em class=def id="bignum">bignum</em> function.
  273. Its argument is a string representing the desired number:
  274. </p>
  275. <pre class="indented">
  276. &gt; (bignum "123456789123456789")
  277. <em class="gray">123456789123456789</em>
  278. &gt; (bignum "1.123123123123123123123123123")
  279. <em class="gray">1.12312312312312312312312312300000000009E0</em>
  280. </pre>
  281. <blockquote>
  282. <div class="indented">
  283. <p>In the non-gmp case, if s7 is built using doubles (s7_double in s7.h), the float "epsilon" is
  284. around (expt 2 -53), or about 1e-16. In the gmp case, it is around (expt 2 (- (*s7* 'bignum-precision))).
  285. So in the default case (precision = 128), using gmp:
  286. </p>
  287. <pre class="indented">
  288. &gt; (= 1.0 (+ 1.0 (expt 2.0 -128)))
  289. <em class="gray">#t</em>
  290. &gt; (= 1.0 (+ 1.0 (expt 2.0 -127)))
  291. <em class="gray">#f</em>
  292. </pre>
  293. <p>and in the non-gmp case:
  294. </p>
  295. <pre class="indented">
  296. &gt; (= 1.0 (+ 1.0 (expt 2 -53)))
  297. <em class="gray">#t</em>
  298. &gt; (= 1.0 (+ 1.0 (expt 2 -52)))
  299. <em class="gray">#f</em>
  300. </pre>
  301. <p>In the gmp case, integers and ratios are limited only by the size of memory,
  302. but reals are limited by (*s7* 'bignum-precision). This means, for example, that
  303. </p>
  304. <pre class="indented">
  305. &gt; (floor 1e56) ; (*s7* 'bignum-precision) is 128
  306. <em class="gray">99999999999999999999999999999999999999927942405962072064</em>
  307. &gt; (set! (*s7* 'bignum-precision) 256)
  308. <em class="gray">256</em>
  309. &gt; (floor 1e56)
  310. <em class="gray">100000000000000000000000000000000000000000000000000000000</em>
  311. </pre>
  312. <p>The non-gmp case is similar, but it's easy to find the edge cases:
  313. </p>
  314. <pre class="indented">
  315. &gt; (floor (+ 0.9999999995 (expt 2.0 23)))
  316. <em class="gray">8388609</em>
  317. </pre>
  318. </div>
  319. </blockquote>
  320. <div class="header" id="math"><h4>math functions</h4></div>
  321. <p>
  322. s7 includes:
  323. </p>
  324. <ul>
  325. <li>sinh, cosh, tanh, asinh, acosh, atanh
  326. <li>logior, logxor, logand, lognot, logbit?, ash, integer-length, integer-decode-float
  327. <li>random
  328. <li>nan?, infinite?
  329. </ul>
  330. <p>
  331. The random function can take any numeric argument, including 0.
  332. The following constants are predefined: pi, most-positive-fixnum, most-negative-fixnum.
  333. Other math-related differences between s7 and r5rs:
  334. </p>
  335. <ul>
  336. <li>rational? and exact mean integer or ratio (i.e. not floating point), inexact means not exact.
  337. <li>floor, ceiling, truncate, and round return (exact) integer results.
  338. <li>"#" does not stand for an unknown digit.
  339. <li>the "@" complex number notation is not supported ("@" is an exponent marker in s7).
  340. <li>"+i" is not considered a number; include the real part.
  341. <li>modulo, remainder, and quotient take integer, ratio, or real arguments.
  342. <li>lcm and gcd can take integer or ratio arguments.
  343. <li>log takes an optional second argument, the base.
  344. <li>'.' and an exponent can occur in a number in any base.
  345. <li>rationalize returns a ratio!
  346. <li>case is significant in numbers, as elsewhere: #b0 is 0, but #B0 is an error.
  347. </ul>
  348. <pre class="indented">
  349. &gt; (exact? 1.0)
  350. <em class="gray">#f</em>
  351. &gt; (rational? 1.5)
  352. <em class="gray">#f</em>
  353. &gt; (floor 1.4)
  354. <em class="gray">1</em>
  355. &gt; (remainder 2.4 1)
  356. <em class="gray">0.4</em>
  357. &gt; (modulo 1.4 1.0)
  358. <em class="gray">0.4</em>
  359. &gt; (lcm 3/4 1/6)
  360. <em class="gray">3/2</em>
  361. &gt; (log 8 2)
  362. <em class="gray">3</em>
  363. &gt; (number-&gt;string 0.5 2)
  364. <em class="gray">"0.1"</em>
  365. &gt; (string-&gt;number "0.1" 2)
  366. <em class="gray">0.5</em>
  367. &gt; (rationalize 1.5)
  368. <em class="gray">3/2</em>
  369. &gt; (complex 1/2 0)
  370. <em class="gray">1/2</em>
  371. &gt; (logbit? 6 1) ; argument order, (logbit? int index), follows gmp, not CL
  372. <em class="gray">#t</em>
  373. </pre>
  374. <p>See <a href="#libgsl">cload and libgsl.scm</a> for easy access to GSL,
  375. and similarly libm.scm for the C math library.
  376. </p>
  377. <blockquote>
  378. <div class="indented">
  379. <p>The exponent itself is always in base 10; this follows gmp usage.
  380. Scheme normally uses "@" for its useless polar notation, but that
  381. means <code>(string-&gt;number "1e1" 16)</code> is ambiguous &mdash; is the "e" a digit or an exponent marker?
  382. In s7, "@" is an exponent marker.
  383. </p>
  384. <pre class="indented">
  385. &gt; (string-&gt;number "1e9" 2) ; (expt 2 9)
  386. <em class="gray">512.0</em>
  387. &gt; (string-&gt;number "1e1" 12) ; "e" is not a digit in base 12
  388. <em class="gray">#f</em>
  389. &gt; (string-&gt;number "1e1" 16) ; (+ (* 1 16 16) (* 14 16) 1)
  390. <em class="gray">481</em>
  391. &gt; (string-&gt;number "1.2e1" 3); (* 3 (+ 1 2/3))
  392. <em class="gray">5.0</em>
  393. </pre>
  394. </div>
  395. <div class="indented">
  396. <p>Should s7 predefine the numbers +inf.0, -inf.0, and nan.0? It doesn't currently, but you can
  397. get them via log or 1/0 (see <a href="#r7rs">below</a>).
  398. But what is <code>(/ 1.0 0.0)</code>? s7 gives a "division by zero" error here, and also in <code>(/ 1 0)</code>.
  399. Guile returns +inf.0 in the first case, which seems reasonable, but a "numerical overflow" error in the second.
  400. Slightly weirder is <code>(expt 0.0 0+i)</code>. Currently s7 returns 0.0, Guile returns +nan.0+nan.0i,
  401. Clisp and sbcl throw an error. Everybody agrees that <code>(expt 0 0)</code> is 1, and Guile thinks
  402. that <code>(expt 0.0 0.0)</code> is 1.0. But <code>(expt 0 0.0)</code> and <code>(expt 0.0 0)</code> return different
  403. results in Guile (1 and 1.0), both are 0.0 in s7, the first is an error in Clisp, but the second returns 1,
  404. and so on &mdash; what a mess! This mess was made a lot worse than it needs to be when the IEEE decreed that
  405. 0.0 equals -0.0, so we can't tell them apart, but that they produce different results in nearly every use!
  406. </p>
  407. <pre class="indented">
  408. scheme@(guile-user)&gt; (= -0.0 0.0)
  409. <em class="gray">#t</em>
  410. scheme@(guile-user)&gt; (negative? -0.0)
  411. <em class="gray">#f</em>
  412. scheme@(guile-user)&gt; (= (/ 1.0 0.0) (/ 1.0 -0.0))
  413. <em class="gray">#f</em>
  414. scheme@(guile-user)&gt; (&lt; (/ 1.0 -0.0) -1e100 1e100 (/ 1.0 0.0))
  415. <em class="gray">#t</em>
  416. </pre>
  417. <p>
  418. How can they be equal? In s7, the sign
  419. of -0.0 is ignored, and they really are equal.
  420. One other oddity: two floats can satisfy eq? and yet not be eqv?:
  421. <code>(eq? nan.0 nan.0)</code> might be #t (it is unspecified), but <code>(eqv? nan.0 nan.0)</code> is #f.
  422. The same problem afflicts memq and assq.
  423. </p>
  424. </div>
  425. <div class="indented">
  426. <p>The <em class=def id="random">random</em> function takes a range and an optional state, and returns a number
  427. between zero and the range, of the same type as the range. It is perfectly reasonable
  428. to use a range of 0, in which case random returns 0.
  429. <em class=def id="randomstate">random-state</em> creates a new random state from a seed. If no state is passed,
  430. random uses some default state initialized from the current time. <em class=def id="randomstatep">random-state?</em> returns #t if passed a random state object.
  431. s7 ought to have a function named random? that always returns #t.
  432. </p>
  433. <pre class="indented">
  434. &gt; (random 0)
  435. <em class="gray">0</em>
  436. &gt; (random 1.0)
  437. <em class="gray">0.86331198514245</em>
  438. &gt; (random 3/4)
  439. <em class="gray">654/1129</em>
  440. &gt; (random 1+i)
  441. <em class="gray">0.86300308872748+0.83601002730848i</em>
  442. &gt; (random -1.0)
  443. <em class="gray">-0.037691127513267</em>
  444. &gt; (define r0 (random-state 1234))
  445. <em class="gray">r0</em>
  446. &gt; (random 100 r0)
  447. <em class="gray">94</em>
  448. &gt; (random 100 r0)
  449. <em class="gray">19</em>
  450. &gt; (define r1 (random-state 1234))
  451. <em class="gray">r1</em>
  452. &gt; (random 100 r1)
  453. <em class="gray">94</em>
  454. &gt; (random 100 r1)
  455. <em class="gray">19</em>
  456. </pre>
  457. <p>copy the random-state to save a spot in a random number sequence, or save the random-state as a list via
  458. random-state-&gt;list, then to restart from that point, apply random-state to that list.
  459. </p>
  460. </div>
  461. <div class="indented">
  462. <p>I can't find the right tone for this section; this is the 400-th revision; I wish I were a better writer!
  463. </p>
  464. <p>In some Schemes,
  465. "rational" means "could possibly be
  466. expressed equally well as a ratio: floats are approximations". In s7 it's: "is actually expressed (at the scheme level) as a ratio (or an integer of course)";
  467. otherwise "rational?" is the same as "real?":
  468. </p>
  469. <pre class="indented">
  470. (not-s7)&gt; (rational? (sqrt 2))
  471. <em class="gray">#t</em>
  472. </pre>
  473. <p>That 1.0 is represented at the IEEE-float level as a sort of
  474. ratio does not mean it has to be a scheme ratio; the two notions are independent.
  475. </p>
  476. <p>But that confusion is trivial compared to the completely nutty "inexact integer".
  477. As I understand it, "inexact" originally meant "floating point", and "exact" meant integer or ratio of integers.
  478. But words have a life of their own.
  479. 0.0 somehow became an "inexact" integer (although it can be represented exactly in floating
  480. point).
  481. +inf.0 must be an integer &mdash;
  482. its fractional part is explicitly zero! But +nan.0...
  483. And then there's:
  484. </p>
  485. <pre class="indented">
  486. (not-s7)&gt; (integer? 9007199254740993.1)
  487. <em class="gray">#t</em>
  488. </pre>
  489. <p>
  490. When does this matter? I often need to index into a vector, but the index is a float (a "real" in Scheme-speak: its
  491. fractional part can be non-zero).
  492. In one Scheme:
  493. </p>
  494. <pre class="indented">
  495. (not-s7)&gt; (vector-ref #(0) (floor 0.1))
  496. <em class="gray">ERROR: Wrong type (expecting exact integer): 0.0 </em>; [why? "it's probably a programmer mistake"!]
  497. </pre>
  498. <p>Not to worry, I'll use inexact-&gt;exact:
  499. </p>
  500. <pre class="indented">
  501. (not-s7)&gt; (inexact-&gt;exact 0.1)
  502. <em class="gray">3602879701896397/36028797018963968 </em>; [why? "floats are ratios"!]
  503. </pre>
  504. <p>So I end up using the verbose <code>(floor (inexact-&gt;exact ...))</code> everywhere, and even
  505. then I have no guarantee that I'll get a legal vector index.
  506. I have never seen any use made of the exact/inexact distinction &mdash; just
  507. wild flailing to try get around it.
  508. I think the whole idea is confused and useless, and leads
  509. to verbose and buggy code.
  510. If we discard it,
  511. we can maintain backwards compatibility via:
  512. </p>
  513. <pre class="indented">
  514. (define exact? rational?)
  515. (define (inexact? x) (not (rational? x)))
  516. (define inexact-&gt;exact rationalize) ; or floor
  517. (define (exact-&gt;inexact x) (* x 1.0))
  518. </pre>
  519. <p>#i and #e are also useless because you can
  520. have any number after, for example, #b:
  521. </p>
  522. <pre class="indented">
  523. &gt; #b1.1
  524. <em class="gray">1.5</em>
  525. &gt; #b1e2
  526. <em class="gray">4.0</em>
  527. &gt; #o17.5+i
  528. <em class="gray">15.625+1i</em>
  529. </pre>
  530. <p>Speaking of #b and friends, what should <code>(string-&gt;number "#xffff" 2)</code> return?
  531. </p>
  532. </div>
  533. <details>
  534. <summary class="indented">more examples</summary>
  535. <div class="indented">
  536. <pre>
  537. (define (log-n-of n . ints) ; return the bits on in exactly n of ints
  538. (let ((len (length ints)))
  539. (cond ((= len 0) (if (= n 0) -1 0))
  540. ((= n 0) (lognot (apply logior ints)))
  541. ((= n len) (apply logand ints))
  542. ((&gt; n len) 0)
  543. (#t
  544. (do ((1s 0)
  545. (prev ints)
  546. (i 0 (+ i 1)))
  547. ((= i len) 1s)
  548. (let ((cur (ints i)))
  549. (if (= i 0)
  550. (set! 1s (logior 1s (logand cur (apply log-n-of (- n 1) (cdr ints)))))
  551. (let ((mid (cdr prev)))
  552. (set! (cdr prev) (if (= i (- len 1)) () (cdr mid)))
  553. (set! 1s (logior 1s (logand cur (apply log-n-of (- n 1) ints))))
  554. (set! (cdr prev) mid)
  555. (set! prev mid)))))))))
  556. </pre>
  557. </div>
  558. </details>
  559. </blockquote>
  560. <div class="header" id="define*"><h4>define*, lambda*</h4></div>
  561. <p><em class=def id="definestar">define*</em> and
  562. <em class=def id="lambdastar">lambda*</em>
  563. are extensions of define and lambda that make it easier
  564. to deal with optional, keyword, and rest arguments.
  565. The syntax is very simple: every argument to define* has a default value
  566. and is automatically available as a keyword argument. The default value
  567. is either #f if unspecified, or given in a list whose first member is
  568. the argument name.
  569. The last argument
  570. can be preceded by :rest or a dot to indicate that all other trailing arguments
  571. should be packaged as a list under that argument's name. A trailing or rest
  572. argument's default value is ().
  573. </p>
  574. <pre class="indented">
  575. (<em class=red>define*</em> (hi a (b 32) (c "hi")) (list a b c))
  576. </pre>
  577. <p>Here the argument "a" defaults to #f, "b" to 32, etc.
  578. When the function is called,
  579. the argument names are set from the values passed the function,
  580. then any unset arguments are bound to their default values, evaluated in left-to-right order.
  581. As the current argument list is scanned, any name that occurs as a keyword, :arg for example where the parameter name is arg,
  582. sets that argument's new value. Otherwise, as values occur, they
  583. are plugged into the actual argument list based on their position, counting a keyword/value pair as one argument.
  584. This is called an optional-key list in CLM. So, taking the function
  585. above as an example:
  586. </p>
  587. <pre class="indented">
  588. &gt; (hi 1)
  589. <em class="gray">(1 32 "hi")</em>
  590. &gt; (hi :b 2 :a 3)
  591. <em class="gray">(3 2 "hi")</em>
  592. &gt; (hi 3 2 1)
  593. <em class="gray">(3 2 1)</em>
  594. </pre>
  595. <p>See s7test.scm for many examples. (s7's define* is very close to srfi-89's define*).
  596. </p>
  597. <blockquote>
  598. <div class="indented">
  599. <p>The combination of optional and keyword arguments is viewed with disfavor in the Lisp
  600. community, but the problem is in CL's implementation of the idea, not the idea itself.
  601. I've used the s7 style since around 1976, and have never found it confusing. The mistake
  602. in CL is to require the optional arguments if a keyword argument occurs, and to consider them as distinct from the
  603. keyword arguments. So everyone forgets and puts a keyword where CL expects a required-optional
  604. argument. CL then does something ridiculous, and the programmer stomps around shouting about keywords, but the fault lies with CL.
  605. If s7's way is considered too loose, one way to tighten it might be to insist that once a keyword
  606. is used, only keyword argument pairs can follow.
  607. </p>
  608. </div>
  609. <div class="indented">
  610. <p>A natural companion of lambda* is named let*. In named let, the implicit function's
  611. arguments have initial values, but thereafter, each call requires the full set of arguments.
  612. Why not treat the initial values as default values?
  613. </p>
  614. <pre class="indented">
  615. &gt; (let* func ((i 1) (j 2))
  616. (+ i j (if (&gt; i 0) (func (- i 1)) 0)))
  617. <em class="gray">5</em>
  618. &gt; (letrec ((func (lambda* ((i 1) (j 2))
  619. (+ i j (if (&gt; i 0) (func (- i 1)) 0)))))
  620. (func))
  621. <em class="gray">5</em>
  622. </pre>
  623. <p>This is consistent with the lambda* arguments because their defaults are
  624. already set in left-to-right order, and as each parameter is set to its default value,
  625. the binding is added to the default value expression environment (just as if it were a let*).
  626. The let* name itself (the implicit function) is not defined until after the bindings
  627. have been evaluated (as in named let).
  628. </p>
  629. <p>In CL, keyword default values are handled in the same way:
  630. </p>
  631. <pre class="indented">
  632. &gt; (defun foo (&amp;key (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c))
  633. <em class="gray">FOO </em>
  634. &gt; (foo :b 2 :a 60)
  635. <em class="gray">(60 2 67) </em>
  636. </pre>
  637. <p>In s7, we'd use:
  638. </p>
  639. <pre class="indented">
  640. (define* (foo (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c))
  641. </pre>
  642. </div>
  643. <div class="indented">
  644. <p>To try to catch what I believe are usually mistakes, I added two
  645. error checks. One is triggered if you set the same parameter twice
  646. in the same call, and the other if an unknown keyword is encountered
  647. in the key position. These problems arise in a case such as
  648. </p>
  649. <pre class="indented">
  650. (define* (f (a 1) (b 2)) (list a b))
  651. </pre>
  652. <p>You could do any of the following by accident:
  653. </p>
  654. <pre class="indented">
  655. (f 1 :a 2) ; what is a?
  656. (f :b 1 2) ; what is b?
  657. (f :c 3) ; did you really want a to be :c and b to be 3?
  658. </pre>
  659. <p>In the last case, to pass a keyword deliberately, either include the
  660. argument keyword: <code>(f :a :c)</code>, or make the default value a keyword:
  661. <code>(define* (f (a :c) ...))</code>.
  662. To turn off this error check, add :allow-other-keys at the end of the parameter list.
  663. </p>
  664. </div>
  665. <details>
  666. <summary class="indented">rest arg nits</summary>
  667. <div class="indented">
  668. <p>s7's lambda* arglist handling is not the same as CL's lambda-list. First,
  669. you can have more than one :rest parameter:
  670. </p>
  671. <pre class="indented">
  672. &gt; ((lambda* (:rest a :rest b) (map + a b)) 1 2 3 4 5)
  673. <em class="gray">'(3 5 7 9)</em>
  674. </pre>
  675. <p>and second, the rest parameter, if any, takes up an argument slot just like any other
  676. argument:
  677. </p>
  678. <pre class="indented">
  679. &gt; ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 32)
  680. <em class="gray">(32 1 ())</em>
  681. &gt; ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 1 2 3 4 5)
  682. <em class="gray">(1 3 (2 3 4 5))</em>
  683. </pre>
  684. <p>CL would agree with the first case if we used &amp;key for 'c', but would give an error in the second.
  685. Of course, the major difference is that s7 keyword arguments don't insist that the key be present.
  686. The :rest argument is needed in cases like these because we can't use an expression
  687. such as:
  688. </p>
  689. <pre class="indented">
  690. &gt; ((lambda* ((a 3) . b c) (list a b c)) 1 2 3 4 5)
  691. <em class="red">error: </em><em class="gray">stray dot?</em>
  692. &gt; ((lambda* (a . (b 1)) b) 1 2) ; the reader turns the arglist into (a b 1)
  693. <em class="red">error: </em><em class="gray">lambda* parameter '1 is a constant</em>
  694. </pre>
  695. <p>Yet another nit: the :rest argument is not considered a keyword argument, so
  696. </p>
  697. <pre class="indented">
  698. &gt; (define* (f :rest a) a)
  699. <em class="gray">f</em>
  700. &gt; (f :a 1)
  701. <em class="gray">(:a 1)</em>
  702. </pre>
  703. </div>
  704. </details>
  705. </blockquote>
  706. <div class="header" id="macros"><h4>macros</h4></div>
  707. <p><em class=def id="definemacro">define-macro</em>,
  708. <em class=def id="definemacrostar">define-macro*</em>,
  709. <em class=def id="macroexpand">macroexpand</em>,
  710. <em class=def id="gensym">gensym</em>,
  711. <em class=def id="gensym?">gensym?</em>, and
  712. <em class=def id="macrop">macro?</em>
  713. implement the standard old-time macros.
  714. </p>
  715. <pre class="indented">
  716. &gt; (define-macro (and-let* vars . body)
  717. `(let () (and ,@(map (lambda (v) `(define ,@v)) vars) (begin ,@body))))
  718. &gt; (define-macro (<em class=def id="trace">trace</em> f)
  719. `(define ,f
  720. (apply lambda 'args
  721. `((format () "(~A ~{~A~^ ~}) -&gt; " ',',f args)
  722. (let ((val (apply ,,f args)))
  723. (format () "~A~%" val)
  724. val)))))
  725. <em class="gray">trace</em>
  726. &gt; (trace abs)
  727. <em class="gray">abs</em>
  728. &gt; (abs -1.5)
  729. <em class="gray">(abs -1.5) -&gt; 1.5</em>
  730. <em class="gray">1.5</em>
  731. </pre>
  732. <p>macroexpand can help debug a macro. I always forget that it
  733. wants an expression:
  734. </p>
  735. <pre class="indented">
  736. &gt; (define-macro (add-1 arg) `(+ 1 ,arg))
  737. <em class="gray">add-1</em>
  738. &gt; (macroexpand (add-1 32))
  739. <em class="gray">(+ 1 32)</em>
  740. </pre>
  741. <p>gensym returns a symbol that is guaranteed to be unused. It takes an optional string argument
  742. giving the new symbol name's prefix. gensym? returns #t if its argument is a symbol created by gensym.
  743. </p>
  744. <pre class="indented">
  745. (define-macro (pop! sym)
  746. (let ((v (<em class=red>gensym</em>)))
  747. `(let ((,v (car ,sym)))
  748. (set! ,sym (cdr ,sym))
  749. ,v)))
  750. </pre>
  751. <p>As in define*, the starred forms give optional and keyword arguments:
  752. </p>
  753. <pre class="indented">
  754. &gt; (define-macro* (add-2 a (b 2)) `(+ ,a ,b))
  755. <em class="gray">add-2</em>
  756. &gt; (add-2 1 3)
  757. <em class="gray">4</em>
  758. &gt; (add-2 1)
  759. <em class="gray">3</em>
  760. &gt; (add-2 :b 3 :a 1)
  761. <em class="gray">4</em>
  762. </pre>
  763. <p>A bacro is a macro that expands its body and evaluates
  764. the result in the calling environment.
  765. </p>
  766. <pre class="indented">
  767. (define setf
  768. (let ((args (gensym))
  769. (name (gensym)))
  770. (apply <em class=red>define-bacro</em> `((,name . ,args)
  771. (unless (null? ,args)
  772. (apply set! (car ,args) (cadr ,args) ())
  773. (apply setf (cddr ,args)))))))
  774. </pre>
  775. <p>
  776. The setf argument is a gensym (created when setf is defined) so that its name does not shadow any existing
  777. variable. Bacros expand in the calling environment, and a normal argument name
  778. might shadow something in that environment while the bacro is being expanded.
  779. Similarly, if you introduce bindings in the bacro expansion code, you need to
  780. keep track of which environment you want things to happen in. Use with-let
  781. and gensym liberally.
  782. stuff.scm has bacro-shaker which can find inadvertent name collisions,
  783. but it is flighty and easily confused.
  784. See s7test.scm for many examples of macros including such perennial favorites as
  785. loop, dotimes, do*, enum, pushnew, and defstruct.
  786. The calling environment itself is (outlet (curlet)) from within a bacro, so
  787. </p>
  788. <pre class="indented">
  789. (define-bacro (holler)
  790. `(format *stderr* "(~S~{ ~S ~S~^~})~%"
  791. (let ((f __func__))
  792. (if (pair? f) (car f) f))
  793. (map (lambda (slot)
  794. (values (symbol-&gt;keyword (car slot)) (cdr slot)))
  795. (reverse (map values ,(outlet (curlet)))))))
  796. (define (f1 a b)
  797. (holler)
  798. (+ a b))
  799. (f1 2 3) ; prints out "(f1 :a 2 :b 3)" and returns 5
  800. </pre>
  801. <blockquote>
  802. <div class="indented">
  803. <p>
  804. Since a bacro (normally) sheds its define-time environment:
  805. </p>
  806. <pre class="indented">
  807. (define call-bac
  808. (let ((<em class=red>x</em> 2))
  809. (define-bacro (m a) `(+ ,a ,<em class=red>x</em>))))
  810. &gt; (call-bac 1)
  811. <em class="red">error: </em><em class="gray">x: unbound variable</em>
  812. </pre>
  813. <p>
  814. A macro here returns 3. But don't be hasty! The bacro can get its define-time environment (its closure)
  815. via funclet, so in fact, define-macro is a special case of define-bacro! We can define
  816. macros that work in all four ways: the expansion can happen in either the definition or calling environment,
  817. as can the evaluation of that expansion. In a bacro, both happen in the calling environment
  818. if we take no other action, and in a normal macro (define-macro), the expansion happens in the definition
  819. environment, and the evaluation in the calling environment.
  820. Here's a brief example of all four:
  821. </p>
  822. <pre class="indented">
  823. (let ((x 1) (y 2))
  824. (define-bacro (bac1 a)
  825. `(+ ,x y ,a)) ; expand and eval in calling env
  826. (let ((x 32) (y 64))
  827. (bac1 3))) ; (with-let (inlet 'x 32 'y 64) (+ 32 y 3))
  828. -&gt; 99 ; with-let and inlet refer to <a href="#environments">environments</a>
  829. (let ((x 1) (y 2)) ; this is like define-macro
  830. (define-bacro (bac2 a)
  831. (with-let (sublet (funclet bac2) :a a)
  832. `(+ ,x y ,a))) ; expand in definition env, eval in calling env
  833. (let ((x 32) (y 64))
  834. (bac2 3))) ; (with-let (inlet 'x 32 'y 64) (+ 1 y 3))
  835. -&gt; 68
  836. (let ((x 1) (y 2))
  837. (define-bacro (bac3 a)
  838. (let ((e (with-let (sublet (funclet bac3) :a a)
  839. `(+ ,x y ,a))))
  840. `(with-let ,(sublet (funclet bac3) :a a)
  841. ,e))) ; expand and eval in definition env
  842. (let ((x 32) (y 64))
  843. (bac3 3))) ; (with-let (inlet 'x 1 'y 2) (+ 1 y 3))
  844. -&gt; 6
  845. (let ((x 1) (y 2))
  846. (define-bacro (bac4 a)
  847. (let ((e `(+ ,x y ,a)))
  848. `(with-let ,(sublet (funclet bac4) :a a)
  849. ,e))) ; expand in calling env, eval in definition env
  850. (let ((x 32) (y 64))
  851. (bac4 3))) ; (with-let (inlet 'x 1 'y 2) (+ 32 y 3))
  852. -&gt; 37
  853. </pre>
  854. </div>
  855. <div class="indented">
  856. <p>As the setf example shows, a macro is a first-class citizen of s7. You can
  857. pass it as a function argument, apply it to a list, return it from a function,
  858. call it recursively,
  859. and assign it to a variable. You can even set its procedure-setter!
  860. </p>
  861. <pre class="indented">
  862. &gt; (define-macro (hi a) `(+ ,a 1))
  863. <em class="gray">hi</em>
  864. &gt; (apply hi '(4))
  865. <em class="gray">5</em>
  866. &gt; (define (fmac mac) (apply mac '(4)))
  867. <em class="gray">fmac</em>
  868. &gt; (fmac hi)
  869. <em class="gray">5</em>
  870. &gt; (define (fmac mac) (mac 4))
  871. <em class="gray">fmac</em>
  872. &gt; (fmac hi)
  873. <em class="gray">5</em>
  874. &gt; (define (make-mac)
  875. (define-macro (hi a) `(+ ,a 1)))
  876. <em class="gray">make-mac</em>
  877. &gt; (let ((x (make-mac)))
  878. (x 2))
  879. <em class="gray">3</em>
  880. &gt; (define-macro (ref v i) `(vector-ref ,v ,i))
  881. <em class="gray">ref</em>
  882. &gt; (define-macro (set v i x) `(vector-set! ,v ,i ,x))
  883. <em class="gray">set</em>
  884. &gt; (set! (procedure-setter ref) set)
  885. <em class="gray">set</em>
  886. &gt; (let ((v (vector 1 2 3))) (set! (ref v 0) 32) v)
  887. <em class="gray">#(32 2 3)</em>
  888. </pre>
  889. <p>To expand all the macros in a piece of code:
  890. </p>
  891. <pre class="indented">
  892. (define-macro (fully-macroexpand form)
  893. (list 'quote
  894. (let expand ((form form))
  895. (cond ((not (pair? form)) form)
  896. ((and (symbol? (car form))
  897. (macro? (symbol-&gt;value (car form))))
  898. (expand (apply macroexpand (list form))))
  899. ((and (eq? (car form) 'set!) ; look for (set! (mac ...) ...) and use mac's procedure-setter
  900. (pair? (cdr form))
  901. (pair? (cadr form))
  902. (macro? (symbol-&gt;value (caadr form))))
  903. (expand
  904. (apply (eval
  905. (procedure-source (procedure-setter (symbol-&gt;value (caadr form)))))
  906. (append (cdadr form) (cddr form)))))
  907. (else (cons (expand (car form)) (expand (cdr form))))))))
  908. </pre>
  909. <p>This does not always handle bacros correctly because their expansion can depend on the run-time
  910. state.
  911. </p>
  912. </div>
  913. <details>
  914. <summary class="indented">backquote details</summary>
  915. <div class="indented">
  916. <p>Backquote (quasiquote) in s7 is almost trivial. Constants are unchanged, symbols are quoted,
  917. ",arg" becomes "arg", and ",@arg" becomes "(apply values arg)" &mdash; hooray for real multiple values!
  918. It's almost as easy to write the actual macro body as the backquoted version of it.
  919. </p>
  920. <pre class="indented">
  921. &gt; (define-macro (hi a) `(+ 1 ,a))
  922. <em class="gray">hi</em>
  923. &gt; (procedure-source hi)
  924. <em class="gray">(lambda (a) ({list} '+ 1 a))</em>
  925. &gt; (define-macro (hi a) `(+ 1 ,@a))
  926. <em class="gray">hi</em>
  927. &gt; (procedure-source hi)
  928. <em class="gray">(lambda (a) ({list} '+ 1 ({apply_values} a)))</em>
  929. </pre>
  930. <p>{list} is a special version of list to avoid name collisions
  931. and handle a few tricky details (similarly for {apply_values}). There is no unquote-splicing
  932. macro in s7; ",@(...)" becomes "(unquote ({apply_values} ...))" at read-time. There shouldn't be any unquote
  933. either. In Scheme the reader turns ,x into (unquote x), so:
  934. </p>
  935. <pre>
  936. &gt; (let (,'a) unquote)
  937. <em class="gray">a</em>
  938. &gt; (let (, (lambda (x) (+ x 1))) ,,,,'3)
  939. <em class="gray">7</em>
  940. </pre>
  941. <p>comma becomes a sort of symbol macro! I think I'll remove unquote; ,x and ,@x will still work
  942. as expected, but there will not be any "unquote" or "unquote-splicing" in the resultant source code. Just to make life difficult:
  943. </p>
  944. <pre>
  945. &gt; (let (' 1) quote)
  946. <em class="gray">1</em>
  947. </pre>
  948. <p>but that translation is so ingrained in lisp
  949. that I'm reluctant to change it. The two unquote names, on the
  950. other hand, seem unnecessary.
  951. </p>
  952. </div>
  953. </details>
  954. <p>s7 macros are not hygienic. For example,
  955. </p>
  956. <pre class="indented">
  957. &gt; (define-macro (mac b)
  958. `(let ((a 12))
  959. (+ a ,b)))
  960. <em class="gray">mac</em>
  961. &gt; (let ((a 1) (+ *)) (mac a))
  962. <em class="gray">144</em>
  963. </pre>
  964. <p>This returns 144 because '+' has turned into '*', and 'a' is the internal 'a',
  965. not the argument 'a'. We get <code>(* 12 12)</code> where we might have expected
  966. <code>(+ 12 1)</code>.
  967. Starting with the '+' problem,
  968. as long as the redefinition of '+' is local (that is, it happens after the macro definition), we can unquote the +:
  969. </p>
  970. <pre class="indented">
  971. &gt; (define-macro (mac b)
  972. `(let ((a 12))
  973. (,+ a ,b))) ; ,+ picks up the definition-time +
  974. <em class="gray">mac</em>
  975. &gt; (let ((a 1) (+ *)) (mac a))
  976. <em class="gray">24 ; (+ a a) where a is 12</em>
  977. </pre>
  978. <p>But the unquote trick won't work if we have previously loaded some file that redefined '+'
  979. at the top-level (so at macro definition time, + is *, but we want the built-in +).
  980. Although this example is silly, the problem is real in Scheme
  981. because Scheme has no reserved words and only one name space.
  982. </p>
  983. <pre class="indented">
  984. &gt; (define + *)
  985. <em class="gray">+</em>
  986. &gt; (define (add a b) (+ a b))
  987. <em class="gray">add</em>
  988. &gt; (add 2 3)
  989. <em class="gray">6</em>
  990. &gt; (define (divide a b) (/ a b))
  991. <em class="gray">divide</em>
  992. &gt; (divide 2 3)
  993. <em class="gray">2/3</em>
  994. &gt; (set! / -) ; a bad idea &mdash; this turns off s7's optimizer
  995. <em class="gray">-</em>
  996. &gt; (divide 2 3)
  997. <em class="gray">-1</em>
  998. </pre>
  999. <p>Obviously macros are not the problem here. Since
  1000. we might be loading
  1001. code written by others, it's sometimes hard to tell what names
  1002. that code depends on or redefines.
  1003. We need a way to get the pristine (start-up, built-in) value of '+'.
  1004. One long-winded way in s7 uses <a href="#unlet">unlet</a>:
  1005. </p>
  1006. <pre class="indented">
  1007. &gt; (define + *)
  1008. <em class="gray">+</em>
  1009. &gt; (define (add a b) (with-let (unlet) (+ a b)))
  1010. <em class="gray">add</em>
  1011. &gt; (add 2 3)
  1012. <em class="gray">5</em>
  1013. </pre>
  1014. <p>But this is hard to read, and it's not inconceivable that we might want all three
  1015. values of a symbol, the start-up value, the definition-time value, and the
  1016. current value. The latter can be accessed with the bare symbol, the definition-time
  1017. value with unquote (','), and the start-up value with either unlet
  1018. or #_&lt;name&gt;. That is, #_+ is a reader macro for <code>(with-let (unlet) +)</code>.
  1019. </p>
  1020. <pre class="indented">
  1021. &gt; (define-macro (mac b)
  1022. `(<em class=red>#_let</em> ((a 12))
  1023. (<em class=red>#_+</em> a ,b))) ; #_+ and #_let are start-up values
  1024. <em class="gray">mac</em>
  1025. &gt; (let ((a 1) (+ *)) (mac a))
  1026. <em class="gray">24 ; (+ a a) where a is 12 and + is the start-up +</em>
  1027. ;;; make + generic (there's a similar C-based example below)
  1028. &gt; (define (+ . args)
  1029. (if (null? args) 0
  1030. (apply (if (number? (car args)) <em class=red>#_+ #_string-append</em>) args)))
  1031. <em class="gray">+</em>
  1032. &gt; (+ 1 2)
  1033. <em class="gray">3</em>
  1034. &gt; (+ "hi" "ho")
  1035. <em class="gray">"hiho"</em>
  1036. </pre>
  1037. <p>#_&lt;name&gt; could be implemented via *#readers*:
  1038. </p>
  1039. <pre class="indented">
  1040. (set! *#readers*
  1041. (cons (cons #\_ (lambda (str)
  1042. (with-let (unlet)
  1043. (string-&gt;symbol (substring str 1)))))
  1044. *#readers*))
  1045. </pre>
  1046. <p>
  1047. So, now we have only the variable capture problem ('a' has been captured in the preceding examples).
  1048. This is the only thing that the gigantic "hygienic macro" systems actually deal with:
  1049. a microscopic problem that you'd think, from the hype, was up there with malaria and the
  1050. national debt. gensym is the standard approach:
  1051. </p>
  1052. <pre class="indented">
  1053. &gt; (define-macro (mac b)
  1054. (let ((var (<em class=red>gensym</em>)))
  1055. `(#_let ((,var 12))
  1056. (#_+ ,var ,b))))
  1057. <em class="gray">mac</em>
  1058. &gt; (let ((a 1) (+ *)) (mac a))
  1059. <em class="gray">13</em>
  1060. ;; or use lambda:
  1061. &gt; (define-macro (mac b)
  1062. `((lambda (b) (let ((a 12)) (#_+ a b))) ,b))
  1063. <em class="gray">mac</em>
  1064. &gt; (let ((a 1) (+ *)) (mac a))
  1065. <em class="gray">13</em>
  1066. </pre>
  1067. <p>But in s7, the simplest approach uses environments. You have complete
  1068. control over the environment at any point:
  1069. </p>
  1070. <pre>
  1071. (define-macro (mac b)
  1072. `(with-let (inlet 'b ,b)
  1073. (let ((a 12))
  1074. (+ a b))))
  1075. &gt; (let ((a 1) (+ *)) (mac a))
  1076. <em class="gray">13</em>
  1077. (define-macro (mac1 . b) ; originally `(let ((a 12)) (+ a ,@b ,@b))
  1078. `(with-let (inlet 'e (curlet)) ; this 'e will not collide with the calling env
  1079. (let ((a 12)) ; nor will 'a (so no gensyms are needed etc)
  1080. (+ a (with-let e ,@b) (with-let e ,@b)))))
  1081. &gt; (let ((a 1) (e 2)) (mac1 (display a) (+ a e)))
  1082. <em class="gray">18</em> ; (and it displays "11")
  1083. (define-macro (mac2 x) ; this will use mac2's definition environment for its body
  1084. `(with-let (sublet (funclet mac2) :x ,x)
  1085. (let ((a 12))
  1086. (+ a b x)))) ; a is always 12, b is whatever b happens to be in mac2's env
  1087. &gt; (define b 10) ; this is mac2's b
  1088. <em class="gray">10</em>
  1089. &gt; (let ((+ *) (a 1) (b 15)) (mac2 (+ a b)))
  1090. <em class="gray">37</em> ; mac2 uses its own a (12), b (10), and + (+)
  1091. ; but (+ a b) is 15 because at that point + is *: (* 1 15)
  1092. </pre>
  1093. <p>Hygienic macros are trivial! So s7 does not have syntax-rules because it is not needed.
  1094. s7's lint.scm will warn you about any such problematic macro expansion, so I'd
  1095. say just write macros as simply as possible, then let lint tell you
  1096. that it's time to do the with-let shuffle. When that happens, wrap the macro body in
  1097. a with-let that captures the current environment, and at each use of a macro argument
  1098. wrap it in a with-let that re-establishes that environment.
  1099. </p>
  1100. <div class="indented">
  1101. <pre>
  1102. (define-macro (swap a b) ; assume a and b are symbols
  1103. `(with-let (inlet 'e (curlet) 'tmp ,a)
  1104. (set! (e ',a) (e ',b))
  1105. (set! (e ',b) tmp)))
  1106. &gt; (let ((b 1) (tmp 2)) (swap b tmp) (list b tmp))
  1107. <em class="gray">(2 1)</em>
  1108. (define-macro (swap a b) ; here a and b can be any settable expressions
  1109. `(set! ,b (with-let (inlet 'e (curlet) 'tmp ,a)
  1110. (with-let e (set! ,a ,b))
  1111. tmp)))
  1112. &gt; (let ((v (vector 1 2))) (swap (v 0) (v 1)) v)
  1113. <em class="gray">#(2 1)</em>
  1114. &gt; (let ((tmp (cons 1 2))) (swap (car tmp) (cdr tmp)) tmp)
  1115. <em class="gray">(2 . 1)</em>
  1116. (set! (procedure-setter swap) (define-macro (set-swap a b c) `(set! ,b ,c)))
  1117. &gt; (let ((a 1) (b 2) (c 3) (d 4)) (swap a (swap b (swap c d))) (list a b c d))
  1118. <em class="gray">(2 3 4 1)</em>
  1119. ;;; but this is simpler:
  1120. (define-macro (rotate! . args)
  1121. `(set! ,(args (- (length args) 1))
  1122. (with-let (inlet 'e (curlet) 'tmp ,(car args))
  1123. (with-let e
  1124. ,@(map (lambda (a b) `(set! ,a ,b)) args (cdr args)))
  1125. tmp)))
  1126. &gt; (let ((a 1) (b 2) (c 3)) (rotate! a b c) (list a b c))
  1127. <em class="gray">(2 3 1)</em>
  1128. </pre>
  1129. </div>
  1130. <p>
  1131. If you want the macro's expanded result
  1132. to be evaluated in its definition environment:
  1133. </p>
  1134. <pre>
  1135. (let ((a 3))
  1136. (define-macro (mac b)
  1137. `(with-let (inlet 'b ,b (funclet mac))
  1138. (+ a b))) ; definition-time "a", call-time "b"
  1139. (define-macro (mac-1 b)
  1140. `(+ a ,b)) ; call-time "a" and "b"
  1141. (let ((a 32))
  1142. (list (mac 1)
  1143. (mac-1 1))))
  1144. </pre>
  1145. <!--
  1146. (define (tree-quote tree args)
  1147. (if (pair? tree)
  1148. (if (eq? (car tree) 'quote)
  1149. tree
  1150. (cons (tree-quote (car tree) args)
  1151. (tree-quote (cdr tree) args)))
  1152. (if (memq tree args)
  1153. (list 'quote tree)
  1154. tree)))
  1155. (define-macro (define-hacro name-and-args . body)
  1156. (let ((name (car name-and-args))
  1157. (args (cdr name-and-args)))
  1158. `(define-macro ,name-and-args
  1159. (list 'with-let
  1160. (list 'inlet ,@(map (lambda (arg)
  1161. (values (symbol->keyword arg) arg))
  1162. args))
  1163. ,@(tree-quote body args)))))
  1164. ; (define-hacro (mac a b) `(+ ,a ,b))
  1165. ; (macroexpand (mac 2 3))
  1166. ; (with-let (inlet :a 2 :b 3) (+ a b))
  1167. ; (procedure-source mac)
  1168. ; (lambda (a b) (list 'with-let (list 'inlet :a a :b b) ({list} '+ 'a 'b)))
  1169. -->
  1170. <div class="indented">
  1171. <p>Here is Peter Seibel's wonderful once-only macro:
  1172. </p>
  1173. <pre class="indented">
  1174. (define-macro (once-only names . body)
  1175. (let ((gensyms (map (lambda (n) (gensym)) names)))
  1176. `(let (,@(map (lambda (g) (list g '(gensym))) gensyms))
  1177. `(let (,,@(map (lambda (g n) (list list g n)) gensyms names))
  1178. ,(let (,@(map list names gensyms))
  1179. ,@body)))))
  1180. </pre>
  1181. <!-- this was:
  1182. (define-macro (once-only names . body)
  1183. (let ((gensyms (map (lambda (n) (gensym)) names)))
  1184. `(let (,@(map (lambda (g) `(,g (gensym))) gensyms))
  1185. `(let (,,@(map (lambda (g n) ``(,,g ,,n)) gensyms names))
  1186. ,(let (,@(map (lambda (n g) `(,n ,g)) names gensyms))
  1187. ,@body)))))
  1188. -->
  1189. <p>From the land of sparkling bacros:
  1190. </p>
  1191. <pre class="indented">
  1192. (define once-only
  1193. (let ((names (gensym))
  1194. (body (gensym)))
  1195. (apply define-bacro `((,(gensym) ,names . ,body)
  1196. `(let (,@(map (lambda (name) `(,name ,(eval name))) ,names))
  1197. ,@,body)))))
  1198. </pre>
  1199. <p>Sadly, with-let is simpler.
  1200. </p>
  1201. </div>
  1202. </blockquote>
  1203. <!--
  1204. when is (define-macro (f a) `(+ ,a 1)) not the same as (define (f a) (+ a 1))?
  1205. (f (values 2 3))
  1206. (f most-positive-fixnum) but only because the optimizer messes this up
  1207. -->
  1208. <div class="header" id="pws"><h4>procedure-setter</h4></div>
  1209. <pre class="indented">
  1210. (<em class=def>procedure-setter</em> proc)
  1211. (<em class=def id="dilambda">dilambda</em> proc setter)
  1212. </pre>
  1213. <p>Each function (or macro!) can have an associated setter, much like defsetf in CL. As a convenience, there's also
  1214. a way to associate the two functions under one name: dilambda.
  1215. The setter is called when the procedure is the target of set! Its last argument is the
  1216. value passed to set!:
  1217. </p>
  1218. <pre class="indented">
  1219. &gt; (procedure-setter cadr)
  1220. <em class="gray">#f</em>
  1221. &gt; (set! (procedure-setter cadr)
  1222. (lambda (lst val)
  1223. (set! (car (cdr lst)) val)))
  1224. <em class="gray">#&lt;lambda (lst val)&gt;</em>
  1225. &gt; (procedure-source (procedure-setter cadr))
  1226. <em class="gray">(lambda (lst val) (set! (car (cdr lst)) val))</em>
  1227. &gt; (let ((lst (list 1 2 3)))
  1228. (set! (cadr lst) 4)
  1229. lst)
  1230. <em class="gray">(1 4 3)</em>
  1231. </pre>
  1232. <p>In some cases, the setter needs to be a macro:
  1233. </p>
  1234. <pre class="indented">
  1235. &gt; (set! (procedure-setter logbit?)
  1236. (define-macro (m var index on) ; here we want to set "var", so we need a macro
  1237. `(if ,on
  1238. (set! ,var (logior ,var (ash 1 ,index)))
  1239. (set! ,var (logand ,var (lognot (ash 1 ,index)))))))
  1240. <em class="gray">m</em>
  1241. &gt; (define (mingle a b)
  1242. (let ((r 0))
  1243. (do ((i 0 (+ i 1)))
  1244. ((= i 31) r)
  1245. (set! (logbit? r (* 2 i)) (logbit? a i))
  1246. (set! (logbit? r (+ (* 2 i) 1)) (logbit? b i)))))
  1247. <em class="gray">mingle</em>
  1248. &gt; (mingle 6 3) ; the INTERCAL mingle operator?
  1249. <em class="gray">30</em>
  1250. </pre>
  1251. <blockquote>
  1252. <div class="indented">
  1253. <p>Here is a pretty example of dilambda:
  1254. </p>
  1255. <pre class="indented">
  1256. (define-macro (c?r path)
  1257. ;; "path" is a list and "X" marks the spot in it that we are trying to access
  1258. ;; (a (b ((c X)))) &mdash; anything after the X is ignored, other symbols are just placeholders
  1259. ;; c?r returns a dilambda that gets/sets X
  1260. (define (X-marks-the-spot accessor tree)
  1261. (if (pair? tree)
  1262. (or (X-marks-the-spot (cons 'car accessor) (car tree))
  1263. (X-marks-the-spot (cons 'cdr accessor) (cdr tree)))
  1264. (and (eq? tree 'X) accessor)))
  1265. (let ((body 'lst))
  1266. (for-each
  1267. (lambda (f)
  1268. (set! body (list f body)))
  1269. (reverse (X-marks-the-spot () path)))
  1270. `(<em class=red>dilambda</em>
  1271. (lambda (lst)
  1272. ,body)
  1273. (lambda (lst val)
  1274. (set! ,body val)))))
  1275. &gt; ((c?r (a b (X))) '(1 2 (3 4) 5))
  1276. <em class="gray">3</em>
  1277. &gt; (let ((lst (list 1 2 (list 3 4) 5)))
  1278. (set! ((c?r (a b (X))) lst) 32)
  1279. lst)
  1280. <em class="gray">(1 2 (32 4) 5)</em>
  1281. &gt; (procedure-source (c?r (a b (X))))
  1282. <em class="gray">(lambda (lst) (car (car (cdr (cdr lst)))))</em>
  1283. &gt; ((c?r (a b . X)) '(1 2 (3 4) 5))
  1284. <em class="gray">((3 4) 5)</em>
  1285. &gt; (let ((lst (list 1 2 (list 3 4) 5)))
  1286. (set! ((c?r (a b . X)) lst) '(32))
  1287. lst)
  1288. <em class="gray">(1 2 32)</em>
  1289. &gt; (procedure-source (c?r (a b . X)))
  1290. <em class="gray">(lambda (lst) (cdr (cdr lst)))</em>
  1291. &gt; ((c?r (((((a (b (c (d (e X)))))))))) '(((((1 (2 (3 (4 (5 6))))))))))
  1292. <em class="gray">6</em>
  1293. &gt; (let ((lst '(((((1 (2 (3 (4 (5 6)))))))))))
  1294. (set! ((c?r (((((a (b (c (d (e X)))))))))) lst) 32)
  1295. lst)
  1296. <em class="gray">(((((1 (2 (3 (4 (5 32)))))))))</em>
  1297. &gt; (procedure-source (c?r (((((a (b (c (d (e X)))))))))))
  1298. <em class="gray">(lambda (lst) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (car (car (car lst)))))))))))))))</em>
  1299. </pre>
  1300. </div>
  1301. <div class="indented">
  1302. <p>Speaking of INTERCAL, COME-FROM:
  1303. </p>
  1304. <pre class="indented">
  1305. (define-macro (define-with-goto-and-come-from name-and-args . body)
  1306. (let ((labels ())
  1307. (gotos ())
  1308. (come-froms ()))
  1309. (let collect-jumps ((tree body))
  1310. (when (pair? tree)
  1311. (when (pair? (car tree))
  1312. (case (caar tree)
  1313. ((label) (set! labels (cons tree labels)))
  1314. ((goto) (set! gotos (cons tree gotos)))
  1315. ((come-from) (set! come-froms (cons tree come-froms)))
  1316. (else (collect-jumps (car tree)))))
  1317. (collect-jumps (cdr tree))))
  1318. (for-each
  1319. (lambda (goto)
  1320. (let* ((name (cadr (cadar goto)))
  1321. (label (member name labels (lambda (a b) (eq? a (cadr (cadar b)))))))
  1322. (if label
  1323. (set-cdr! goto (car label))
  1324. (error 'bad-goto "can't find label: ~S" name))))
  1325. gotos)
  1326. (for-each
  1327. (lambda (from)
  1328. (let* ((name (cadr (cadar from)))
  1329. (label (member name labels (lambda (a b) (eq? a (cadr (cadar b)))))))
  1330. (if label
  1331. (set-cdr! (car label) from)
  1332. (error 'bad-come-from "can't find label: ~S" name))))
  1333. come-froms)
  1334. `(define ,name-and-args
  1335. (let ((label (lambda (name) #f))
  1336. (goto (lambda (name) #f))
  1337. (come-from (lambda (name) #f)))
  1338. ,@body))))
  1339. </pre>
  1340. </div>
  1341. </blockquote>
  1342. <div class="header" id="generalizedset"><h4>applicable objects, generalized set!, generic functions</h4></div>
  1343. <p>A procedure with a setter can be viewed as one generalization of set!. Another
  1344. treats objects as having predefined get and set functions. In s7
  1345. lists, strings, vectors, hash-tables, environments, and any cooperating C or Scheme-defined objects
  1346. are both applicable and settable. newLisp calls this implicit indexing, Kawa has it, Gauche implements it
  1347. via object-apply, Guile via procedure-with-setter; CL's funcallable instance might be the same idea.
  1348. </p>
  1349. <p>
  1350. In <code>(vector-ref #(1 2) 0)</code>, for example, vector-ref is just a type
  1351. declaration. But in Scheme, type declarations are unnecessary, so we get exactly
  1352. the same result from <code>(#(1 2) 0)</code>. Similarly, <code>(lst 1)</code> is the
  1353. same as <code>(list-ref lst 1)</code>, and <code>(set! (lst 1) 2)</code> is the same
  1354. as <code>(list-set! lst 1 2)</code>.
  1355. I like this syntax: the less noise, the better!
  1356. </p>
  1357. <blockquote>
  1358. <div class="indented">
  1359. <p>Well, maybe applicable strings look weird: <code>("hi" 1)</code> is #\i, but worse,
  1360. so is <code>(cond (1 =&gt; "hi"))</code>! Even though a string, list, or vector is "applicable", it is
  1361. not currently considered to be a procedure, so <code>(procedure? "hi")</code> is #f. map and for-each, however,
  1362. accept anything that apply can handle, so
  1363. <code>(map #(0 1) '(1 0))</code> is '(1 0). (On the first call to map in this case, you get the result of
  1364. <code>(#(0 1) 1)</code> and so on).
  1365. string-&gt;list, vector-&gt;list, and let-&gt;list are <code>(map values object)</code>.
  1366. Their inverses are (and always have been) equally trivial.
  1367. </p>
  1368. <p>The applicable object syntax makes it easy to write generic functions.
  1369. For example, s7test.scm has implementations of Common Lisp's sequence functions.
  1370. length, copy, reverse, fill!, iterate, map and for-each are generic in this sense (map always returns a list).
  1371. </p>
  1372. <pre class="indented">
  1373. &gt; (map (lambda (a b) (- a b)) (list 1 2) (vector 3 4))
  1374. <em class="gray">(5 -3 9)</em>
  1375. &gt; (length "hi")
  1376. <em class="gray">2</em>
  1377. </pre>
  1378. <p>
  1379. Here's a generic FFT:
  1380. </p>
  1381. <pre class="indented">
  1382. (define* (cfft! data n (dir 1)) ; (complex data)
  1383. (if (not n) (set! n (length data)))
  1384. (do ((i 0 (+ i 1))
  1385. (j 0))
  1386. ((= i n))
  1387. (if (&gt; j i)
  1388. (let ((temp (data j)))
  1389. (set! (data j) (data i))
  1390. (set! (data i) temp)))
  1391. (do ((m (/ n 2)))
  1392. ((or (&lt; m 2)
  1393. (&lt; j m))
  1394. (set! j (+ j m)))
  1395. (set! j (- j m))
  1396. (set! m (/ m 2))))
  1397. (do ((ipow (floor (log n 2)))
  1398. (prev 1)
  1399. (lg 0 (+ lg 1))
  1400. (mmax 2 (* mmax 2))
  1401. (pow (/ n 2) (/ pow 2))
  1402. (theta (complex 0.0 (* pi dir)) (* theta 0.5)))
  1403. ((= lg ipow))
  1404. (let ((wpc (exp theta))
  1405. (wc 1.0))
  1406. (do ((ii 0 (+ ii 1)))
  1407. ((= ii prev))
  1408. (do ((jj 0 (+ jj 1))
  1409. (i ii (+ i mmax))
  1410. (j (+ ii prev) (+ j mmax)))
  1411. ((&gt;= jj pow))
  1412. (let ((tc (* wc (data j))))
  1413. (set! (data j) (- (data i) tc))
  1414. (set! (data i) (+ (data i) tc))))
  1415. (set! wc (* wc wpc)))
  1416. (set! prev mmax)))
  1417. data)
  1418. &gt; (cfft! (list 0.0 1+i 0.0 0.0))
  1419. <em class="gray">(1+1i -1+1i -1-1i 1-1i)</em>
  1420. &gt; (cfft! (vector 0.0 1+i 0.0 0.0))
  1421. <em class="gray">#(1+1i -1+1i -1-1i 1-1i)</em>
  1422. </pre>
  1423. <p>And a generic function that copies one sequence's elements into another sequence:
  1424. </p>
  1425. <pre class="indented">
  1426. (define (copy-into source dest) ; this is equivalent to (copy source dest)
  1427. (do ((i 0 (+ i 1)))
  1428. ((= i (min (length source) (length dest)))
  1429. dest)
  1430. (set! (dest i) (source i))))
  1431. </pre>
  1432. <p>but that is already built-in as the two-argument version of the copy function.
  1433. </p>
  1434. </div>
  1435. <div class="indented">
  1436. <p>There is one place where list-set! and friends are not the same as set!: the former
  1437. evaluate their first argument, but set! does not (with a quibble; see below):
  1438. </p>
  1439. <pre class="indented">
  1440. &gt; (let ((str "hi")) (string-set! (let () str) 1 #\a) str)
  1441. <em class="gray">"ha"</em>
  1442. &gt; (let ((str "hi")) (set! (let () str) 1 #\a) str)
  1443. <em class="gray">;((let () str) 1 #\a): too many arguments to set!</em>
  1444. &gt; (let ((str "hi")) (set! ((let () str) 1) #\a) str)
  1445. <em class="gray">"ha"</em>
  1446. &gt; (let ((str "hi")) (set! (str 1) #\a) str)
  1447. <em class="gray">"ha"</em>
  1448. </pre>
  1449. <p>set! looks at its first argument to decide what to set.
  1450. If it's a symbol, no problem. If it's a list, set! looks at its car to see if it is
  1451. some object that has a setter. If the car is itself a list, set! evaluates the internal
  1452. expression, and tries again. So the second case above is the only one that won't work.
  1453. And of course:
  1454. </p>
  1455. <pre class="indented">
  1456. &gt; (let ((x (list 1 2)))
  1457. (set! ((((lambda () (list x))) 0) 0) 3)
  1458. x)
  1459. <em class="gray">(3 2)</em>
  1460. </pre>
  1461. </div>
  1462. <div class="indented">
  1463. <p>By my count, around 20 of the Scheme built-in functions are already generic in the sense
  1464. that they accept arguments of many types (leaving aside the numeric and type checking functions, take for example equal?, display,
  1465. member, assoc, apply, eval, quasiquote, and values). s7 extends that list with map, for-each, reverse,
  1466. and length, and adds a few others such as copy, fill!, sort!, object-&gt;string, object-&gt;let, and append.
  1467. newLisp takes a more radical approach than s7: it extends operators such as '&gt;'
  1468. to compare strings and lists, as well as numbers. In map and for-each, however, you can mix the argument
  1469. types, so I'm not as attracted to making '&gt;' generic; you can't, for example, <code>(&gt; "hi" 32.1)</code>,
  1470. or even <code>(&gt; 1 0+i)</code>.
  1471. </p>
  1472. </div>
  1473. </blockquote>
  1474. <div class="separator"></div>
  1475. <p>The somewhat non-standard generic sequence functions in s7 are:
  1476. </p>
  1477. <pre class="indented">
  1478. (<em class=def id="sortb">sort!</em> sequence less?)
  1479. (<em class=def id="reverseb">reverse!</em> sequence) and (reverse sequence)
  1480. (<em class=def id="fillb">fill!</em> sequence value (start 0) end)
  1481. (<em class=def id="s7copy">copy</em> obj) and (copy source destination (start 0) end)
  1482. (<em class=def id="objecttostring">object-&gt;string</em> obj)
  1483. (object-&gt;let obj)
  1484. (length obj)
  1485. (append . sequences)
  1486. (map func . sequences) and (for-each func . sequences)
  1487. (<a href="#morallyequalp">morally-equal?</a> obj1 obj2)
  1488. </pre>
  1489. <p><b>reverse!</b> is an in-place version of reverse. That is,
  1490. it modifies the sequence passed to it in the process of reversing its contents.
  1491. If the sequence is a list, remember to use set!:
  1492. <code>(set! p (reverse! p))</code>. This is somewhat inconsistent with other cases,
  1493. but historically, lisp programmers have treated the in-place reverse as the fast
  1494. version, so s7 follows suit.
  1495. </p>
  1496. <p>Leaving aside the weird list case,
  1497. <b>append</b> returns a sequence of the same type as its first argument.
  1498. </p>
  1499. <pre class="indented">
  1500. &gt; (append #(1 2) '(3 4))
  1501. <em class="gray">#(1 2 3 4)</em>
  1502. &gt; (append (float-vector) '(1 2) (byte-vector 3 4))
  1503. <em class="gray">(float-vector 1.0 2.0 3.0 4.0)</em>
  1504. </pre>
  1505. <p>
  1506. <b>sort!</b> sorts a sequence using the
  1507. function passed as its second argument:
  1508. </p>
  1509. <pre class="indented">
  1510. &gt; (sort! (list 3 4 8 2 0 1 5 9 7 6) &lt;)
  1511. <em class="gray">(0 1 2 3 4 5 6 7 8 9)</em>
  1512. </pre>
  1513. <p>Underlying some of these functions are generic iterators, also built-into s7:
  1514. </p>
  1515. <pre class="indented">
  1516. (<em class=def id="makeiterator">make-iterator</em> sequence)
  1517. (<em class=def id="iteratorp">iterator?</em> obj)
  1518. (<em class=def id="iterate">iterate</em> iterator)
  1519. (<em class=def id="iteratorsequence">iterator-sequence</em> iterator)
  1520. (<em class=def id="iteratoratend">iterator-at-end?</em> iterator)
  1521. </pre>
  1522. <p><b>make-iterator</b> takes a sequence argument and returns an iterator object that traverses
  1523. that sequence as it is called. The iterator itself can be treated as a function of no arguments,
  1524. or (for code clarity) it can be the argument to <b>iterate</b>, which does the same thing.
  1525. That is <code>(iter)</code> is the same as <code>(iterate iter)</code>. The sequence that an iterator is traversing
  1526. is <b>iterator-sequence</b>.
  1527. </p>
  1528. <p>
  1529. If the sequence is a hash-table or let, the iterator normally returns a cons of the key and value.
  1530. There are many cases where this overhead is objectionable, so make-iterator takes a third optional
  1531. argument, the cons to use (changing its car and cdr directly on each call).
  1532. </p>
  1533. <p>When an iterator reaches the end of its sequence, it returns #&lt;eof&gt;. It used to
  1534. return nil; I can't decide whether this change is an improvement. If an iterator over a
  1535. list notices that its list is circular, it returns #&lt;eof&gt;. map and for-each use
  1536. iterators, so if you pass a circular list to either, it will stop eventually. (An
  1537. arcane consequence for method writers: specialize make-iterator, not map or for-each).
  1538. </p>
  1539. <pre class="indented">
  1540. (define (find-if f sequence)
  1541. (let ((iter (make-iterator sequence)))
  1542. (do ((x (iter) (iter)))
  1543. ((or (eof-object? x) (f x))
  1544. (and (not (eof-object? x)) x)))))
  1545. </pre>
  1546. <p>But of course a sequence might contain #&lt;eof&gt;! So to be really safe, use iterator-at-end?
  1547. instead of eof-object?.
  1548. </p>
  1549. <p>The argument to make-iterator can also be a function or macro.
  1550. There should be a variable named 'iterator with a non-#f
  1551. value in the closure's environment:
  1552. </p>
  1553. <pre class="indented">
  1554. (define (make-circular-iterator obj)
  1555. (let ((iter (make-iterator obj)))
  1556. (make-iterator
  1557. (let ((iterator? #t))
  1558. (lambda ()
  1559. (let ((result (iter)))
  1560. (if (eof-object? result)
  1561. ((set! iter (make-iterator obj)))
  1562. result)))))))
  1563. </pre>
  1564. <p>The 'iterator? variable is similar to the 'documentation variable used by procedure-documentation.
  1565. It gives make-iterator some hope of catching inadvertent bogus function arguments that would
  1566. otherwise cause an infinite loop.
  1567. </p>
  1568. <div class="header" id="multidimensionalvectors"><h4>multidimensional vectors</h4></div>
  1569. <p>
  1570. s7 supports
  1571. vectors with any number of dimensions. It is here, in particular, that generalized
  1572. set! shines. make-vector's second argument can be a list of dimensions, rather than
  1573. an integer as in the one dimensional case:
  1574. </p>
  1575. <pre class="indented">
  1576. (make-vector (list 2 3 4))
  1577. (make-vector '(2 3) 1.0)
  1578. (vector-dimensions (make-vector '(2 3 4))) -&gt; (2 3 4)
  1579. </pre>
  1580. <p>The second example includes the optional initial element.
  1581. <code>(vect i ...)</code> or <code>(vector-ref vect i ...)</code> return the given
  1582. element, and <code>(set! (vect i ...) value)</code> and <code>(vector-set! vect i ... value)</code>
  1583. set it. vector-length (or just length) returns the total number of elements.
  1584. vector-dimensions returns a list of the dimensions.
  1585. </p>
  1586. <pre class="indented">
  1587. &gt; (define v (make-vector '(2 3) 1.0))
  1588. <em class="gray">#2D((1.0 1.0 1.0) (1.0 1.0 1.0))</em>
  1589. &gt; (set! (v 0 1) 2.0)
  1590. <em class="gray">#2D((1.0 2.0 1.0) (1.0 1.0 1.0))</em>
  1591. &gt; (v 0 1)
  1592. <em class="gray">2.0</em>
  1593. &gt; (vector-length v)
  1594. <em class="gray">6</em>
  1595. </pre>
  1596. <p>This function initializes each element of a multidimensional vector:
  1597. </p>
  1598. <pre class="indented">
  1599. (define (make-array dims . inits)
  1600. (make-shared-vector (apply vector (flatten inits)) dims))
  1601. &gt; (make-array '(3 3) '(1 1 1) '(2 2 2) '(3 3 3))
  1602. <em class="gray">#2D((1 1 1) (2 2 2) (3 3 3))</em>
  1603. </pre>
  1604. <p>make-int-vector and make-float-vector produce homogeneous vectors holding
  1605. s7_ints or s7_doubles.
  1606. These are mostly useful in conjunction with C code. These
  1607. homogeneous vector functions are currently built-in:
  1608. </p>
  1609. <pre class="indented">
  1610. (<em class=def>float-vector?</em> obj)
  1611. (<em class=def>float-vector</em> . args)
  1612. (<em class=def>make-float-vector</em> len (init 0.0))
  1613. (<em class=def>float-vector-ref</em> obj . indices)
  1614. (<em class=def>float-vector-set!</em> obj indices[...] value)
  1615. (<em class=def id="intvectorp">int-vector?</em> obj)
  1616. (<em class=def id="intvector">int-vector</em> . args)
  1617. (<em class=def id="makeintvector">make-int-vector</em> len (init 0))
  1618. (<em class=def id="intvectorref">int-vector-ref</em> obj . indices)
  1619. (<em class=def id="intvectorset">int-vector-set!</em> obj indices[...] value)
  1620. </pre>
  1621. <div class="indented">
  1622. <p>And also, for completeness:</p>
  1623. <pre class="indented">
  1624. (<em class=def id="bytevectorp">byte-vector?</em> obj)
  1625. (<em class=def id="bytevector">byte-vector</em> . args)
  1626. (<em class=def id="makebytevector">make-byte-vector</em> len (init 0))
  1627. (<em class=def id="stringtobytevector">string-&gt;byte-vector</em> str)
  1628. </pre>
  1629. <p>but these are really just strings in disguise.</p>
  1630. </div>
  1631. <p>To access a vector's elements with different dimensions than the original had, use
  1632. <code>(make-shared-vector original-vector new-dimensions (offset 0))</code>:
  1633. </p>
  1634. <pre class="indented">
  1635. &gt; (let ((v1 #2d((1 2 3) (4 5 6))))
  1636. (let ((v2 (make-shared-vector v1 '(6)))) ; flatten the original
  1637. v2))
  1638. <em class="gray">#(1 2 3 4 5 6)</em>
  1639. &gt; (let ((v1 #(1 2 3 4 5 6)))
  1640. (let ((v2 (make-shared-vector v1 '(3 2))))
  1641. v2))
  1642. <em class="gray">#2D((1 2) (3 4) (5 6))</em>
  1643. </pre>
  1644. <blockquote>
  1645. <div class="indented">
  1646. <p>matrix multiplication:
  1647. </p>
  1648. <pre>
  1649. (define (matrix-multiply A B)
  1650. ;; assume square matrices and so on for simplicity
  1651. (let ((size (car (vector-dimensions A))))
  1652. (do ((C (make-vector (list size size) 0))
  1653. (i 0 (+ i 1)))
  1654. ((= i size) C)
  1655. (do ((j 0 (+ j 1)))
  1656. ((= j size))
  1657. (do ((sum 0)
  1658. (k 0 (+ k 1)))
  1659. ((= k size)
  1660. (set! (C i j) sum))
  1661. (set! sum (+ sum (* (A i k) (B k j)))))))))
  1662. </pre>
  1663. </div>
  1664. <div class="indented">
  1665. <p>Conway's game of Life:
  1666. </p>
  1667. <pre>
  1668. (define* (life (width 40) (height 40))
  1669. (let ((state0 (make-vector (list width height) 0))
  1670. (state1 (make-vector (list width height) 0)))
  1671. ;; initialize with some random pattern
  1672. (do ((x 0 (+ x 1)))
  1673. ((= x width))
  1674. (do ((y 0 (+ y 1)))
  1675. ((= y height))
  1676. (set! (state0 x y) (if (&lt; (random 100) 15) 1 0))))
  1677. (do () ()
  1678. ;; show current state (using terminal escape sequences, borrowed from the Rosetta C code)
  1679. (format *stderr* "~C[H" #\escape) ; ESC H = tab set
  1680. (do ((y 0 (+ y 1)))
  1681. ((= y height))
  1682. (do ((x 0 (+ x 1)))
  1683. ((= x width))
  1684. (format *stderr*
  1685. (if (zero? (state0 x y))
  1686. " " ; ESC 07m below = inverse
  1687. (values "~C[07m ~C[m" #\escape #\escape))))
  1688. (format *stderr* "~C[E" #\escape)) ; ESC E = next line
  1689. ;; get the next state
  1690. (do ((x 1 (+ x 1)))
  1691. ((= x (- width 1)))
  1692. (do ((y 1 (+ y 1)))
  1693. ((= y (- height 1)))
  1694. (let ((n (+ (state0 (- x 1) (- y 1))
  1695. (state0 x (- y 1))
  1696. (state0 (+ x 1) (- y 1))
  1697. (state0 (- x 1) y)
  1698. (state0 (+ x 1) y)
  1699. (state0 (- x 1) (+ y 1))
  1700. (state0 x (+ y 1))
  1701. (state0 (+ x 1) (+ y 1)))))
  1702. (set! (state1 x y)
  1703. (if (or (= n 3)
  1704. (and (= n 2)
  1705. (not (zero? (state0 x y)))))
  1706. 1 0)))))
  1707. (do ((x 0 (+ x 1)))
  1708. ((= x width))
  1709. (do ((y 0 (+ y 1)))
  1710. ((= y height))
  1711. (set! (state0 x y) (state1 x y)))))))
  1712. </pre>
  1713. </div>
  1714. <div class="indented">
  1715. <p>Multidimensional vector constant syntax is modelled after CL: #nd(...) or #nD(...)
  1716. signals that the lists specify the elements of an 'n' dimensional vector: <code>#2D((1 2 3) (4 5 6))</code>
  1717. </p>
  1718. <pre class="indented">
  1719. &gt; (vector-ref #2D((1 2 3) (4 5 6)) 1 2)
  1720. <em class="gray">6</em>
  1721. &gt; (matrix-multiply #2d((-1 0) (0 -1)) #2d((2 0) (-2 2)))
  1722. <em class="gray">#2D((-2 0) (2 -2))</em>
  1723. </pre>
  1724. <p>If any dimension has 0 length, you get an n-dimensional empty vector. It is not
  1725. equal to a 1-dimensional empty vector.
  1726. </p>
  1727. <pre class="indented">
  1728. &gt; (make-vector '(10 0 3))
  1729. <em class="gray">#3D()</em>
  1730. &gt; (equal? #() #3D())
  1731. <em class="gray">#f</em>
  1732. </pre>
  1733. </div>
  1734. <div class="indented">
  1735. <p>To save on costly parentheses, and make it easier to write generic multidimensional sequence functions,
  1736. you can use this same syntax with lists.
  1737. </p>
  1738. <pre class="indented">
  1739. &gt; (let ((L '((1 2 3) (4 5 6))))
  1740. (L 1 0)) ; same as (list-ref (list-ref L 1) 0) or ((L 1) 0)
  1741. <em class="gray">4</em>
  1742. &gt; (let ((L '(((1 2 3) (4 5 6)) ((7 8 9) (10 11 12)))))
  1743. (set! (L 1 0 2) 32) ; same as (list-set! (list-ref (list-ref L 1) 0) 2 32) which is unreadable!
  1744. L)
  1745. <em class="gray">(((1 2 3) (4 5 6)) ((7 8 32) (10 11 12)))</em>
  1746. </pre>
  1747. <p>Or with vectors of vectors, of course:
  1748. </p>
  1749. <pre class="indented">
  1750. &gt; (let ((V #(#(1 2 3) #(4 5 6))))
  1751. (V 1 2)) ; same as (vector-ref (vector-ref V 1) 2) or ((V 1) 2)
  1752. <em class="gray">6</em>
  1753. &gt; (let ((V #2d((1 2 3) (4 5 6))))
  1754. (V 0))
  1755. <em class="gray">#(1 2 3)</em>
  1756. </pre>
  1757. <p>There's one difference between a vector-of-vectors and a multidimensional vector:
  1758. in the latter case, you can't clobber one of the inner vectors.
  1759. </p>
  1760. <pre class="indented">
  1761. &gt; (let ((V #(#(1 2 3) #(4 5 6)))) (set! (V 1) 32) V)
  1762. <em class="gray">#(#(1 2 3) 32)</em>
  1763. &gt; (let ((V #2d((1 2 3) (4 5 6)))) (set! (V 1) 32) V)
  1764. <em class="gray">;not enough args for vector-set!: (#2D((1 2 3) (4 5 6)) 1 32)</em>
  1765. </pre>
  1766. </div>
  1767. <div class="indented">
  1768. <p>Using lists to display the inner vectors may not be optimal, especially when the elements are also lists:
  1769. </p>
  1770. <pre class="indented">
  1771. #2D(((0) (0) ((0))) ((0) 0 ((0))))
  1772. </pre>
  1773. <p>The "#()" notation is no better (the elements can be vectors), and I'm not a fan of "[]" parentheses.
  1774. Perhaps we could use different colors? Or different size parentheses?
  1775. </p>
  1776. <pre class="indented">
  1777. #2D<em class=green>(</em><em class=red>(</em>(0) (0) ((0))<em class=red>)</em> <em class=red>(</em>(0) 0 ((0))<em class=red>)</em><em class=green>)</em>
  1778. #2D<em class="bigger">(</em><em class="big">(</em>(0) (0) ((0))<em class="big">)</em> <em class="big">(</em>(0) 0 ((0))<em class="big">)</em><em class="bigger">)</em>
  1779. </pre>
  1780. <p>A similar problem afflicts homogeneous vectors. We need some reasonable way to express
  1781. such a vector even when it has more than one dimension. My first thought was <code>#(...)#</code>,
  1782. but that makes <code>(let ((b1 0)) (#(1 2)#b1))</code> ambiguous.
  1783. </p>
  1784. </div>
  1785. <div class="indented">
  1786. <p>I'm not sure how to handle vector-&gt;list and list-&gt;vector in the multidimensional case.
  1787. Currently, vector-&gt;list flattens the vector, and list-&gt;vector always returns a
  1788. one dimensional vector, so the two are not inverses.
  1789. </p>
  1790. <pre class="indented">
  1791. &gt; (vector-&gt;list #2d((1 2) (3 4)))
  1792. <em class="gray">(1 2 3 4)</em> ; should this be '((1 2) (3 4)) or '(#(1 2) #(3 4))?
  1793. &gt; (list-&gt;vector '(#(1 2) #(3 4))) ; what about '((1 2) (3 4))?
  1794. <em class="gray">#(#(1 2) #(3 4)) </em>
  1795. </pre>
  1796. <p>
  1797. This also affects format and sort!:
  1798. </p>
  1799. <pre class="indented">
  1800. &gt; (format #f "~{~A~^ ~}" #2d((1 2) (3 4)))
  1801. <em class="gray">"1 2 3 4"</em>
  1802. &gt; (sort! #2d((1 4) (3 2)) &gt;)
  1803. <em class="gray">#2D((4 3) (2 1))</em>
  1804. </pre>
  1805. <p>Perhaps make-shared-vector can help:
  1806. </p>
  1807. <pre class="indented">
  1808. &gt;(make-shared-vector (list-&gt;vector '(1 2 3 4)) '(2 2))
  1809. <em class="gray">#2D((1 2) (3 4))</em>
  1810. </pre>
  1811. </div>
  1812. <div class="indented">
  1813. <p>Another question: should we accept the multi-index syntax in a case such as <code>
  1814. (#("abc" "def") 0 2)</code>?
  1815. My first thought was that the indices should all refer to the same
  1816. type of object, so s7 would complain in a mixed case like that.
  1817. If we can nest any applicable objects and apply the whole thing to
  1818. an arbitrary list of indices, ambiguities arise:
  1819. </p>
  1820. <pre class="indented">
  1821. ((lambda (x) x) "hi" 0)
  1822. ((lambda (x) (lambda (y) (+ x y))) 1 2)
  1823. </pre>
  1824. <p>I think these should complain that the function got too many arguments,
  1825. but from the implicit indexing point of view, they could be interpreted
  1826. as:
  1827. </p>
  1828. <pre class="indented">
  1829. (string-ref ((lambda (x) x) "hi") 0) ; i.e. (((lambda (x) x) "hi") 0)
  1830. (((lambda (x) (lambda (y) (+ x y))) 1) 2)
  1831. </pre>
  1832. <p>Add optional and rest arguments, and you can't tell who is supposed to
  1833. take which arguments.
  1834. Currently, you can mix types with implicit indices,
  1835. but a function grabs all remaining indices. Trickier than I expected!
  1836. </p>
  1837. </div>
  1838. </blockquote>
  1839. <div class="header" id="hashtables"><h4>hash-tables</h4></div>
  1840. <ul>
  1841. <li>(<em class=def id="makehashtable">make-hash-table</em> (size 8) eq-func)
  1842. <li>(<em class=def id="hashtable">hash-table</em> ...)
  1843. <li>(<em class=def id="hashtablestar">hash-table*</em> ...)
  1844. <li>(<em class=def id="hashtablep">hash-table?</em> obj)
  1845. <li>(<em class=def id="hashtableref">hash-table-ref</em> ht key)
  1846. <li>(<em class=def id="hashtableset">hash-table-set!</em> ht key value)
  1847. <li>(<em class=def id="hashtableentries">hash-table-entries</em> ht)
  1848. </ul>
  1849. <p>
  1850. Each hash-table keeps track of the keys it contains, optimizing the search wherever possible.
  1851. Any s7 object can be the key or the key's value.
  1852. If you pass a table size that is not a power of 2, make-hash-table rounds it up to the next power of 2.
  1853. The table grows as needed. length returns the current size.
  1854. If a key is not in the table, hash-table-ref returns #f. To remove a key,
  1855. set its value to #f; to remove all keys, <code>(fill! table #f)</code>.
  1856. </p>
  1857. <pre class="indented">
  1858. &gt; (let ((ht (make-hash-table)))
  1859. (set! (ht "hi") 123)
  1860. (ht "hi"))
  1861. <em class="gray">123</em>
  1862. </pre>
  1863. <p>hash-table (the function) parallels the functions vector, list, and string. Its arguments are conses containing key/value pairs.
  1864. The result is a new hash-table with those values preinstalled: <code>(hash-table '("hi" . 32) '("ho" . 1))</code>.
  1865. After much use, I now think it is more convenient here, as in inlet, to use hash-table*; its arguments are
  1866. simply the keys and values, without the consing: <code>(hash-table* 'a 1 'b 2)</code>.
  1867. Implicit indexing gives multilevel hashes:
  1868. </p>
  1869. <pre class="indented">
  1870. &gt; (let ((h (hash-table* 'a (hash-table* 'b 2 'c 3)))) (h 'a 'b))
  1871. <em class="gray">2</em>
  1872. &gt; (let ((h (hash-table* 'a (hash-table* 'b 2 'c 3)))) (set! (h 'a 'b) 4) (h 'a 'b))
  1873. <em class="gray">4</em>
  1874. </pre>
  1875. <blockquote>
  1876. <div class="indented">
  1877. <p>Since hash-tables accept the same applicable-object syntax that vectors use, we can
  1878. treat a hash-table as, for example, a sparse array:
  1879. </p>
  1880. <pre class="indented">
  1881. &gt; (define make-sparse-array make-hash-table)
  1882. <em class="gray">make-sparse-array</em>
  1883. &gt; (let ((arr (make-sparse-array)))
  1884. (set! (arr 1032) "1032")
  1885. (set! (arr -23) "-23")
  1886. (list (arr 1032) (arr -23)))
  1887. <em class="gray">("1032" "-23")</em>
  1888. </pre>
  1889. </div>
  1890. <div class="indented">
  1891. <p>map and for-each accept hash-table arguments. On each iteration, the map or for-each function is passed
  1892. an entry, <code>'(key . value)</code>, in whatever order the entries are encountered in the table.
  1893. </p>
  1894. <pre class="indented">
  1895. (define (hash-table-&gt;alist table)
  1896. (map values table))
  1897. (define (merge-hash-tables . tables) ; probably faster: (define merge-hash-tables append)
  1898. (apply hash-table (apply map values hash-tables)))
  1899. </pre>
  1900. <p>reverse of a hash-table returns a new table with the keys and values reversed.
  1901. fill! sets all the values.
  1902. Two hash-tables are equal if they have the same keys with the same values. This is independent
  1903. of the table sizes, or the order in which the key/value pairs were added.
  1904. </p>
  1905. </div>
  1906. <div class="indented">
  1907. <p>The third argument to make-hash-table (eq-func) is slightly complicated. If it is omitted,
  1908. s7 chooses the hashing equality and mapping functions based on the keys in the hash-table.
  1909. There are times when you know
  1910. in advance what equality function you want. If it's one of the built-in s7 equality
  1911. functions, eq?, eqv?, equal?, morally-equal?, =, string=?, string-ci=?, char=?, or char-ci=?,
  1912. you can pass that function as the third argument. In any other case, you need to
  1913. give s7 both the equality function and the mapping function. The latter takes any object
  1914. and returns the hash-table location for it (an integer). The problem here is that
  1915. for the arbitrary equality function to work, objects that are equal according to that
  1916. function have to be mapped to the same hash-table location. There's no way for s7 to intuit
  1917. what this mapping should be except in the built-in cases. So to specify some arbitrary function, the third
  1918. argument is a cons: '(equality-checker mapper).
  1919. </p>
  1920. <p>Here's a brief example. In CLM, we have c-objects of type mus-generator (from s7's point of view),
  1921. and we want to hash them using equal? (which will call the generator-specific equality function).
  1922. But s7 doesn't realize that the mus-generator type covers 40 or 50 internal types, so as the mapper we pass mus-type:
  1923. <code>(make-hash-table 64 (cons equal? mus-type))</code>.
  1924. </p>
  1925. </div>
  1926. <div class="indented">
  1927. <p>If the hash key is a float (a non-rational number), hash-table-ref uses <a href="#morallyequalp">morally-equal?</a>.
  1928. Otherwise, for example, you could use NaN as a key, but then never be able to access it!
  1929. </p>
  1930. </div>
  1931. <div class="indented">
  1932. <pre>
  1933. (define-macro (define-memoized name&amp;arg . body)
  1934. (let ((arg (cadr name&amp;arg))
  1935. (memo (gensym "memo")))
  1936. `(define ,(car name&amp;arg)
  1937. (let ((,memo (<em class=red>make-hash-table</em>)))
  1938. (lambda (,arg)
  1939. (or (,memo ,arg) ; check for saved value
  1940. (set! (,memo ,arg) (begin ,@body)))))))) ; set! returns the new value
  1941. &gt; (define (fib n)
  1942. (if (&lt; n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
  1943. <em class="gray">fib</em>
  1944. &gt; (define-memoized
  1945. (memo-fib n)
  1946. (if (&lt; n 2) n (+ (memo-fib (- n 1)) (memo-fib (- n 2)))))
  1947. <em class="gray">memo-fib</em>
  1948. &gt; (time (fib 34)) ; un-memoized time
  1949. <em class="gray">1.168</em> ; 0.70 on ccrma's i7-3930 machines
  1950. &gt; (time (memo-fib 34)) ; memoized time
  1951. <em class="gray">3.200e-05</em>
  1952. &gt; (outlet (funclet memo-fib))
  1953. <em class="gray">(inlet '{memo}-18 (hash-table
  1954. '(0 . 0) '(1 . 1) '(2 . 1) '(3 . 2) '(4 . 3) '(5 . 5)
  1955. '(6 . 8) '(7 . 13) '(8 . 21) '(9 . 34) '(10 . 55) '(11 . 89)
  1956. '(12 . 144) '(13 . 233) '(14 . 377) '(15 . 610) '(16 . 987)
  1957. '(17 . 1597) '(18 . 2584) '(19 . 4181) '(20 . 6765) '(21 . 10946)
  1958. '(22 . 17711) '(23 . 28657) '(24 . 46368) '(25 . 75025) '(26 . 121393)
  1959. '(27 . 196418) '(28 . 317811) '(29 . 514229) '(30 . 832040) '(31 . 1346269)
  1960. '(32 . 2178309) '(33 . 3524578) '(34 . 5702887)))</em>
  1961. </pre>
  1962. </div>
  1963. </blockquote>
  1964. <div class="header" id="environments"><h4>environments</h4></div>
  1965. <p>An environment holds symbols and their values. The global environment, for example,
  1966. holds all the variables that are defined at the top level.
  1967. Environments are first class (and applicable) objects in s7.
  1968. </p>
  1969. <pre class="indented">
  1970. (<em class=def id="rootlet">rootlet</em>) the top-level (global) environment
  1971. (<em class=def id="curlet">curlet</em>) the current (innermost) environment
  1972. (<em class=def id="funclet">funclet</em> proc) the environment at the time when proc was defined
  1973. (owlet) the environment at the point of the last error
  1974. (<em class=def id="unlet">unlet</em>) the current environment, but all built-in functions have their original values
  1975. (<em class=def id="letref">let-ref</em> env sym) get value of sym in env, same as (env sym)
  1976. (<em class=def id="letset">let-set!</em> env sym val)
  1977. (<em class=def id="inlet">inlet</em> . bindings) make a new environment with the given bindings
  1978. (<em class=def id="sublet">sublet</em> env . bindings) same as inlet, but the new environment is local to env
  1979. (<em class=def id="varlet">varlet</em> env . bindings) add new bindings directly to env
  1980. (<em class=def id="cutlet">cutlet</em> env . fields) remove bindings from env
  1981. (<em class=def id="letp">let?</em> obj) #t if obj is an environment
  1982. (<em class=def id="with-let">with-let</em> env . body) evaluate body in the environment env
  1983. (<em class=def id="outlet">outlet</em> env) the environment that encloses the environment env (settable)
  1984. (<em class=def id="lettolist">let-&gt;list</em> env) return the environment bindings as a list of (symbol . value) cons's
  1985. (<em class=def id="openlet">openlet</em> env) mark env as open (see below)
  1986. (<em class=def id="openletp">openlet?</em> env) #t is env is open
  1987. (<em class=def id="coverlet">coverlet</em> env) mark env as closed (undo an earlier openlet)
  1988. (<em class=def id="objecttolet">object-&gt;let</em> obj) return an environment containing information about obj
  1989. (<em class=def id="lettemporarily">let-temporarily</em> vars . body)
  1990. </pre>
  1991. <br>
  1992. <blockquote>
  1993. <pre class="indented">
  1994. &gt; (inlet 'a 1 'b 2)
  1995. <em class="gray">(inlet 'a 1 'b 2)</em>
  1996. &gt; (let ((a 1) (b 2)) (curlet))
  1997. <em class="gray">(inlet 'a 1 'b 2)</em>
  1998. &gt; (let ((x (inlet :a 1 :b 2))) (x 'a))
  1999. <em class="gray">1</em>
  2000. &gt; (with-let (inlet 'a 1 'b 2) (+ a b))
  2001. <em class="gray">3</em>
  2002. &gt; (let ((x (inlet :a 1 :b 2))) (set! (x 'a) 4) x)
  2003. <em class="gray">(inlet 'a 4 'b 2)</em>
  2004. &gt; (let ((x (inlet))) (varlet x 'a 1) x)
  2005. <em class="gray">(inlet 'a 1)</em>
  2006. &gt; (let ((a 1)) (let ((b 2)) (outlet (curlet))))
  2007. <em class="gray">(inlet 'a 1)</em>
  2008. &gt; (let ((e (inlet 'a (inlet 'b 1 'c 2)))) (e 'a 'b)) ; in C terms, e-&gt;a-&gt;b
  2009. <em class="gray">1</em>
  2010. &gt; (let ((e (inlet 'a (inlet 'b 1 'c 2)))) (set! (e 'a 'b) 3) (e 'a 'b))
  2011. <em class="gray">3</em>
  2012. </pre>
  2013. </blockquote>
  2014. <p>As the names suggest, in s7 an environment is viewed as a disembodied let. Environments are equal if they
  2015. contain the same symbols with the same values leaving aside shadowing, and taking into account the environment
  2016. chain up to the rootlet. That is, two environments are equal if any local variable of either has the same value in both.
  2017. </p>
  2018. <p><b>with-let</b> evaluates its body in the given environment, so
  2019. <code>(with-let e . body)</code> is equivalent to
  2020. <code>(eval `(begin ,@body) e)</code>, but probably faster.
  2021. Similarly, <code>(let bindings . body)</code> is equivalent to
  2022. <code>(eval `(begin ,@body) (apply inlet (flatten bindings)))</code>,
  2023. ignoring the outer (enclosing) environment (the default outer environment
  2024. of inlet is rootlet).
  2025. Or better,
  2026. </p>
  2027. <pre class="indented">
  2028. (define-macro (with-environs e . body)
  2029. `(apply let (map (lambda (a) (list (car a) (cdr a))) ,e) '(,@body)))
  2030. </pre>
  2031. <p>Or turning it around,</p>
  2032. <pre>
  2033. (define-macro (Let vars . body)
  2034. `(with-let (sublet (curlet)
  2035. ,@(map (lambda (var)
  2036. (values (symbol-&gt;keyword (car var)) (cadr var)))
  2037. vars))
  2038. ,@body))
  2039. (Let ((c 4))
  2040. (Let ((a 2)
  2041. (b (+ c 2)))
  2042. (+ a b c)))
  2043. </pre>
  2044. <p><b>let-temporarily</b> (now built-into s7) is somewhat similar to fluid-let in other Schemes.
  2045. Its syntax looks like
  2046. let, but it first saves the current value, then sets the
  2047. variable to the new value (via set!), calls the body, and finally restores the
  2048. original value. It can handle anything settable:
  2049. </p>
  2050. <pre class="indented">
  2051. (let-temporarily (((*s7* 'print-length) 8)) (display x))
  2052. </pre>
  2053. <p>This sets s7's print-length variable to 8 while displaying x, then
  2054. puts it back to its original value.
  2055. </p>
  2056. <p>
  2057. <b>sublet</b> adds bindings (symbols with associated values) to an environment.
  2058. It does not change the environment passed to it, but
  2059. just prepends the new bindings, shadowing any old ones,
  2060. as if you had called "let".
  2061. To add the bindings directly to the environment,
  2062. use <b>varlet</b>. Both of these functions accept nil as the
  2063. 'env' argument as shorthand for <code>(rootlet)</code>.
  2064. Both also accept other environments as well as individual bindings,
  2065. adding all the argument's bindings to the new environment.
  2066. <b>inlet</b> is very similar, but normally omits the environment argument.
  2067. The arguments to sublet and inlet can be passed as
  2068. symbol/value pairs, as a cons, or using keywords as if in define*.
  2069. inlet can also be used to copy an environment without accidentally invoking
  2070. that environment's copy method.
  2071. </p>
  2072. <p>Here's an example: we want to define two functions that share a
  2073. local variable:
  2074. </p>
  2075. <pre class="indented">
  2076. (varlet (curlet) ; import f1 and f2 into the current environment
  2077. (let ((x 1)) ; x is our local variable
  2078. (define (f1 a) (+ a x))
  2079. (define (f2 b) (* b x))
  2080. (inlet 'f1 f1 'f2 f2))) ; export f1 and f2
  2081. </pre>
  2082. <p>One way to add reader and writer functions to an individual environment slot is:
  2083. </p>
  2084. <pre class="indented">
  2085. (define e (inlet
  2086. 'x (let ((local-x 3)) ; x's initial value
  2087. (dilambda
  2088. (lambda () local-x)
  2089. (lambda (val) (set! local-x (max 0 (min val 100))))))))
  2090. &gt; ((e 'x))
  2091. <em class="gray">3</em>
  2092. &gt; (set! ((e 'x)) 123)
  2093. <em class="gray">100</em>
  2094. </pre>
  2095. <blockquote>
  2096. <div class="indented">
  2097. <p>I originally used a bunch of foolishly pompous names for the environment functions.
  2098. Two are still available for backwards compatibility:
  2099. </p>
  2100. <pre class="indented">
  2101. rootlet global-environment
  2102. curlet current-environment
  2103. </pre>
  2104. </div>
  2105. </blockquote>
  2106. <p>It is possible in Scheme to redefine built-in functions such as car.
  2107. To ensure that some code sees the original built-in function definitions,
  2108. wrap it in <code>(with-let (unlet) ...)</code>:
  2109. </p>
  2110. <pre class="indented">
  2111. &gt; (let ((caar 123))
  2112. (+ caar (with-let (unlet)
  2113. (caar '((2) 3)))))
  2114. <em class="gray">125</em>
  2115. </pre>
  2116. <p>
  2117. with-let and unlet are constants, so you can
  2118. use them in any context without worrying about whether they've been redefined.
  2119. As mentioned in the macro section, #_&lt;name&gt; is a built-in reader macro
  2120. for <code>(with-let (unlet) &lt;name&gt;)</code>,
  2121. so for example, #_+ is the built-in + function, no matter what.
  2122. <code>(unlet)</code> cleans up the current environment whenever it's called,
  2123. so you can use it to revert the REPL. (The environment of built-in functions
  2124. that unlet accesses is not accessible from scheme code, so there's no way
  2125. that those values can be clobbered).
  2126. </p>
  2127. <blockquote>
  2128. <div class="indented">
  2129. <p>
  2130. I think these functions can implement the notions of libraries,
  2131. separate namespaces, or modules.
  2132. Here's one way: first the library writer just writes his library.
  2133. The normal user simply loads it. The abnormal user worries about everything,
  2134. so first he loads the library in a local let to make sure no bindings escape
  2135. to pollute his code, and then he
  2136. uses unlet to
  2137. make sure that none of his bindings pollute the library code:
  2138. </p>
  2139. <pre class="indented">
  2140. (let ()
  2141. (with-let (unlet)
  2142. (load "any-library.scm" (curlet))
  2143. ;; by default load puts stuff in the global environment
  2144. ...))
  2145. </pre>
  2146. <p>Now Abnormal User can do what he wants with the library entities.
  2147. Say he wants to use "lognor" under the name "bitwise-not-or", and
  2148. all the other functions are of no interest:
  2149. </p>
  2150. <pre class="indented">
  2151. (varlet (curlet)
  2152. 'bitwise-not-or (with-let (unlet)
  2153. (load "any-library.scm" (curlet))
  2154. lognor)) ; lognor is presumably defined in "any-library.scm"
  2155. </pre>
  2156. <p>Say he wants to make sure the library is cleanly loaded, but all
  2157. its top-level bindings are imported into the current environment:
  2158. </p>
  2159. <pre class="indented">
  2160. (varlet (curlet)
  2161. (with-let (unlet)
  2162. (let ()
  2163. (load "any-library.scm" (curlet))
  2164. (curlet)))) ; these are the bindings introduced by loading the library
  2165. </pre>
  2166. <p>To do the same thing, but prepend "library:" to each name:
  2167. </p>
  2168. <pre class="indented">
  2169. (apply varlet (curlet)
  2170. (with-let (unlet)
  2171. (let ()
  2172. (load "any-library.scm" (curlet))
  2173. (map (lambda (binding)
  2174. (cons (symbol "library:" (symbol-&gt;string (car binding)))
  2175. (cdr binding)))
  2176. (curlet)))))
  2177. </pre>
  2178. <p>That's all there is to it! Here is the same idea as a macro:
  2179. </p>
  2180. <pre>
  2181. (define-macro (let! init end . body)
  2182. ;; syntax mimics 'do: (let! (vars&amp;values) ((exported-names) result) body)
  2183. ;; (let! ((a 1)) ((hiho)) (define (hiho x) (+ a x)))
  2184. `(let ,init
  2185. ,@body
  2186. (varlet (outlet (curlet))
  2187. ,@(map (lambda (export)
  2188. `(cons ',export ,export))
  2189. (car end)))
  2190. ,@(cdr end)))
  2191. </pre>
  2192. <!--
  2193. (define-macro (safe-let! init end . body)
  2194. `(with-let (#_inlet (unlet)
  2195. ,@(#_map (#_lambda (b)
  2196. `(#_cons ',(#_car b) ,(#_cadr b)))
  2197. init))
  2198. ,@body
  2199. (#_varlet (#_outlet (#_curlet))
  2200. ,@(#_map (#_lambda (export)
  2201. `(#_cons ',export ,export))
  2202. (#_car end)))
  2203. ,@(#_cdr end)))
  2204. -->
  2205. </div>
  2206. <div class="indented">
  2207. <p>Well, almost, darn it. If the loaded library file sets (via set!) a global value
  2208. such as abs, we need to put it back to its original form:
  2209. </p>
  2210. <pre>
  2211. (define (safe-load file)
  2212. (let ((e (with-let (unlet) ; save the environment before loading
  2213. (let-&gt;list (curlet)))))
  2214. (<em class=red>load</em> file (curlet))
  2215. (let ((new-e (with-let (unlet) ; get the environment after loading
  2216. (let-&gt;list (curlet)))))
  2217. (for-each ; see if any built-in functions were stepped on
  2218. (lambda (sym)
  2219. (unless (assoc (car sym) e)
  2220. (format () "~S clobbered ~A~%" file (car sym))
  2221. (apply set! (car sym) (list (cdr sym)))))
  2222. new-e))))
  2223. ;; say libtest.scm has the line (set! abs odd?)
  2224. &gt; (safe-load "libtest.scm")
  2225. <em class="gray">"libtest.scm" clobbered abs</em>
  2226. &gt; (abs -2)
  2227. <em class="gray">2</em>
  2228. </pre>
  2229. </div>
  2230. </blockquote>
  2231. <p><b>openlet</b> marks its argument, either an environment, a closure, or a c-object
  2232. as open. I need better terminology here! An open object is one that the
  2233. built-in s7 functions handle specially. If they encounter one in their
  2234. argument list, they look in the object for their own name, and call that
  2235. function if it exists. A bare-bones example:
  2236. </p>
  2237. <pre class="indented">
  2238. &gt; (abs (openlet (inlet 'abs (lambda (x) 47))))
  2239. <em class="gray">47</em>
  2240. &gt; (define* (f1 (a 1)) (if (real? a) (abs a) ((a 'f1) a)))
  2241. <em class="gray">f1</em>
  2242. &gt; (f1 :a (openlet (inlet 'f1 (lambda (e) 47))))
  2243. <em class="gray">47</em>
  2244. </pre>
  2245. <p>In CLOS, we'd declare a class and a method, and call make-instance,
  2246. and then discover that it wouldn't work anyway.
  2247. Here we have, in effect, an anonymous instance of an anonymous class.
  2248. I think this is called a "prototype system"; javascript is apparently similar.
  2249. A slightly more complex example:
  2250. </p>
  2251. <pre class="indented">
  2252. (let* ((e1 (openlet
  2253. (inlet
  2254. 'x 3
  2255. '* (lambda args
  2256. (apply * (if (number? (car args))
  2257. (values (car args) ((cadr args) 'x) (cddr args))
  2258. (values ((car args) 'x) (cdr args))))))))
  2259. (e2 (copy e1)))
  2260. (set! (e2 'x) 4)
  2261. (* 2 e1 e2)) ; (* 2 3 4) =&gt; 24
  2262. </pre>
  2263. <p>Perhaps these names would be better: openlet -&gt; with-methods, coverlet -&gt; without-methods,
  2264. and openlet? -&gt; methods?.
  2265. </p>
  2266. <p><b>object-&gt;let</b> returns an environment (more of a dictionary really) that
  2267. contains details about its argument. It
  2268. is intended as a debugging aid, underlying a debugger's "inspect" for example.
  2269. </p>
  2270. <pre class="indented">
  2271. &gt; (let ((iter (make-iterator "1234")))
  2272. (iter)
  2273. (iter)
  2274. (object-&gt;let iter))
  2275. <em class="gray">(inlet 'value #&lt;iterator: string&gt; 'type iterator? 'at-end #f 'sequence "1234" 'length 4 'position 2)</em>
  2276. </pre>
  2277. <p>A c-object (in the sense of s7_new_type), can add its own info to this namespace via an object-&gt;let
  2278. method in its local environment. snd-marks.c has a simple example using a class-wide environment (g_mark_methods),
  2279. holding as the value of its 'object-&gt;let field the function s7_mark_to_let. The latter uses s7_varlet to
  2280. add information to the namespace created by <code>(object-&gt;let mark)</code>.
  2281. </p>
  2282. <br>
  2283. <blockquote>
  2284. <details>
  2285. <summary class="indented">define-class</summary>
  2286. <div class="indented">
  2287. <p>Here is yet another object system. Each class and each instance is an environment.
  2288. A class might be thought of as a template for instances, but
  2289. there's actually no difference between them. To make an instance of a class, copy it. To inherit from
  2290. another class, concatenate the environments. To access (get or set) a field or a method, use the implicit
  2291. indexing syntax with the field or method name. To evaluate a form in the context of an instance
  2292. (CL's with-slots), use with-let. To run through all the fields, use map or for-each.
  2293. </p>
  2294. <pre>
  2295. (define-macro* (define-class class-name inherited-classes (slots ()) (methods ()))
  2296. `(let ((outer-env (outlet (curlet)))
  2297. (new-methods ())
  2298. (new-slots ()))
  2299. (for-each
  2300. (lambda (class)
  2301. ;; each class is a set of nested environments, the innermost (first in the list)
  2302. ;; holds the local slots which are copied each time an instance is created,
  2303. ;; the next holds the class slots (global to all instances, not copied);
  2304. ;; these hold the class name and other such info. The remaining environments
  2305. ;; hold the methods, with the localmost method first. So in this loop, we
  2306. ;; are gathering the local slots and all the methods of the inherited
  2307. ;; classes, and will splice them together below as a new class.
  2308. (set! new-slots (append (let-&gt;list class) new-slots))
  2309. (do ((e (outlet (outlet class)) (outlet e)))
  2310. ((or (not (let? e))
  2311. (eq? e (rootlet))))
  2312. (set! new-methods (append (let-&gt;list e) new-methods))))
  2313. ,inherited-classes)
  2314. (let ((remove-duplicates
  2315. (lambda (lst) ; if multiple local slots with same name, take the localmost
  2316. (letrec ((rem-dup
  2317. (lambda (lst nlst)
  2318. (cond ((null? lst) nlst)
  2319. ((assq (caar lst) nlst) (rem-dup (cdr lst) nlst))
  2320. (else (rem-dup (cdr lst) (cons (car lst) nlst)))))))
  2321. (reverse (rem-dup lst ()))))))
  2322. (set! new-slots
  2323. (remove-duplicates
  2324. (append (map (lambda (slot)
  2325. (if (pair? slot)
  2326. (cons (car slot) (cadr slot))
  2327. (cons slot #f)))
  2328. ,slots) ; the incoming new slots, #f is the default value
  2329. new-slots)))) ; the inherited slots
  2330. (set! new-methods
  2331. (append (map (lambda (method)
  2332. (if (pair? method)
  2333. (cons (car method) (cadr method))
  2334. (cons method #f)))
  2335. ,methods) ; the incoming new methods
  2336. ;; add an object-&gt;string method for this class (this is already a generic function).
  2337. (list (cons 'object-&gt;string
  2338. (lambda* (obj (use-write #t))
  2339. (if (eq? use-write :readable) ; write readably
  2340. (format #f "(make-~A~{ :~A ~W~^~})"
  2341. ',class-name
  2342. (map (lambda (slot)
  2343. (values (car slot) (cdr slot)))
  2344. obj))
  2345. (format #f "#&lt;~A: ~{~A~^ ~}&gt;"
  2346. ',class-name
  2347. (map (lambda (slot)
  2348. (list (car slot) (cdr slot)))
  2349. obj))))))
  2350. (reverse! new-methods))) ; the inherited methods, shadowed automatically
  2351. (let ((new-class (openlet
  2352. (apply sublet ; the local slots
  2353. (sublet ; the global slots
  2354. (apply inlet ; the methods
  2355. (reverse new-methods))
  2356. 'class-name ',class-name ; class-name slot
  2357. 'inherited ,inherited-classes
  2358. 'inheritors ()) ; classes that inherit from this class
  2359. new-slots))))
  2360. (varlet outer-env
  2361. ',class-name new-class ; define the class as class-name in the calling environment
  2362. ;; define class-name? type check
  2363. (string-&gt;symbol (string-append (symbol-&gt;string ',class-name) "?"))
  2364. (lambda (obj)
  2365. (and (let? obj)
  2366. (eq? (obj 'class-name) ',class-name))))
  2367. (varlet outer-env
  2368. ;; define the make-instance function for this class.
  2369. ;; Each slot is a keyword argument to the make function.
  2370. (string-&gt;symbol (string-append "make-" (symbol-&gt;string ',class-name)))
  2371. (apply lambda* (map (lambda (slot)
  2372. (if (pair? slot)
  2373. (list (car slot) (cdr slot))
  2374. (list slot #f)))
  2375. new-slots)
  2376. `((let ((new-obj (copy ,,class-name)))
  2377. ,@(map (lambda (slot)
  2378. `(set! (new-obj ',(car slot)) ,(car slot)))
  2379. new-slots)
  2380. new-obj))))
  2381. ;; save inheritance info for this class for subsequent define-method
  2382. (letrec ((add-inheritor (lambda (class)
  2383. (for-each add-inheritor (class 'inherited))
  2384. (if (not (memq new-class (class 'inheritors)))
  2385. (set! (class 'inheritors) (cons new-class (class 'inheritors)))))))
  2386. (for-each add-inheritor ,inherited-classes))
  2387. ',class-name)))
  2388. (define-macro (define-generic name) ; (define (genfun any) ((any 'genfun) any))
  2389. `(define ,name
  2390. (lambda args
  2391. (let ((gf ((car args) ',name))) ; get local definition
  2392. (if (not (eq? gf ,name)) ; avoid infinite recursion
  2393. (apply gf args)
  2394. (error "attempt to call generic function wrapper recursively"))))))
  2395. (define-macro (define-slot-accessor name slot)
  2396. `(define ,name (dilambda
  2397. (lambda (obj) (obj ',slot))
  2398. (lambda (obj val) (set! (obj ',slot) val)))))
  2399. (define-macro (define-method name-and-args . body)
  2400. `(let* ((outer-env (outlet (curlet)))
  2401. (method-name (car ',name-and-args))
  2402. (method-args (cdr ',name-and-args))
  2403. (object (caar method-args))
  2404. (class (symbol-&gt;value (cadar method-args)))
  2405. (old-method (class method-name))
  2406. (method (apply lambda* method-args ',body)))
  2407. ;; define the method as a normal-looking function
  2408. ;; s7test.scm has define-method-with-next-method that implements call-next-method here
  2409. ;; it also has make-instance
  2410. (varlet outer-env
  2411. method-name (apply lambda* method-args
  2412. `(((,object ',method-name)
  2413. ,@(map (lambda (arg)
  2414. (if (pair? arg) (car arg) arg))
  2415. method-args)))))
  2416. ;; add the method to the class
  2417. (varlet (outlet (outlet class)) method-name method)
  2418. ;; if there are inheritors, add it to them as well, but not if they have a shadowing version
  2419. (for-each
  2420. (lambda (inheritor)
  2421. (if (not (eq? (inheritor method-name) #&lt;undefined&gt;)) ; defined? goes to the global env
  2422. (if (eq? (inheritor method-name) old-method)
  2423. (set! (inheritor method-name) method))
  2424. (varlet (outlet (outlet inheritor)) method-name method)))
  2425. (class 'inheritors))
  2426. method-name))
  2427. (define (all-methods obj method)
  2428. ;; for arbitrary method combinations: this returns a list of all the methods of a given name
  2429. ;; in obj's class and the classes it inherits from (see example below)
  2430. (let* ((base-method (obj method))
  2431. (methods (if (procedure? base-method) (list base-method) ())))
  2432. (for-each
  2433. (lambda (ancestor)
  2434. (let ((next-method (ancestor method)))
  2435. (if (and (procedure? next-method)
  2436. (not (memq next-method methods)))
  2437. (set! methods (cons next-method methods)))))
  2438. (obj 'inherited))
  2439. (reverse methods)))
  2440. &gt; (define-class class-1 ()
  2441. '((a 1) (b 2))
  2442. (list (list 'add (lambda (obj)
  2443. (with-let obj
  2444. (+ a b))))))
  2445. <em class="gray">class-1</em>
  2446. &gt; (define v (make-class-1 :a 32))
  2447. <em class="gray">v </em>
  2448. &gt; (v 'a) ; to set the 'a slot, (set! (v 'a) 0)
  2449. <em class="gray">32</em>
  2450. &gt; (object-&gt;string v) ; built-in functions are all generic
  2451. <em class="gray">"#&lt;class-1: (a 32) (b 2)&gt;"</em> ; so this uses the method defined in the class definition
  2452. &gt; ((v 'add) v)
  2453. <em class="gray">34</em>
  2454. &gt; (define-generic add)
  2455. <em class="gray">add</em>
  2456. &gt; (add v) ; syntactic sugar for ((v 'add) v)
  2457. <em class="gray">34</em>
  2458. &gt; (define-slot-accessor slot-a a) ; more sugar!
  2459. <em class="gray">slot-a</em>
  2460. &gt; (slot-a v) ; same as (v 'a), set via (set! (slot-a v) 123)
  2461. <em class="gray">32</em>
  2462. &gt; (map car v) ; map and for-each work with environments
  2463. <em class="gray">(a b)</em> ; map cdr would return '(32 2) in this case
  2464. &gt; (define-class class-2 (list class-1)
  2465. '((c 3))
  2466. (list (list 'multiply (lambda (obj)
  2467. (with-let obj
  2468. (* a b c))))))
  2469. <em class="gray">class-2</em>
  2470. &gt; (define v2 (make-class-2 :a 32))
  2471. <em class="gray">v2</em>
  2472. &gt; v2 ; will use object-&gt;string
  2473. <em class="gray">"#&lt;class-2: (c 3) (a 32) (b 2)&gt;"</em>
  2474. &gt; ((v2 'multiply) v2)
  2475. <em class="gray">192</em>
  2476. &gt; (add v2) ; inherited from class-1
  2477. <em class="gray">34</em>
  2478. &gt; (define-method (subtract (obj class-1)) (with-let obj (- a b)))
  2479. <em class="gray">subtract</em>
  2480. &gt; (subtract v2) ; class-2 inherits from class-1 so it knows about subtract
  2481. <em class="gray">30</em>
  2482. &gt; (define v1 (make-class-1))
  2483. <em class="gray">v1</em>
  2484. &gt; (varlet v1 ; change the add method just in this instance
  2485. 'add (lambda (obj)
  2486. (with-let obj
  2487. (+ 1 a (* 2 b)))))
  2488. <em class="gray">#&lt;class-1: (a 1) (b 2) (add #&lt;lambda (obj)&gt;)&gt;</em>
  2489. &gt; (add v1)
  2490. <em class="gray">6</em>
  2491. &gt; (add v) ; other class-1 instances are not affected
  2492. <em class="gray">34</em>
  2493. &gt; (define-class class-3 (list class-2) ()
  2494. (list (list 'multiply (lambda (obj num)
  2495. (* num
  2496. ((class-2 'multiply) obj) ; method combination
  2497. (add obj))))))
  2498. <em class="gray">class-3</em>
  2499. &gt; ((class-3 'multiply) class-3 10)
  2500. <em class="gray">180 ; (* 10 (* 1 2 3) (+ 1 2))</em>
  2501. &gt; (define v3 (make-class-3))
  2502. <em class="gray">v3</em>
  2503. &gt; (all-methods v3 'multiply)
  2504. <em class="gray">(#&lt;lambda (obj num)&gt; #&lt;lambda (obj)&gt;)</em>
  2505. &gt; (for-each (lambda (p) (format () "~A~%" (procedure-source p))) (all-methods v3 'multiply))
  2506. <em class="gray">(lambda (obj num) (* num ((class-2 'multiply) obj) (add obj)))</em>
  2507. <em class="gray">(lambda (obj) (with-let obj (* a b c)))</em>
  2508. </pre>
  2509. <p>with-let (used briefly above) provides an even more striking simplification of syntax
  2510. than implicit indexing or multidimensional vectors, and it is faster as well!
  2511. See Snd's generators.scm for many examples.
  2512. </p>
  2513. <!--
  2514. at class definition time:
  2515. (list 'mac (symbol->value (define-macro (mac a) `(+ ,a 1))))
  2516. -->
  2517. </div>
  2518. </details>
  2519. <details>
  2520. <summary class="indented">more examples</summary>
  2521. <div class="indented">
  2522. <p>Implicit indexing of a local environment
  2523. does not search the global environment. Since unlet extends the
  2524. current environment chain, it is considered a local environment:
  2525. </p>
  2526. <pre class="indented">
  2527. &gt; ((rootlet) 'abs)
  2528. <em class="gray">abs</em>
  2529. &gt; (let () ((curlet) 'abs))
  2530. <em class="gray">#&lt;undefined&gt;</em>
  2531. &gt; ((unlet) 'abs)
  2532. <em class="gray">#&lt;undefined&gt;</em>
  2533. </pre>
  2534. </div>
  2535. <div class="indented">
  2536. <pre>
  2537. (define-macro (value-&gt;symbol expr)
  2538. `(let ((val ,expr)
  2539. (e1 (curlet)))
  2540. (call-with-exit
  2541. (lambda (return)
  2542. (do ((e e1 (outlet e))) ()
  2543. (for-each
  2544. (lambda (slot)
  2545. (if (equal? val (cdr slot))
  2546. (return (car slot))))
  2547. e)
  2548. (if (eq? e (rootlet))
  2549. (return #f)))))))
  2550. &gt; (let ((a 1) (b "hi"))
  2551. (value-&gt;symbol "hi"))
  2552. <em class="gray">b</em>
  2553. </pre>
  2554. </div>
  2555. <div class="indented">
  2556. <p>openlet alerts the rest of s7 that the environment has methods.
  2557. </p>
  2558. <pre>
  2559. (begin
  2560. (define fvector? #f)
  2561. (define make-fvector #f)
  2562. (let ((type (gensym))
  2563. (-&gt;float (lambda (x)
  2564. (if (real? x)
  2565. (* x 1.0)
  2566. (error 'wrong-type-arg "fvector new value is not a real: ~A" x)))))
  2567. (set! make-fvector
  2568. (lambda* (len (init 0.0))
  2569. (<em class=red>openlet</em>
  2570. (inlet :v (make-vector len (-&gt;float init))
  2571. :type type
  2572. :length (lambda (f) len)
  2573. :object-&gt;string (lambda (f . args) "#&lt;fvector&gt;")
  2574. :let-set! (lambda (fv i val) (#_vector-set! (fv 'v) i (-&gt;float val)))
  2575. :let-ref (lambda (fv i) (#_vector-ref (fv 'v) i))))))
  2576. (set! fvector? (lambda (p)
  2577. (and (let? p)
  2578. (eq? (p 'type) type))))))
  2579. &gt; (define fv (make-fvector 32))
  2580. <em class="gray">fv</em>
  2581. &gt; fv
  2582. <em class="gray">#&lt;fvector&gt;</em>
  2583. &gt; (length fv)
  2584. <em class="gray">32</em>
  2585. &gt; (set! (fv 0) 123)
  2586. <em class="gray">123.0</em>
  2587. &gt; (fv 0)
  2588. <em class="gray">123.0</em>
  2589. </pre>
  2590. </div>
  2591. <div class="indented">
  2592. <p>I can't resist adding at least some of a quaternion implementation
  2593. (finally "number?" is not the same
  2594. as "complex?"!):
  2595. </p>
  2596. <pre>
  2597. (define-class quaternion ()
  2598. '((r 0) (i 0) (j 0) (k 0))
  2599. (list (list 'number? (lambda (obj) #t))
  2600. (list 'complex? (lambda (obj) #f))
  2601. (list 'real? (lambda (obj) #f))
  2602. (list 'integer? (lambda (obj) #f))
  2603. (list 'rational? (lambda (obj) #f))
  2604. (list '+ (lambda orig-args
  2605. (let add ((r ()) (i ()) (j ()) (k ()) (args orig-args))
  2606. (if (null? args)
  2607. (<em class=red>make-quaternion</em>
  2608. (apply + r) (apply + i) (apply + j) (apply + k))
  2609. (let ((n (car args)))
  2610. (cond
  2611. ((real? n)
  2612. (add (cons n r) i j k (cdr args)))
  2613. ((complex? n)
  2614. (add (cons (real-part n) r) (cons (imag-part n) i) j k (cdr args)))
  2615. ((<em class=red>quaternion?</em> n)
  2616. (add (cons (n 'r) r) (cons (n 'i) i)
  2617. (cons (n 'j) j) (cons (n 'k) k)
  2618. (cdr args)))
  2619. ((not (<em class=red>openlet?</em> n)) ; maybe we'll add octonions later!
  2620. (error 'wrong-type-arg "+ argument ~A is not a number" n))
  2621. ((eq? n (car orig-args))
  2622. (error 'missing-method "+ can't handle these arguments: ~A" args))
  2623. (else
  2624. (apply (n '+)
  2625. (make-quaternion
  2626. (apply + r) (apply + i) (apply + j) (apply + k))
  2627. (cdr args)))))))))))
  2628. &gt; (let ((q1 (make-quaternion 1.0 1.0 0.0 0.0)))
  2629. (+ 1 q1 2.5+i))
  2630. <em class="gray">#&lt;quaternion: (r 4.5) (i 2.0) (j 0.0) (k 0.0)&gt;</em>
  2631. </pre>
  2632. </div>
  2633. </details>
  2634. <div class="indented">
  2635. <p>If an s7 function ignores the type of an argument, as in cons or vector for example,
  2636. then that argument won't be treated as having any methods.
  2637. </p>
  2638. <p>
  2639. Since outlet is settable, there are two ways an environment can
  2640. become circular. One is to include the current environment as the value of one of its variables.
  2641. The other is: <code>(let () (set! (outlet (curlet)) (curlet)))</code>.
  2642. </p>
  2643. <p>If you want to hide an environment's fields from any part of s7 that does not
  2644. know the field names in advance,
  2645. </p>
  2646. <pre class="indented">
  2647. (openlet ; make it appear to be empty to the rest of s7
  2648. (inlet 'object-&gt;string (lambda args "#&lt;let&gt;")
  2649. 'map (lambda args ())
  2650. 'for-each (lambda args #&lt;unspecified&gt;)
  2651. 'let-&gt;list (lambda args ())
  2652. 'length (lambda args 0)
  2653. 'copy (lambda args (inlet))
  2654. 'open #t
  2655. 'coverlet (lambda (e) (set! (e 'open) #f) e)
  2656. 'openlet (lambda (e) (set! (e 'open) #t) e)
  2657. 'openlet? (lambda (e) (e 'open))
  2658. ;; your secret data here
  2659. ))
  2660. </pre>
  2661. <p>(There are still at least two ways to tell that something is fishy).
  2662. </p>
  2663. <!-- add a field and it disappears, or sublet and read back -->
  2664. </div>
  2665. </blockquote>
  2666. <div class="header" id="multiplevalues"><h4>multiple-values</h4></div>
  2667. <p>
  2668. In s7, multiple values are spliced directly into the caller's argument list.
  2669. </p>
  2670. <pre class="indented">
  2671. &gt; (+ (values 1 2 3) 4)
  2672. <em class="gray">10</em>
  2673. &gt; (string-ref ((lambda () (values "abcd" 2))))
  2674. <em class="gray">#\c</em>
  2675. &gt; ((lambda (a b) (+ a b)) ((lambda () (values 1 2))))
  2676. <em class="gray">3</em>
  2677. &gt; (+ (call/cc (lambda (ret) (ret 1 2 3))) 4) ; call/cc has an implicit "values"
  2678. <em class="gray">10</em>
  2679. &gt; ((lambda* ((a 1) (b 2)) (list a b)) (values :a 3))
  2680. <em class="gray">(3 2)</em>
  2681. (define-macro (call-with-values producer consumer)
  2682. `(,consumer (,producer)))
  2683. (define-macro (multiple-value-bind vars expr . body)
  2684. `((lambda ,vars ,@body) ,expr))
  2685. (define-macro (define-values vars expression)
  2686. `(if (not (null? ',vars))
  2687. (varlet (curlet) ((lambda ,vars (curlet)) ,expression))))
  2688. (define (curry function . args)
  2689. (if (null? args)
  2690. function
  2691. (lambda more-args
  2692. (if (null? more-args)
  2693. (apply function args)
  2694. (function (apply values args) (apply values more-args))))))
  2695. </pre>
  2696. <blockquote>
  2697. <div class="indented">
  2698. <p>multiple-values are useful in a several situations. For example,
  2699. <code>(if test (+ a b c) (+ a b d e))</code> can be written
  2700. <code>(+ a b (if test c (values d e)))</code>.
  2701. There are a few special uses of multiple-values.
  2702. First, you can use the values function to return any number of values, including 0,
  2703. from map's function application:
  2704. </p>
  2705. <pre class="indented">
  2706. &gt; (map (lambda (x) (if (odd? x) (values x (* x 20)) (values))) (list 1 2 3))
  2707. <em class="gray">(1 20 3 60)</em>
  2708. &gt; (map values (list 1 2 3) (list 4 5 6))
  2709. <em class="gray">(1 4 2 5 3 6)</em>
  2710. (define (remove-if func lst)
  2711. (map (lambda (x) (if (func x) (values) x)) lst))
  2712. (define (pick-mappings func lst)
  2713. (map (lambda (x) (or (func x) (values))) lst))
  2714. (define (shuffle . args)
  2715. (apply map values args))
  2716. &gt; (shuffle '(1 2 3) #(4 5 6) '(7 8 9))
  2717. <em class="gray">(1 4 7 2 5 8 3 6 9)</em>
  2718. (define (concatenate . args)
  2719. (apply append (map (lambda (arg) (map values arg)) args)))
  2720. </pre>
  2721. <p>Second, a macro can return multiple values; these are evaluated and spliced,
  2722. exactly like a normal macro,
  2723. so you can use <code>(values '(define a 1) '(define b 2))</code> to
  2724. splice multiple definitions at the macro invocation point.
  2725. If an expansion returns (values), nothing is spliced in. This is
  2726. mostly useful in <a href="#readercond">reader-cond</a> and the #; reader.
  2727. </p>
  2728. <pre class="indented">
  2729. &gt; (define-expansion (comment str) (values))
  2730. <em class="gray">comment</em>
  2731. &gt; (+ 1 (comment "one") 2 (comment "two"))
  2732. <em class="gray">3</em>
  2733. </pre>
  2734. <p>At the top-level (in the REPL), since there's nothing to splice into, you simply get your values back:
  2735. </p>
  2736. <pre class="indented">
  2737. &gt; (values 1 (list 1 2) (+ 3 4 5))
  2738. <em class="gray">(values 1 (1 2) 12)</em>
  2739. </pre>
  2740. <p>But this printout is just trying to be informative. There is no multiple-values object
  2741. in s7. You can't <code>(set! x (values 1 2))</code>, for example. The values function
  2742. tells s7 that its arguments should be handled in a special way, and the multiple-value indication goes away
  2743. as soon as the arguments are spliced into some caller's arguments.
  2744. </p>
  2745. <p>Internally, s7 uses <code>(apply values ...)</code> to implement unquote splicing (",@") in quasiquote.
  2746. <!--
  2747. Is <code>(apply apply func arglist)</code> the same as <code>(apply func (apply values arglist))</code>,
  2748. or (leaving aside <code>'(()))</code>, <code>(func (apply values (apply values arglist)))</code>?
  2749. -->
  2750. </p>
  2751. </div>
  2752. <div class="indented">
  2753. <p>Since set! does not evaluate its first argument, and
  2754. there is no setter for "values", <code>(set! (values x) ...)</code> is not
  2755. the same as <code>(set! x ...)</code>. <code>(string-set! (values string) ...)</code>
  2756. works because string-set! does evaluate its first argument. <code>((values + 1 2) (values 3 4) 5)</code>
  2757. is 15, as anyone would expect.
  2758. </p>
  2759. </div>
  2760. <!--
  2761. <details>
  2762. <summary class="indented">more examples</summary>
  2763. <pre>
  2764. (define (flatten lst)
  2765. (map values (list (let flatten-1 ((lst lst))
  2766. (cond ((null? lst) (values))
  2767. ((not (pair? lst)) lst)
  2768. (else (values (flatten-1 (car lst))
  2769. (flatten-1 (cdr lst)))))))))
  2770. </pre>
  2771. <div class="indented">
  2772. </details>
  2773. -->
  2774. <details>
  2775. <summary class="indented">more on values</summary>
  2776. <div class="indented">
  2777. <p>In some Schemes, values behaves like CL's prog1:
  2778. </p>
  2779. <pre class="indented">
  2780. (not s7)&gt; (let ((x 1)) (cond ((values #f (set! x 2) #t) 3) (#t x)))
  2781. <em class="gray">2</em>
  2782. (not s7)&gt; (if (values #f #t) 1 2)
  2783. <em class="gray">2</em>
  2784. </pre>
  2785. <p>But in s7 we're trying to implement real multiple values (else why have them at all?).
  2786. There are many ways we could interpret <code>(cond ((values ...))...)</code> and
  2787. <code>(cond ((values...) =&gt; func))</code>, but surely
  2788. equivalent uses of "cond" and "if" should give the same result.
  2789. Currently in s7, where a test is in progress, only <code>(values #f)</code> is the same as #f.
  2790. </p>
  2791. <pre class="indented">
  2792. &gt; (if (values #f #f) 1 2) ; (values #f #f) is not #f
  2793. <em class="gray">1</em>
  2794. &gt; (cond ((values #f #f) 1) (#t 2))
  2795. <em class="gray">1</em>
  2796. ;;; but if we interpreted this as splicing in the values, we get an inconsistency:
  2797. &gt; (cond (#f #f 1) (#t 2))
  2798. <em class="gray">2</em>
  2799. &gt; (if (values #f) 1 2)
  2800. <em class="gray">2</em>
  2801. &gt; (cond ((values #f) 1) (#t 2))
  2802. <em class="gray">2</em>
  2803. &gt; (if (values) 1 2)
  2804. <em class="gray">1</em>
  2805. &gt; (cond ((values) 1) (#t 2))
  2806. <em class="gray">1</em>
  2807. ;;; this is consistent with (cond (1) (#t 2))
  2808. </pre>
  2809. <p>
  2810. So "if" and "cond" agree, but it requires that in one case the "values"
  2811. behavior is slightly weird. <code>(or (values #f #f))</code> is #f, but that isn't inconsistent because
  2812. "or" is not testing anything.
  2813. We might choose to say that <code>(if (values #f #f)...)</code>
  2814. is an error, but that would be hasty &mdash;
  2815. our troubles have only begun. First, "cond" can omit the expressions that follow the test, unlike "if":
  2816. </p>
  2817. <pre class="indented">
  2818. &gt; (cond (3))
  2819. <em class="gray">3</em>
  2820. </pre>
  2821. <p>and even trickier, "cond" can pass the test value to a function:
  2822. </p>
  2823. <pre class="indented">
  2824. &gt; (cond (3 =&gt; +))
  2825. <em class="gray">3</em>
  2826. </pre>
  2827. <p>The various standards agree that in the "=&gt;" case, the "fed to" function
  2828. receives one argument, so
  2829. </p>
  2830. <pre class="indented">
  2831. (not s7)&gt; (cond ((values 1 2) =&gt; +))
  2832. <em class="gray">1</em>
  2833. </pre>
  2834. <p>If we were following the "splice immediately" model, this would be <code>(cond (1 2 =&gt; +))</code>
  2835. which is an error in some Schemes.
  2836. So something has to give. My druthers is to make "values" work as consistently as possible, and hope
  2837. that the one odd corner will not trip anyone. From that point of view, the "one arg" standard
  2838. looks like a wasted opportunity.
  2839. s7 handles it this way:
  2840. </p>
  2841. <pre class="indented">
  2842. &gt; (+ 1 (cond ((values 2 3))) 4) ; trailing values are not ignored
  2843. <em class="gray">10</em>
  2844. &gt; (cond ((values 1 2 3) =&gt; +))
  2845. <em class="gray">6</em>
  2846. </pre>
  2847. <p>Of course, it is unproblematic that the expression can itself involve multiple values:
  2848. </p>
  2849. <pre class="indented">
  2850. &gt; (+ (cond (#t (values 1 2))))
  2851. <em class="gray">3</em>
  2852. </pre>
  2853. <p>Now, what have I missed?
  2854. </p>
  2855. </div>
  2856. </details>
  2857. </blockquote>
  2858. <!-- one place where multiple values might cause surprise:
  2859. :(define* (a1 (a2 (values 1 2))) a2)
  2860. :(a1)
  2861. (values 1 2)
  2862. :(define (a1 a2) a2)
  2863. :(a1 (values 1 2))
  2864. ;(values 1 2): too many arguments: (values 1 2)
  2865. -->
  2866. <div class="header" id="callwithexit1"><h4>call-with-exit, with-baffle and continuation?</h4></div>
  2867. <p><b><em class=def id="callwithexit">call-with-exit</em></b> is call/cc without the ability to jump back into the original context,
  2868. similar to "return" in C. This
  2869. is cleaner than call/cc, and much faster.
  2870. </p>
  2871. <pre class="indented">
  2872. (define-macro (block . body)
  2873. ;; borrowed loosely from CL &mdash; predefine "return" as an escape
  2874. `(<em class=red>call-with-exit</em> (lambda (return) ,@body)))
  2875. (define-macro (while test . body) ; while loop with predefined break and continue
  2876. `(<em class=red>call-with-exit</em>
  2877. (lambda (break)
  2878. (let continue ()
  2879. (if (let () ,test)
  2880. (begin
  2881. (let () ,@body)
  2882. (continue))
  2883. (break))))))
  2884. (define-macro (switch selector . clauses) ; C-style case (branches fall through unless break called)
  2885. `(<em class=red>call-with-exit</em>
  2886. (lambda (break)
  2887. (case ,selector
  2888. ,@(do ((clause clauses (cdr clause))
  2889. (new-clauses ()))
  2890. ((null? clause) (reverse new-clauses))
  2891. (set! new-clauses (cons `(,(caar clause)
  2892. ,@(cdar clause)
  2893. ,@(map (lambda (nc)
  2894. (apply values (cdr nc))) ; doubly spliced!
  2895. (if (pair? clause) (cdr clause) ())))
  2896. new-clauses)))))))
  2897. (define (and-for-each func . args)
  2898. ;; apply func to the first member of each arg, stopping if it returns #f
  2899. (<em class=red>call-with-exit</em>
  2900. (lambda (quit)
  2901. (apply for-each (lambda arglist
  2902. (if (not (apply func arglist))
  2903. (quit #&lt;unspecified&gt;)))
  2904. args))))
  2905. (define (find-if f . args) ; generic position-if is very similar
  2906. (<em class=red>call-with-exit</em>
  2907. (lambda (return)
  2908. (apply for-each (lambda main-args
  2909. (if (apply f main-args)
  2910. (apply return main-args)))
  2911. args))))
  2912. &gt; (find-if even? #(1 3 5 2))
  2913. <em class="gray">2</em>
  2914. &gt; (* (find-if > #(1 3 5 2) '(2 2 2 3)))
  2915. <em class="gray">6</em>
  2916. </pre>
  2917. <p>
  2918. The call-with-exit function's argument (the "continuation") is only valid
  2919. within the call-with-exit function. In call/cc, you can save it, then call it later
  2920. to jump back, but if you try that with call-with-exit (from outside the call-with-exit function's body), you'll get an error.
  2921. This is similar to trying to read from a closed input port.
  2922. </p>
  2923. <p>The other side, so to speak, of call-with-exit, is <em class=def id="withbaffle">with-baffle</em>.
  2924. Both limit the scope of a continuation.
  2925. Sometimes we need a normal call/cc, but want to make sure it is active
  2926. only within a given block of code.
  2927. Normally, if a continuation gets away, there's no telling when it might wreak havoc on us.
  2928. Scheme code with call/cc becomes unpredictable, undebuggable, and completely
  2929. unmaintainable.
  2930. with-baffle blocks all that &mdash; no continuation can jump into its body:
  2931. </p>
  2932. <pre class="indented">
  2933. (let ((what's-for-breakfast ())
  2934. (bad-dog 'fido)) ; bad-dog wonders what's for breakfast?
  2935. (<em class=red>with-baffle</em> ; the syntax is (with-baffle . body)
  2936. (set! what's-for-breakfast
  2937. (call/cc
  2938. (lambda (biscuit?)
  2939. (set! bad-dog biscuit?) ; bad-dog smells a biscuit!
  2940. 'biscuit!))))
  2941. (if (eq? what's-for-breakfast 'biscuit!)
  2942. (bad-dog 'biscuit!)) ; now, outside the baffled block, bad-dog wants that biscuit!
  2943. what's-for-breakfast) ; but s7 says "No!": baffled! ("continuation can't jump into with-baffle")
  2944. </pre>
  2945. <br>
  2946. <p><em class=def id="continuationp">continuation?</em> returns #t if its argument is a continuation,
  2947. as opposed to a normal procedure. I don't know why Scheme hasn't had this function from
  2948. the very beginning, but it's needed if you want to write a continuable error
  2949. handler. Here is a sketch of the situation:
  2950. </p>
  2951. <pre class="indented">
  2952. (let ()
  2953. (catch #t
  2954. (lambda ()
  2955. (let ((res (call/cc
  2956. (lambda (ok)
  2957. (error 'cerror "an error" ok)))))
  2958. (display res) (newline)))
  2959. (lambda args
  2960. (if (and (eq? (car args) 'cerror)
  2961. (<em class=red>continuation?</em> (cadadr args)))
  2962. (begin
  2963. (display "continuing...")
  2964. ((cadadr args) 2)))
  2965. (display "oops"))))
  2966. continuing...2
  2967. </pre>
  2968. <p>In a more general case, the error handler is separate from the
  2969. catch body, and needs a way to distinguish a real continuation
  2970. from a simple procedure.
  2971. </p>
  2972. <pre class="indented">
  2973. (define (continuable-error . args)
  2974. (call/cc
  2975. (lambda (continue)
  2976. (apply error args))))
  2977. (define (continue-from-error)
  2978. (if (<em class=red>continuation?</em> ((owlet) 'continue)) ; might be #&lt;undefined&gt; or a function as in the while macro
  2979. (((owlet) 'continue))
  2980. 'bummer))
  2981. </pre>
  2982. <!--
  2983. (define-macro (call-with-exit func)
  2984. (let ((tag (caadr func)))
  2985. `(catch ',tag
  2986. (lambda ()
  2987. (define-macro (,tag . body)
  2988. `(throw ',',tag ,@body))
  2989. ,@(cddr func))
  2990. (lambda (type info)
  2991. (car info)))))
  2992. -->
  2993. <div class="header" id="format1"><h4>format, object-&gt;string</h4></div>
  2994. <p>object-&gt;string returns the string representation of its argument. Its optional second argument
  2995. can be #f (use display), #t (the default, use write), or :readable. In the latter case, object-&gt;string
  2996. tries to produce a string that can be evaluated via eval-string to return an object equal to the
  2997. original.
  2998. </p>
  2999. <pre class="indented">
  3000. &gt; (object-&gt;string "hiho")
  3001. <em class="gray">"\"hiho\""</em>
  3002. &gt; (format #f "~S" "hiho")
  3003. <em class="gray">"\"hiho\""</em>
  3004. </pre>
  3005. <br>
  3006. <p>s7's <em class=def id="format">format</em> function is very close to that in srfi-48.
  3007. </p>
  3008. <pre class="indented">
  3009. &gt; (format #f "~A ~D ~F" 'hi 123 3.14)
  3010. <em class="gray">"hi 123 3.140000"</em>
  3011. </pre>
  3012. <p>The format directives (tilde chars) are:</p>
  3013. <pre class="indented">
  3014. ~% insert newline
  3015. ~&amp; insert newline if preceding char was not newline
  3016. ~~ insert tilde
  3017. ~\n (tilde followed by newline): trim white space
  3018. ~{ begin iteration (take arguments from a list, string, vector, or any other applicable object)
  3019. ~} end iteration
  3020. ~^ ~| jump out of iteration
  3021. ~* ignore the current argument
  3022. ~C print character (numeric argument = how many times to print it)
  3023. ~P insert 's' if current argument is not 1 or 1.0 (use ~@P for "ies" or "y")
  3024. ~A object-&gt;string as in display
  3025. ~S object-&gt;string as in write
  3026. ~B number-&gt;string in base 2
  3027. ~O number-&gt;string in base 8
  3028. ~D number-&gt;string in base 10
  3029. ~X number-&gt;string in base 16
  3030. ~E float to string, (format #f "~E" 100.1) -&gt; "1.001000e+02", (%e in C)
  3031. ~F float to string, (format #f "~F" 100.1) -&gt; "100.100000", (%f in C)
  3032. ~G float to string, (format #f "~G" 100.1) -&gt; "100.1", (%g in C)
  3033. ~T insert spaces (padding)
  3034. ~N get numeric argument from argument list (similar to ~V in CL)
  3035. ~W object-&gt;string with :readable (write readably; s7 is the intended reader)
  3036. </pre>
  3037. <p>The eight directives before ~W take the usual numeric arguments to specify field width and precision.
  3038. These can also be ~N or ~n in which case the numeric argument is read from the list of arguments:
  3039. </p>
  3040. <pre class="indented">
  3041. (format #f "~ND" 20 1234) ; =&gt; (format "~20D" 1234)
  3042. <em class="gray">" 1234"</em>
  3043. </pre>
  3044. <p>
  3045. <code>(format #f ...)</code> simply returns the formatted string; <code>(format #t ...)</code>
  3046. also sends the string to the current-output-port. <code>(format () ...)</code> sends the output to
  3047. the current-output-port without returning the string (this mimics the other IO routines
  3048. such as display and newline). Other built-in port choices are *stdout* and *stderr*.
  3049. </p>
  3050. <blockquote>
  3051. <div class="indented">
  3052. <p>Floats can occur in any base, so:
  3053. </p>
  3054. <pre class="indented">
  3055. &gt; #xf.c
  3056. <em class="gray">15.75</em>
  3057. </pre>
  3058. <p>This also affects format. In most Schemes, <code>(format #f "~X" 1.25)</code> is
  3059. an error. In CL, it is equivalent to using ~A which is perverse. But
  3060. </p>
  3061. <pre class="indented">
  3062. &gt; (number-&gt;string 1.25 16)
  3063. <em class="gray">"1.4"</em>
  3064. </pre>
  3065. <p>and there's no obvious way to get the same effect from format unless we accept
  3066. floats in the "~X" case. So in s7,
  3067. </p>
  3068. <pre class="indented">
  3069. &gt; (format #f "~X" 21)
  3070. <em class="gray">"15"</em>
  3071. &gt; (format #f "~X" 1.25)
  3072. <em class="gray">"1.4"</em>
  3073. &gt; (format #f "~X" 1.25+i)
  3074. <em class="gray">"1.4+1.0i"</em>
  3075. &gt; (format #f "~X" 21/4)
  3076. <em class="gray">"15/4"</em>
  3077. </pre>
  3078. <p>That is, the output choice matches the argument. A case that came up in the Guile mailing lists is:
  3079. <code>(format #f "~F" 1/3)</code>. s7 currently returns "1/3", but Clisp returns "0.33333334".
  3080. </p>
  3081. <br>
  3082. <p>The curly bracket directive applies to anything you can map over, not just lists:
  3083. </p>
  3084. <pre class="indented">
  3085. &gt; (format #f "~{~C~^ ~}" "hiho")
  3086. <em class="gray">"h i h o"</em>
  3087. &gt; (format #f "~{~{~C~^ ~}~^...~}" (list "hiho" "test"))
  3088. <em class="gray">"h i h o...t e s t"</em>
  3089. &gt; (with-input-from-string (format #f "(~{~C~^ ~})" (format #f "~B" 1367)) read) ; integer-&gt;list
  3090. <em class="gray">(1 0 1 0 1 0 1 0 1 1 1)</em>
  3091. </pre>
  3092. <br>
  3093. <p>Since any sequence can be passed to ~{~}, we need a way to truncate output and represent
  3094. the rest of the sequence with "...", but ~^ only stops at the end of the sequence. ~|
  3095. is like ~^ but it also stops after it handles (*s7* 'print-length) elements and prints
  3096. "...". So, <code>(format #f "~{~A~| ~}" #(0 1 2 3 4))</code> returns "0 1 2 ..."
  3097. if (*s7* 'print-length) is 3.
  3098. </p>
  3099. </div>
  3100. </blockquote>
  3101. <blockquote>
  3102. <div class="indented">
  3103. <p>I added object-&gt;string to s7 before deciding to include format. format excites a
  3104. vague disquiet &mdash; why do we need this ancient unlispy thing?
  3105. We can almost replace it with:
  3106. </p>
  3107. <pre class="indented">
  3108. (define (objects-&gt;string . objects)
  3109. (apply string-append (map (lambda (obj) (object-&gt;string obj #f)) objects)))
  3110. </pre>
  3111. <p>But how to handle lists (~{...~} in format), or columnized output (~T)?
  3112. I wonder whether formatted string output still matters outside a REPL. Even in that context,
  3113. a modern GUI leaves formatting decisions to a text or table widget.
  3114. </p>
  3115. <pre class="indented">
  3116. (define-macro (string-&gt;objects str . objs)
  3117. `(with-input-from-string ,str
  3118. (lambda ()
  3119. ,@(map (lambda (obj)
  3120. `(set! ,obj (eval (read))))
  3121. objs))))
  3122. </pre>
  3123. <!--
  3124. :(objects->string "int: " 32 ", string: " "hi")
  3125. "int: 32, string: hi"
  3126. (define (cycle->string . objs)
  3127. (call-with-exit
  3128. (lambda (return)
  3129. (for-each
  3130. (lambda (obj)
  3131. (if (pair? obj)
  3132. (return
  3133. (string-append
  3134. (apply objects->string
  3135. (map (lambda (obj)
  3136. (if (pair? obj)
  3137. (car obj)
  3138. obj))
  3139. objs))
  3140. (apply cycle->string
  3141. (map (lambda (obj)
  3142. (if (pair? obj)
  3143. (cdr obj)
  3144. obj))
  3145. objs))))))
  3146. objs)
  3147. "")))
  3148. ;;; (cycle->string ": " (list 1 2 3) " |")
  3149. :(objects->string "int: " 32 ", list with spaces: (" (cycle->string (list 1 2 3) " ") "), string: " "hi")
  3150. "int: 32, list with spaces: (1 2 3 ), string: hi"
  3151. :(let ((x 0) (y 0)) (string->objects "1 2" x y) (list x y))
  3152. (1 2)
  3153. -->
  3154. </div>
  3155. </blockquote>
  3156. <div class="header" id="hooks"><h4>hooks</h4></div>
  3157. <pre class="indented">
  3158. (<em class=def id="makehook">make-hook</em> . fields) ; make a new hook
  3159. (<em class=def id="hookfunctions">hook-functions</em> hook) ; the hook's list of 'body' functions
  3160. </pre>
  3161. <p>A hook is a function created by make-hook, and called (normally from C) when something interesting happens.
  3162. In GUI toolkits hooks are called callback-lists, in CL conditions,
  3163. in other contexts watchpoints or signals. s7 itself has several
  3164. hooks: <a href="#errorhook">*error-hook*</a>, <a href="#readerrorhook">*read-error-hook*</a>,
  3165. <a href="#unboundvariablehook">*unbound-variable-hook*</a>, *missing-close-paren-hook*,
  3166. and <a href="#loadhook">*load-hook*</a>.
  3167. make-hook is:
  3168. </p>
  3169. <pre class="indented">
  3170. (define (make-hook . args)
  3171. (let ((body ()))
  3172. (apply lambda* args
  3173. '(let ((result #&lt;unspecified&gt;))
  3174. (let ((e (curlet)))
  3175. (for-each (lambda (f) (f e)) body)
  3176. result))
  3177. ())))
  3178. </pre>
  3179. <p>So the result of calling make-hook is a function (the lambda* that is applied to args above) that
  3180. contains a list of functions, 'body.
  3181. Each function in that list takes one argument, the hook.
  3182. Each time the hook itself is called, each of the body functions is called, and the value of 'result is returned.
  3183. That variable, and each of the hook's arguments are accessible to the hook's internal
  3184. functions by going through the environment passed to the internal functions. This is a bit circuitous;
  3185. here's a sketch:
  3186. </p>
  3187. <pre class="indented">
  3188. &gt; (define h (make-hook '(a 32) 'b)) ; h is a function: (lambda* ((a 32) b) ...)
  3189. <em class="gray">h</em>
  3190. &gt; (set! (hook-functions h) ; this sets ((funclet h) 'body)
  3191. (list (lambda (hook) ; each hook internal function takes one argument, the environment
  3192. (set! (hook 'result) ; this is the "result" variable above
  3193. (format #f "a: ~S, b: ~S" (hook 'a) (hook 'b))))))
  3194. <em class="gray">(#&lt;lambda (hook)&gt;)</em>
  3195. &gt; (h 1 2) ; this calls the hook's internal functions (just one in this case)
  3196. <em class="gray">"a: 1, b: 2" ; we set "result" to this string, so it is returned as the hook application result</em>
  3197. &gt; (h)
  3198. <em class="gray">"a: 32, b: #f"</em>
  3199. </pre>
  3200. <p>In C, to make a hook:
  3201. </p>
  3202. <pre class="indented">
  3203. hook = s7_eval_c_string("(make-hook '(a 32) 'b)");
  3204. s7_gc_protect(s7, hook);
  3205. </pre>
  3206. <p>And call it:
  3207. </p>
  3208. <pre class="indented">
  3209. result = s7_call(s7, hook, s7_list(s7, 2, s7_make_integer(s7, 1), s7_make_integer(s7, 2)));
  3210. </pre>
  3211. <div class="indented">
  3212. <pre>
  3213. (define-macro (hook . body) ; return a new hook with "body" as its body, setting "result"
  3214. `(let ((h (make-hook)))
  3215. (set! (hook-functions h) (list (lambda (h) (set! (h 'result) (begin ,@body)))))
  3216. h))
  3217. </pre>
  3218. </div>
  3219. <div class="header" id="procedureinfo"><h4>procedure info</h4></div>
  3220. <pre class="indented">
  3221. (<em class=def id="proceduresource">procedure-source</em> proc)
  3222. (<em class=def id="proceduredocumentation">procedure-documentation</em> proc)
  3223. (<em class=def id="proceduresignature">procedure-signature</em> proc)
  3224. (<em class=def id="proceduresetter">procedure-setter</em> proc)
  3225. (funclet proc)
  3226. (<em class=def id="arity">arity</em> obj)
  3227. (<em class=def id="aritablep">aritable?</em> obj num-args)
  3228. </pre>
  3229. <p>
  3230. procedure-setter returns or sets the set function associated with a procedure (set-car! with car, for example).
  3231. funclet returns
  3232. a procedure's environment.
  3233. procedure-source returns the procedure source (a list).
  3234. </p>
  3235. <pre class="indented">
  3236. (define (procedure-arglist f) (cadr (procedure-source f)))
  3237. </pre>
  3238. <p>
  3239. procedure-documentation returns the documentation string associated with a procedure. This used to be
  3240. the initial string in the function's body (as in CL), but now it is the value of the 'documentation variable, if any,
  3241. in the procedure's local environment. That is, <code>(define (f a) "doc string" a)</code> is now
  3242. <code>(define f (let ((documentation "doc string")) (lambda (a) a)))</code>. This change gets the
  3243. string out of the body (where it can slow down evaluation of the function to no purpose), and
  3244. makes it possible to extend the function information arbitrarily.
  3245. </p>
  3246. <p>
  3247. arity takes any object and returns either #f if it is not applicable,
  3248. or a cons containing the minimum and maximum number of arguments acceptable. If the maximum reported
  3249. is a really big number, that means any number of arguments is ok.
  3250. aritable? takes two arguments, an object and an integer, and returns #t if the object can be
  3251. applied to that many arguments.
  3252. </p>
  3253. <pre class="indented">
  3254. &gt; (define add-2 (let ((documentation "add-2 adds its 2 args")) (lambda* (a (b 32)) (+ a b))))
  3255. <em class="gray">add-2</em>
  3256. &gt; (procedure-documentation add-2)
  3257. <em class="gray">"add-2 adds its 2 args"</em>
  3258. &gt; (procedure-source add-2)
  3259. <em class="gray">(lambda* (a (b 32)) (+ a b))</em>
  3260. &gt; (arity add-2)
  3261. <em class="gray">(0 . 2)</em>
  3262. </pre>
  3263. <p>
  3264. procedure-signature is a list describing the argument types and returned value type
  3265. of the function. The first entry in the list is the return type, and the rest are
  3266. argument types. #t means any type is possible, and 'values means the function returns multiple values.
  3267. </p>
  3268. <pre class="indented">
  3269. &gt; (procedure-signature round)
  3270. <em class="gray">(integer? real?)</em> ; round takes a real argument, returns an integer
  3271. &gt; (procedure-signature vector-ref)
  3272. <em class="gray">(#t vector? . #1=(integer? . #1#))</em> ; trailing args are all integers (indices)
  3273. </pre>
  3274. <p>If an entry is a list, any of the listed types can occur:
  3275. </p>
  3276. <pre class="indented">
  3277. &gt; (procedure-signature char-position)
  3278. <em class="gray">((boolean? integer?) (char? string?) string? integer?)</em>
  3279. </pre>
  3280. <p>which says that the first argument to char-position can be a string or a character,
  3281. and the return type can be either boolean or an integer.
  3282. If the function is defined in scheme, its signature is the value of the 'signature variable
  3283. in its closure:
  3284. </p>
  3285. <pre class="indented">
  3286. &gt; (define f1 (let ((documentation "helpful info")
  3287. (signature '(boolean? real?)))
  3288. (lambda (x)
  3289. (positive? x))))
  3290. <em class="gray">f1</em>
  3291. &gt; (procedure-documentation f1)
  3292. <em class="gray">"helpful info"</em>
  3293. &gt; (procedure-signature f1)
  3294. <em class="gray">(boolean? real?)</em>
  3295. </pre>
  3296. <p>We could do the same thing using methods:
  3297. </p>
  3298. <pre class="indented">
  3299. &gt; (define f1 (let ((procedure-documentation (lambda (f) "helpful info"))
  3300. (procedure-signature (lambda (f) '(boolean? real?))))
  3301. (<em class=red>openlet</em>
  3302. (lambda (x)
  3303. (positive? x)))))
  3304. &gt; (procedure-documentation f1)
  3305. <em class="gray">"helpful info"</em>
  3306. &gt; (procedure-signature f1)
  3307. <em class="gray">(boolean? real?)</em>
  3308. </pre>
  3309. <p>openlet alerts s7 that f1 has methods.
  3310. </p>
  3311. <blockquote>
  3312. <br>
  3313. <details>
  3314. <summary class="indented">examples</summary>
  3315. <div class="indented">
  3316. <p>procedure-source returns the actual function source. If you
  3317. call the function, the optimizer changes the source to suit itself,
  3318. so if you want to walk over the function body or change it in some way,
  3319. make a clean copy of
  3320. the procedure-source first (using, for example, copy-tree in stuff.scm).
  3321. </p>
  3322. <pre>
  3323. (define-bacro (procedure-annotate proc) ; use "bacro" so we can annotate local functions
  3324. (let ((orig (<em class=red>procedure-source</em> proc))) ; this assumes we haven't called "proc" yet
  3325. (define (proc-walk source)
  3326. (cond ((not (pair? source))
  3327. source)
  3328. ((not (memq (car source) '(let let*))) ; if let or let*, show local variables
  3329. (cons (proc-walk (car source))
  3330. (proc-walk (cdr source))))
  3331. ((symbol? (cadr source)) ; named let?
  3332. (append ; (let name vars . body) -&gt; (let name vars print-vars . body)
  3333. (list (car source)
  3334. (cadr source)
  3335. (caddr source)
  3336. `(format () " (let ~A (~{~A~^ ~}) ...)~%" ,(cadr source) (curlet)))
  3337. (cdddr source)))
  3338. (else ; (let(*) vars . body) -&gt; (let vars print-vars . body)
  3339. (append
  3340. (list (car source)
  3341. (cadr source)
  3342. `(format () " (~A (~{~A~^ ~}) ...)~%" ,(car source) (curlet)))
  3343. (cddr source)))))
  3344. (let* ((new-body (proc-walk orig))
  3345. (result (gensym))
  3346. (new-source
  3347. `(lambda ,(cadr orig)
  3348. (let ((,result #&lt;undefined&gt;))
  3349. (dynamic-wind
  3350. (lambda () ; upon entry, show procedure name and args
  3351. (format () "(~A~{ ~A~})~%"
  3352. ',proc
  3353. (outlet (outlet (curlet)))))
  3354. (lambda ()
  3355. (set! ,result (,new-body ,@(cadr orig))))
  3356. (lambda () ; at exit, show result
  3357. (if (eq? ,result #&lt;undefined&gt;)
  3358. (format () " ~A returns early~%" ',proc)
  3359. (format () " ~A returns ~A~%" ',proc ,result))))))))
  3360. `(define ,proc ,new-source))))
  3361. &gt; (define (hi a) (let ((b 12)) (+ b a)))
  3362. <em class="gray">hi</em>
  3363. &gt; (procedure-annotate hi)
  3364. <em class="gray">#&lt;lambda (a)&gt;</em>
  3365. &gt; (let ((x 32)) (+ 1 (hi x)))
  3366. <em class="gray">45</em>
  3367. ;; printing:
  3368. (hi (a . 32))
  3369. (let ((b . 12)) ...)
  3370. hi returns 44
  3371. </pre>
  3372. <p>But maybe something less invasive is better. Here's a version of let that prints
  3373. its bindings (this is borrowed from "nuntius" at reddit lisp):
  3374. </p>
  3375. <pre>
  3376. (define-macro (print-let bindings . body)
  3377. (let ((temp-symbol (gensym)))
  3378. `(let ,(map (lambda (var/val)
  3379. `(,(car var/val)
  3380. (let ((,temp-symbol ,(cadr var/val)))
  3381. (format () ";~S: ~S -&gt; ~S~%"
  3382. ',(car var/val)
  3383. ',(cadr var/val)
  3384. ,temp-symbol)
  3385. ,temp-symbol)))
  3386. bindings)
  3387. ,@body)))
  3388. ;; or simpler:
  3389. (define-macro (print-let bindings . body)
  3390. `(let ,bindings
  3391. (format () "~{;~A~%~}" (curlet))
  3392. ,@body))
  3393. </pre>
  3394. </div>
  3395. <div class="indented">
  3396. <p>A minor footnote: there are cases in s7 where aritable? can't tell whether
  3397. a given number of arguments can be applied to an object. For example,
  3398. <code>((list 1 (list 2 3)) 0 1)</code> is an error, but
  3399. <code>((list 1 (list 2 3)) 1 1)</code> is 3. So
  3400. <code>(aritable? (list 1 (list 2 3)) 2)</code> depdends on
  3401. what actual arguments you pass. In these cases, aritable? returns <code>#f</code>.
  3402. </p>
  3403. </div>
  3404. </details>
  3405. <div class="indented">
  3406. <pre>
  3407. (define (for-each-subset func args)
  3408. ;; form each subset of args, apply func to the subsets that fit its arity
  3409. (let subset ((source args)
  3410. (dest ())
  3411. (len 0))
  3412. (if (null? source)
  3413. (if (<em class=red>aritable?</em> func len) ; does this subset fit?
  3414. (apply func dest))
  3415. (begin
  3416. (subset (cdr source) (cons (car source) dest) (+ len 1))
  3417. (subset (cdr source) dest len)))))
  3418. </pre>
  3419. </div>
  3420. </blockquote>
  3421. <div class="header" id="evalstring"><h4>eval</h4></div>
  3422. <p>
  3423. <b>eval</b> evaluates its argument, a list representing a piece of code. It takes an optional
  3424. second argument, the environment in which the evaluation should take place. <b>eval-string</b>
  3425. is similar, but its argument is a string.
  3426. </p>
  3427. <pre class="indented">
  3428. &gt; (eval '(+ 1 2))
  3429. <em class="gray">3</em>
  3430. &gt; (eval-string "(+ 1 2)")
  3431. <em class="gray">3</em>
  3432. </pre>
  3433. <p>Leaving aside a few special cases, eval-string could be defined:
  3434. </p>
  3435. <pre class="indented">
  3436. (define-macro* (eval-string x e)
  3437. `(eval (with-input-from-string ,x read) (or ,e (curlet))))
  3438. </pre>
  3439. <blockquote>
  3440. <div class="indented">
  3441. <p>eval's environment argument is handy when implementing break and trace:
  3442. </p>
  3443. <pre>
  3444. (define *breaklet* #f)
  3445. (define *step-hook* (make-hook 'code 'e))
  3446. (define-macro* (trace/break code . break-points)
  3447. (define (caller tree)
  3448. (if (pair? tree)
  3449. (cons
  3450. (if (pair? (car tree))
  3451. (if (and (symbol? (caar tree))
  3452. (procedure? (symbol-&gt;value (caar tree))))
  3453. (if (member (car tree) break-points)
  3454. `(__break__ ,(caller (car tree)))
  3455. `(__call__ ,(caller (car tree))))
  3456. (caller (car tree)))
  3457. (car tree))
  3458. (caller (cdr tree)))
  3459. tree))
  3460. `(call-with-exit (lambda (__top__) ,(caller code))))
  3461. (define (go . args)
  3462. (and (let? *breaklet*)
  3463. (apply (*breaklet* 'go) args)))
  3464. (define (clear-break)
  3465. (set! *breaklet* #f))
  3466. (define-macro (__call__ code)
  3467. `(*step-hook* ',code (curlet)))
  3468. (define-macro (__break__ code)
  3469. `(begin
  3470. (call/cc
  3471. (lambda (go)
  3472. (set! *breaklet* (curlet))
  3473. (__top__ (format #f "break at: ~A~%" ',code))))
  3474. ,code))
  3475. (set! (hook-functions *step-hook*)
  3476. (list (lambda (hook)
  3477. (set! (hook 'result) (<em class=red>eval (hook 'code) (hook 'e)</em>)))))
  3478. (set! ((funclet *step-hook*) 'end)
  3479. (list (lambda (hook)
  3480. (define (uncaller tree)
  3481. (if (pair? tree)
  3482. (cons
  3483. (if (and (pair? (car tree))
  3484. (memq (caar tree) '(__call__ __break__)))
  3485. (uncaller (cadar tree))
  3486. (uncaller (car tree)))
  3487. (uncaller (cdr tree)))
  3488. tree))
  3489. (format (current-output-port) ": ~A -&gt; ~A~40T~A~%"
  3490. (uncaller (hook 'code))
  3491. (hook 'result)
  3492. (if (and (not (eq? (hook 'e) (rootlet)))
  3493. (not (defined? '__top__ (hook 'e))))
  3494. (map values (hook 'e))
  3495. "")))))
  3496. ;;; (trace/break (let ((a (+ 3 1)) (b 2)) (if (&gt; (* 2 a) b) 2 3)))
  3497. ;;; (trace/break (let ((a (+ 3 1)) (b 2)) (if (&gt; (* 2 a) b) 2 3)) (* 2 a))
  3498. </pre>
  3499. </div>
  3500. </blockquote>
  3501. <div class="header" id="IO"><h4>IO and other OS functions</h4></div>
  3502. <p>Besides files, ports can also represent strings and functions. The string port functions
  3503. are:
  3504. </p>
  3505. <pre class="indented">
  3506. (with-output-to-string thunk) ; open a string port as current-output-port, call thunk, return string
  3507. (with-input-from-string string thunk) ; open string as current-input-port, call thunk
  3508. (call-with-output-string proc) ; open a string port, apply proc to it, return string
  3509. (call-with-input-string string proc) ; open string as current-input-port, apply proc to it
  3510. (open-output-string) ; open a string output port
  3511. (get-output-string port clear) ; return output accumulated in the string output port
  3512. (open-input-string string) ; open a string input port reading string
  3513. </pre>
  3514. <pre class="indented">
  3515. &gt; (let ((result #f)
  3516. (p (<em class=red>open-output-string</em>)))
  3517. (format p "this ~A ~C test ~D" "is" #\a 3)
  3518. (set! result (<em class=red>get-output-string</em> p))
  3519. (close-output-port p)
  3520. result)
  3521. <em class="gray">"this is a test 3"</em>
  3522. </pre>
  3523. <p>In get-output-string, if the optional 'clear' argument is #t, the port is cleared (the default in r7rs I think).
  3524. Other functions:
  3525. </p>
  3526. <ul>
  3527. <li>read-byte and write-byte: binary IO.
  3528. <li>read-line: line-at-a-time reads, optional third argument #t to include the newline.
  3529. <li>current-error-port, set-current-error-port
  3530. </ul>
  3531. <p>The variable (*s7* 'print-length) sets
  3532. the upper limit on how many elements of a sequence are printed by object-&gt;string and format.
  3533. The end-of-file object is #&lt;eof&gt;.
  3534. When running s7 behind a GUI, you often want input to come from and output to go to
  3535. arbitrary widgets. The function ports provide a way to redirect IO in C. See <a href="#functionportexample">below</a>
  3536. for an example.
  3537. </p>
  3538. <blockquote>
  3539. <div class="indented">
  3540. <p>
  3541. The default IO ports are *stdin*, *stdout*, and *stderr*.
  3542. *stderr* is useful if you want to make sure output is flushed out immediately.
  3543. The default output port is *stdout* which buffers output until a newline is seen.
  3544. In most REPLs, the input port is set up by the REPL, so you need to use
  3545. *stdin* if you want to read from the terminal instead:
  3546. </p>
  3547. <pre class="indented">
  3548. &gt; (read-char)
  3549. <em class="gray">#&lt;eof&gt;</em>
  3550. &gt; (read-char *stdin*)
  3551. a ; here s7 waited for me to type "a" in the terminal
  3552. <em class="gray">#\a</em> ; this is the REPL reporting what read-char returned
  3553. </pre>
  3554. </div>
  3555. <div class="indented">
  3556. <p>An environment can be treated as an IO port, providing what Guile calls a "soft port":
  3557. </p>
  3558. <pre class="indented">
  3559. (define (call-with-input-vector v proc)
  3560. (let ((i -1))
  3561. (proc (openlet (inlet 'read (lambda (p) (v (set! i (+ i 1)))))))))
  3562. </pre>
  3563. <p>Here the IO port is an open environment that redefines the "read" function so that it
  3564. returns the next element of a vector. See stuff.scm for call-with-output-vector.
  3565. The "proc" argument above can also be a macro, giving you a kludgey way to get around
  3566. the dumb "lambda". Here are more useful examples:
  3567. </p>
  3568. <pre class="indented">
  3569. (openlet ; a soft port for format that sends its output to *stderr* and returns the string
  3570. (inlet 'format (lambda (port str . args)
  3571. (display (apply format #f str args) *stderr*))))
  3572. (define (open-output-log name)
  3573. ;; return a soft output port that does not hold its output file open
  3574. (define (logit name str)
  3575. (let ((p (open-output-file name "a")))
  3576. (display str p)
  3577. (close-output-port p)))
  3578. (openlet
  3579. (inlet :name name
  3580. :format (lambda (p str . args) (logit (p 'name) (apply format #f str args)))
  3581. :write (lambda (obj p) (logit (p 'name) (object-&gt;string obj #t)))
  3582. :display (lambda (obj p) (logit (p 'name) (object-&gt;string obj #f)))
  3583. :write-string (lambda (str p) (logit (p 'name) str))
  3584. :write-char (lambda (ch p) (logit (p 'name) (string ch)))
  3585. :newline (lambda (p) (logit (p 'name) (string #\newline)))
  3586. :close-output-port (lambda (p) #f)
  3587. :flush-output-port (lambda (p) #f))))
  3588. </pre>
  3589. </div>
  3590. <div class="indented">
  3591. <p>binary-io.scm in the Snd package has functions that read and write integers and floats in
  3592. both endian choices in a variety of sizes.
  3593. </p>
  3594. </div>
  3595. </blockquote>
  3596. <p>If the compile time switch WITH_SYSTEM_EXTRAS is 1, several additional OS-related and
  3597. file-related functions are built-in. This is work in progress; currently this switch
  3598. adds:
  3599. </p>
  3600. <pre class="indented">
  3601. (directory? str) ; return #t if str is the name of a directory
  3602. (file-exists? str) ; return #t if str names an existing file
  3603. (delete-file str) ; try to delete the file, return 0 is successful, else -1
  3604. (getenv var) ; return the value of an environment variable: (getenv "HOME")
  3605. (directory-&gt;list dir) ; return contents of directory as a list of strings (if HAVE_DIRENT_H)
  3606. (system command) ; execute command
  3607. </pre>
  3608. <p>But maybe this is not needed; see <a href="#cload">cload.scm</a> below for
  3609. a more direct approach.
  3610. </p>
  3611. <div class="header" id="errors"><h4>error handling</h4></div>
  3612. <pre class="indented">
  3613. (error tag . info) ; signal an error of type tag with addition information
  3614. (catch tag body err) ; if error of type tag signalled in body (a thunk), call err with tag and info
  3615. (throw tag . info) ; jump to corresponding catch
  3616. </pre>
  3617. <p>s7's error handling mimics that of Guile. An error is signalled
  3618. via the error function, and can be trapped and dealt with via <em class=def id="catch">catch</em>.
  3619. </p>
  3620. <pre class="indented">
  3621. &gt; (<em class=red>catch</em> 'wrong-number-of-args
  3622. (lambda () ; code protected by the catch
  3623. (abs 1 2))
  3624. (lambda args ; the error handler
  3625. (apply format #t (cadr args))))
  3626. <em class="gray">"abs: too many arguments: (1 2)"</em>
  3627. &gt; (<em class=red>catch</em> 'division-by-zero
  3628. (lambda () (/ 1.0 0.0))
  3629. (lambda args (string-&gt;number "inf.0")))
  3630. <em class="gray">inf.0</em>
  3631. (define-macro (catch-all . body)
  3632. `(<em class=red>catch</em> #t (lambda () ,@body) (lambda args args)))
  3633. </pre>
  3634. <p>
  3635. catch has 3 arguments: a tag indicating what error to catch (#t = anything),
  3636. the code, a thunk, that the catch is protecting, and the function to call
  3637. if a matching error occurs during the evaluation of the thunk. The error handler
  3638. takes a rest argument which will hold whatever the error function chooses to pass it.
  3639. The error function itself takes at least 2 arguments, the error type, a symbol,
  3640. and the error message. There may also be other arguments describing the error.
  3641. The default action, in the absence of any catch, is to treat the message as
  3642. a format control string, apply format to it and the other arguments, and
  3643. send that info to the current-error-port.
  3644. </p>
  3645. <blockquote>
  3646. <div class="indented">
  3647. <p>Normally when reading a file, we have to check for #&lt;eof&gt;, but we can let s7
  3648. do that:
  3649. </p>
  3650. <pre>
  3651. (define (copy-file infile outfile)
  3652. (call-with-input-file infile
  3653. (lambda (in)
  3654. (call-with-output-file outfile
  3655. (lambda (out)
  3656. (<em class=red>catch</em> 'wrong-type-arg ; s7 raises this error if write-char gets #&lt;eof&gt;
  3657. (lambda ()
  3658. (do () () ; read/write until #&lt;eof&gt;
  3659. (write-char (read-char in) out)))
  3660. (lambda err
  3661. outfile)))))))
  3662. </pre>
  3663. <p>catch is not limited to error handling:
  3664. </p>
  3665. <pre class="indented">
  3666. (define (map-with-exit func . args)
  3667. ;; map, but if early exit taken, return the accumulated partial result
  3668. ;; func takes escape thunk, then args
  3669. (let* ((result ())
  3670. (escape-tag (gensym))
  3671. (escape (lambda () (throw escape-tag))))
  3672. (<em class=red>catch</em> escape-tag
  3673. (lambda ()
  3674. (let ((len (apply max (map length args))))
  3675. (do ((ctr 0 (+ ctr 1)))
  3676. ((= ctr len) (reverse result)) ; return the full result if no throw
  3677. (let ((val (apply func escape (map (lambda (x) (x ctr)) args))))
  3678. (set! result (cons val result))))))
  3679. (lambda args
  3680. (reverse result))))) ; if we catch escape-tag, return the partial result
  3681. (define (truncate-if func lst)
  3682. (map-with-exit (lambda (escape x) (if (func x) (escape) x)) lst))
  3683. &gt; (truncate-if even? #(1 3 5 -1 4 6 7 8))
  3684. <em class="gray">(1 3 5 -1)</em>
  3685. </pre>
  3686. <p>But this is less useful than map (it can't map over a hash-table for example),
  3687. and is mostly reimplementing built-in code. Perhaps s7 should have an extension
  3688. of map (and more usefully, for-each) that is patterned after dynamic-wind:
  3689. <code>(dynamic-for-each init-func main-func end-func . args)</code> where init-func
  3690. is called with one argument, the length of the shortest sequence argument (for-each
  3691. and map know this in advance); main-func takes n arguments where n matches
  3692. the number of sequences passed; and end-func is called even if a jump out of main-func
  3693. occurs (like dynamic-wind in this regard). In the dynamic-map case, the end-func
  3694. takes one argument, the current, possibly partial, result list. dynamic-for-each
  3695. then could easily (but maybe not efficiently) implement generic functions such as -&gt;list, -&gt;vector, and
  3696. -&gt;string (converting any sequence into a sequence of some other type).
  3697. map-with-exit would be
  3698. </p>
  3699. <pre class="indented">
  3700. (define (map-with-exit func . args)
  3701. (let ((result ()))
  3702. (call-with-exit
  3703. (lambda (quit)
  3704. (apply dynamic-map #f ; no init-func in this case
  3705. (lambda main-args
  3706. (apply func quit main-args))
  3707. (lambda (res)
  3708. (set! result res))
  3709. args)))
  3710. result))
  3711. </pre>
  3712. </div>
  3713. <div class="indented">
  3714. <p>With all the lambda boilerplate, nested catches are hard to read:
  3715. </p>
  3716. <pre class="indented">
  3717. (catch #t
  3718. (lambda ()
  3719. (catch 'division-by-zero
  3720. (lambda ()
  3721. (catch 'wrong-type-arg
  3722. (lambda ()
  3723. (abs -1))
  3724. (lambda args (format () "got a bad arg~%") -1)))
  3725. (lambda args 0)))
  3726. (lambda args 123))
  3727. </pre>
  3728. <p>Perhaps we need a macro:
  3729. </p>
  3730. <pre class="indented">
  3731. (define-macro (catch-case clauses . body)
  3732. (let ((base `(lambda () ,@body)))
  3733. (for-each (lambda (clause)
  3734. (let ((tag (car clause)))
  3735. (set! base `(lambda ()
  3736. (catch ',(or (eq? tag 'else) tag)
  3737. ,base
  3738. ,@(cdr clause))))))
  3739. clauses)
  3740. (caddr base)))
  3741. ;;; the code above becomes:
  3742. (catch-case ((wrong-type-arg (lambda args (format () "got a bad arg~%") -1))
  3743. (division-by-zero (lambda args 0))
  3744. (else (lambda args 123)))
  3745. (abs -1))
  3746. </pre>
  3747. <p>This is similar to r7rs scheme's "guard", but I don't want a pointless thunk for the body of the catch.
  3748. Along the same lines:
  3749. </p>
  3750. <pre class="indented">
  3751. (define (catch-if test func err)
  3752. (catch #t
  3753. func
  3754. (lambda args
  3755. (apply (if (test (car args)) err throw) args)))) ; if not caught, re-raise the error via throw
  3756. (define (catch-member lst func err)
  3757. (catch-if (lambda (tag) (member tag lst)) func err))
  3758. (define-macro (catch* clauses . error)
  3759. ;; try each clause until one evaluates without error, else error:
  3760. ;; (macroexpand (catch* ((+ 1 2) (- 3 4)) 'error))
  3761. ;; (catch #t (lambda () (+ 1 2)) (lambda args (catch #t (lambda () (- 3 4)) (lambda args 'error))))
  3762. (define (builder lst)
  3763. (if (null? lst)
  3764. (apply values error)
  3765. `(catch #t (lambda () ,(car lst)) (lambda args ,(builder (cdr lst))))))
  3766. (builder clauses))
  3767. </pre>
  3768. </div>
  3769. <!--
  3770. (define (or-catch . funks)
  3771. (call-with-exit
  3772. (lambda (return)
  3773. (for-each
  3774. (lambda (f)
  3775. (catch #t
  3776. (lambda ()
  3777. (return (f)))
  3778. (lambda args
  3779. (case (car args)
  3780. ((wrong-type-arg) ...)
  3781. (...)
  3782. (else (apply throw args))))))
  3783. funks))))
  3784. -->
  3785. </blockquote>
  3786. <p>When an error is encountered, and when s7 is interrupted via <a href="#beginhook">begin_hook</a>,
  3787. (<em class=def id="owlet">owlet</em>) returns an environment that contains
  3788. additional info about that error:
  3789. </p>
  3790. <ul>
  3791. <li>error-type: the error type or tag, e.g. 'division-by-zero
  3792. <li>error-data: the message or information passed by the error function
  3793. <li>error-code: the code that s7 thinks triggered the error
  3794. <li>error-line: the line number of that code
  3795. <li>error-file: the file name of that code
  3796. <li>error-history: previous evaluations leading to the error (a circular list)
  3797. </ul>
  3798. <p>The error-history field depends on the compiler flag WITH_HISTORY. See ow! in
  3799. stuff.scm for one way to display this data. The *s7* field 'history-size sets the size of the buffer.
  3800. </p>
  3801. <blockquote>
  3802. <div class="indented">
  3803. <p>To find a variable's value at the point of the error: <code>((owlet) var)</code>.
  3804. To list all the local bindings from the error outward:
  3805. </p>
  3806. <pre class="indented">
  3807. (do ((e (outlet (owlet)) (outlet e)))
  3808. ((eq? e (rootlet)))
  3809. (format () "~{~A ~}~%" e))
  3810. </pre>
  3811. <p>To see the current s7 stack, <code>(stacktrace)</code>. You'll probably
  3812. want to use this in conjunction with *error-hook*.
  3813. To evaluate the error handler in the environment of the error:
  3814. </p>
  3815. <pre class="indented">
  3816. (let ((x 1))
  3817. (catch #t
  3818. (lambda ()
  3819. (let ((y 2))
  3820. (error 'oops)))
  3821. (lambda args
  3822. (with-let (sublet (owlet) :args args) ; add the error handler args
  3823. (list args x y))))) ; we have access to 'y'
  3824. </pre>
  3825. <p>To limit the maximum size of the stack, set (*s7* 'max-stack-size).
  3826. </p>
  3827. </div>
  3828. </blockquote>
  3829. <p>The hook <em class=def id="errorhook">*error-hook*</em> provides a way to specialize error reporting.
  3830. Its arguments are named 'type and 'data.
  3831. </p>
  3832. <pre class="indented">
  3833. (set! (hook-functions *error-hook*)
  3834. (list (lambda (hook)
  3835. (apply format *stderr* (hook 'data))
  3836. (newline *stderr*))))
  3837. </pre>
  3838. <p><em class=def id="readerrorhook">*read-error-hook*</em> provides two hooks into the reader.
  3839. A major problem when reading code written for other Schemes is that each Scheme provides
  3840. a plethora of idiosyncratic #-names (even special character names), and \ escapes in string
  3841. constants. *read-error-hook* provides a way to handle these weird cases. If a #-name
  3842. is encountered that s7 can't deal with, *read-error-hook* is called with two arguments,
  3843. #t and the string representing the constant. If you set (hook 'result), that result is
  3844. returned to the reader. Otherwise a 'read-error is raised and you drop into the error handler.
  3845. Similarly, if some bizaare \ use occurs, *read-error-hook* is called with two arguments,
  3846. #f and the offending character. If you return a character, it is passed to the reader;
  3847. otherwise you get an error. lint.scm has an example.
  3848. </p>
  3849. <p>
  3850. There is a break macro defined in Snd (snd-xen.c)
  3851. which allows you to stop at some point, then evaluate arbitrary expressions in that context.
  3852. </p>
  3853. <div class="indented">
  3854. <p>The s7-built-in catch tags are 'wrong-type-arg, 'syntax-error, 'read-error,
  3855. 'out-of-memory, 'wrong-number-of-args, 'format-error, 'out-of-range, 'division-by-zero, 'io-error, and 'bignum-error.
  3856. </p>
  3857. </div>
  3858. <div class="header" id="autoload"><h4>autoload</h4></div>
  3859. <!-- INDEX autoload:autoload -->
  3860. <p>
  3861. If s7 encounters an unbound variable, it first looks to see if it has any autoload information about it.
  3862. This info can be declared via <em class=def>autoload</em>, a function of two arguments, the
  3863. symbol that triggers the autoload, and either a filename or a function. If a filename, s7
  3864. loads that file; if a function, it is called with one argument, the current (calling) environment.
  3865. </p>
  3866. <pre class="indented">
  3867. (autoload 'channel-distance "dsp.scm")
  3868. ;; now if we subsequently call channel-distance but forget to load "dsp.scm" first,
  3869. ;; s7 loads "dsp.scm" itself, and uses its definition of channel-distance.
  3870. ;; The C-side equivalent is s7_autoload.
  3871. ;; here is the cload.scm case, loading j0 from the math library if it is called:
  3872. (autoload 'j0
  3873. (lambda (e)
  3874. (unless (provided? 'cload.scm)
  3875. (load "cload.scm"))
  3876. (c-define '(double j0 (double)) "" "math.h")
  3877. (varlet e 'j0 j0)))
  3878. </pre>
  3879. <p>The entity (hash-table or environment probably) that holds the autoload info is named *autoload*.
  3880. If after checking autoload, the symbol is still unbound, s7 calls
  3881. <em class=def id="unboundvariablehook">*unbound-variable-hook*</em>.
  3882. The offending symbol is named 'variable in the hook environment.
  3883. If after running *unbound-variable-hook*, the symbol is still unbound,
  3884. s7 calls the error handler.
  3885. </p>
  3886. <p>The autoloader knows about s7 environments used as libraries, so, for example,
  3887. you can <code>(autoload 'j0 "libm.scm")</code>, then use j0 in scheme code. The first
  3888. time s7 encounters j0, j0 is undefined, so
  3889. s7 loads libm.scm. That load returns the C math library as the environment *libm*.
  3890. s7 then automatically looks for j0 in *libm*, and defines it for you.
  3891. So the result is the same as if you had defined j0 yourself in C code.
  3892. You can use the r7rs library mechanism here, or with-let, or
  3893. whatever you want! (In Snd, libc, libm, libdl, and libgdbm are automatically
  3894. tied into s7 via autoload, so if you call, for example, frexp, libm.scm
  3895. is loaded, and frexp is exported from the *libm* environment, then the
  3896. evaluator soldiers on, as if frexp had always been defined in s7).
  3897. You can also import all of (say) gsl into the current environment
  3898. via <code>(varlet (curlet) *libgsl*)</code>.
  3899. </p>
  3900. <div class="header" id="constants"><h4>define-constant, constant?, symbol-access</h4></div>
  3901. <p><em class=def id="defineconstant">define-constant</em> defines a constant and
  3902. <em class=def id="constantp">constant?</em> returns #t if its argument
  3903. is a constant. A constant in s7 is really constant: it can't be set or rebound.
  3904. </p>
  3905. <pre class="indented">
  3906. &gt; (define-constant var 32)
  3907. <em class="gray">var</em>
  3908. &gt; (set! var 1)
  3909. <em class="gray">;set!: can't alter immutable object: var</em>
  3910. &gt; (let ((var 1)) var)
  3911. <em class="gray">;can't bind or set an immutable object: var, line 1</em>
  3912. </pre>
  3913. <p>This has the possibly surprising side effect that previous uses of the constant name
  3914. become constants:
  3915. </p>
  3916. <pre class="indented">
  3917. (define (func a) (let ((cvar (+ a 1))) cvar))
  3918. (define-constant cvar 23)
  3919. (func 1)
  3920. ;can't bind or set an immutable object: cvar
  3921. </pre>
  3922. <p>So, obviously, choose unique names for your constants, or don't use define-constant.
  3923. A function can also be a constant. In some cases, the optimizer can take advantage
  3924. of this information to speed up function calls.
  3925. </p>
  3926. <p>Constants are very similar to things such as keywords (no set, always return itself as its value),
  3927. variable trace (informative function upon set or keeping a history of past values), typed variables (restricting a
  3928. variable's values or doing automatic conversions upon set), and notification upon set (either in Scheme
  3929. or in C; I wanted this many years ago in Snd). The notification function is especially useful if
  3930. you have a Scheme variable and want to reflect any change in its value immediately in C (see <a href="#notify">below</a>).
  3931. In s7, <em class=def id="symbolaccess">symbol-access</em> sets this function.
  3932. </p>
  3933. <p>Each environment is a set of symbols and their associated values. symbol-access places a function (or macro) between a symbol
  3934. and its value in a given environment. The accessor function takes two arguments, the symbol and the new value, and
  3935. returns the value that is actually set. For example, the function can ensure that a variable is always an integer:
  3936. </p>
  3937. <pre class="indented">
  3938. (define e ; save environment for use below
  3939. (let ((x 3) ; will always be an integer
  3940. (y 3) ; will always keep its initial value
  3941. (z 3)) ; will report set!
  3942. (set! (symbol-access 'x) (lambda (s v) (if (integer? v) v x)))
  3943. (set! (symbol-access 'y) (lambda (s v) y))
  3944. (set! (symbol-access 'z) (lambda (s v) (format *stderr* "z ~A -&gt; ~A~%" z v) v))
  3945. (set! x 3.3) ; x does not change because 3.3 is not an integer
  3946. (set! y 3.3) ; y does not change
  3947. (set! z 3.3) ; prints "z 3 -&gt; 3.3"
  3948. (curlet)))
  3949. &gt; e
  3950. <em class="gray">(inlet 'x 3 'y 3 'z 3.3)</em>
  3951. &gt;(begin (set! (e 'x) 123) (set! (e 'y) #()) (set! (e 'z) #f))
  3952. ;; prints "z 3.3 -&gt; #f"
  3953. &gt; e
  3954. <em class="gray">(inlet 'x 123 'y 3 'z #f)</em>
  3955. &gt; (define-macro (reflective-let vars . body)
  3956. `(let ,vars
  3957. ,@(map (lambda (vr)
  3958. `(set! (symbol-access ',(car vr))
  3959. (lambda (s v)
  3960. (format *stderr* "~S -&gt; ~S~%" s v)
  3961. v)))
  3962. vars)
  3963. ,@body))
  3964. <em class="gray">reflective-let</em>
  3965. &gt; (reflective-let ((a 1)) (set! a 2))
  3966. <em class="gray">2</em> ; prints "a -&gt; 2"
  3967. &gt;(let ((a 0))
  3968. (set! (symbol-access 'a)
  3969. (let ((history (make-vector 3 0))
  3970. (position 0))
  3971. (lambda (s v)
  3972. (set! (history position) v)
  3973. (set! position (+ position 1))
  3974. (if (= position 3) (set! position 0))
  3975. v)))
  3976. (set! a 1)
  3977. (set! a 2)
  3978. ((funclet (symbol-access 'a)) 'history))
  3979. <em class="gray">#(1 2 0)</em>
  3980. </pre>
  3981. <p>Or implement reactive programming:
  3982. </p>
  3983. <pre class="indented">
  3984. (let ((a 1)
  3985. (b 2)
  3986. (c 3))
  3987. (set! (symbol-access 'b) (lambda (s v) (set! a (+ v c)) v))
  3988. (set! (symbol-access 'c) (lambda (s v) (set! a (+ b v)) v))
  3989. (set! a (+ b c)) ; a will be updated if b or c is set
  3990. (set! b 4)
  3991. (set! c 5)
  3992. a) ; a is 9 = (+ 4 5)
  3993. </pre>
  3994. <details>
  3995. <summary class="indented">reactive-let</summary>
  3996. <div class="indented">
  3997. <p>stuff.scm has reactive-set!, reactive-vector, reactive-let, reactive-let*, and reactive-lambda*:
  3998. </p>
  3999. <pre class="indented">
  4000. &gt; (let ((-a- 1)
  4001. (b 2))
  4002. (<em class=red>reactive-set!</em> -a- (* b 2))
  4003. (set! b 3)
  4004. -a-)
  4005. <em class="gray">6</em>
  4006. &gt; (let ((a 1))
  4007. (let ((v (<em class=red>reactive-vector</em> a (+ a 1) 2)))
  4008. (set! a 4)
  4009. v))
  4010. <em class="gray">#(4 5 2)</em>
  4011. &gt; (let ((a 1))
  4012. (<em class=red>reactive-let</em> ((-b- (+ a 1))) ; if 'a changes, '-b- does too
  4013. (set! a 3) ; so '-b- is now 4
  4014. -b-))
  4015. <em class="gray">4</em>
  4016. &gt; (let ((a 1))
  4017. (<em class=red>reactive-lambda*</em> (s v)
  4018. (format *stderr* "~S -&gt; ~S~%" s v))
  4019. (set! a 3))
  4020. <em class="gray">"a -&gt; 3"</em>
  4021. </pre>
  4022. <p>In the reactive-let example, the macro notices that '-b- depends on 'a, so it sets up a symbol-access on 'a
  4023. so that <code>(set! a 3)</code> triggers <code>(set! -b- (+ a 1))</code>. I'm using -name- to distinguish
  4024. the variables that can change value at any time; in the Lisp community, +name+ is often used to mark a constant,
  4025. so this seems like a natural convention.
  4026. </p>
  4027. <p>Here's the standard example of following the mouse (assuming you're using Snd and glistener):
  4028. </p>
  4029. <pre class="indented">
  4030. (let ((*mouse-x* 0) (*mouse-y* 0)
  4031. (x 0) (y 0))
  4032. (reactive-set! x (let ((val (round *mouse-x*)))
  4033. (format *stderr* "mouse: ~A ~A~%" x y)
  4034. val))
  4035. (reactive-set! y (round *mouse-y*))
  4036. (g_signal_connect (G_OBJECT (listener-text-widget *listener*)) "motion_notify_event"
  4037. (lambda (w e d)
  4038. (let ((mxy (cdr (gdk_event_get_coords (GDK_EVENT e)))))
  4039. (set! *mouse-x* (car mxy))
  4040. (set! *mouse-y* (cadr mxy))))))
  4041. </pre>
  4042. <!--
  4043. (let ((*mouse-x* 0) (*mouse-y* 0))
  4044. (g_signal_connect (G_OBJECT (listener-text-widget *listener*)) "motion_notify_event"
  4045. (lambda (w e d)
  4046. (let ((mxy (gdk_event_get_coords (GDK_EVENT e))))
  4047. (set! *mouse-x* (cadr mxy))
  4048. (set! *mouse-y* (caddr mxy)))))
  4049. (with-accessors (*mouse-x* *mouse-y*)
  4050. (let ((x 0) (y 0))
  4051. (reactive-set! x (let ((val (round *mouse-x*)))
  4052. (format *stderr* "mouse: ~A ~A~%" x y)
  4053. val))
  4054. (reactive-set! y (round *mouse-y*))
  4055. (gtk_main))))
  4056. -->
  4057. <p>reactive-lambda* is aimed at library consistency. Say we have the following library
  4058. that wants A to always be half B:
  4059. </p>
  4060. <pre class="indented">
  4061. (define (make-library)
  4062. (let ((A 1.0)
  4063. (B 2.0))
  4064. (reactive-lambda* (s v)
  4065. (case s
  4066. ((A) (set! B (* 2 v)))
  4067. ((B) (set! A (/ v 2)))))
  4068. (define (f1 x)
  4069. (+ A (* B x)))
  4070. (curlet)))
  4071. (with-let (make-library)
  4072. (format *stderr* "(f1 3): ~A~%" (f1 3))
  4073. (set! A 3.0)
  4074. (format *stderr* "A: ~A, B: ~A, (f1 3): ~A~%" A B (f1 3))
  4075. (set! B 4.0)
  4076. (format *stderr* "A: ~A, B: ~A, (f1 3): ~A~%" A B (f1 3)))
  4077. </pre>
  4078. <p>reactive-lambda* sets up accessors on the library's top-level variables
  4079. that call the lambda body if one of the variables is set.
  4080. </p>
  4081. <p>None of these macros does the right thing yet; I'm sort of following my nose.
  4082. </p>
  4083. </div>
  4084. </details>
  4085. <div class="header" id="miscellanea"><h4>marvels and curiousities</h4></div>
  4086. <p>
  4087. <b><em class=def id="loadpath">*load-path*</em></b> is a list of directories to search when loading a file.
  4088. <b><em class=def id="loadhook">*load-hook*</em></b> is a hook whose functions are called just before a file is loaded.
  4089. The hook function argument, named 'name, is the filename.
  4090. While loading, the <em class=def id="portfilename">port-filename</em> and
  4091. <em class=def id="portlinenumber">port-line-number</em> of the current-input-port can tell you
  4092. where you are in the file. This data is available after loading via <em class=def id="pairlinenumber">pair-line-number</em>
  4093. and <em class=def id="pairfilename">pair-filename</em>. port-line-number is settable (for fancy *#readers*).
  4094. </p>
  4095. <pre class="indented">
  4096. (set! (hook-functions *load-hook*)
  4097. (list (lambda (hook)
  4098. (format () "loading ~S...~%" (hook 'name)))))
  4099. (set! (hook-functions *load-hook*)
  4100. (cons (lambda (hook)
  4101. (format *stderr* "~A~%"
  4102. (system (string-append "./snd lint.scm -e '(begin (lint \"" (hook 'name) "\") (exit))'") #t)))
  4103. (hook-functions *load-hook*)))
  4104. </pre>
  4105. <p>Here's a *load-hook* function that adds the loaded file's directory
  4106. to the *load-path* variable so that subsequent loads don't need to specify
  4107. the directory:
  4108. </p>
  4109. <pre class="indented">
  4110. (set! (hook-functions <em class=red>*load-hook*</em>)
  4111. (list (lambda (hook)
  4112. (let ((pos -1)
  4113. (filename (hook 'name)))
  4114. (do ((len (length filename))
  4115. (i 0 (+ i 1)))
  4116. ((= i len))
  4117. (if (char=? (filename i) #\/)
  4118. (set! pos i)))
  4119. (if (positive? pos)
  4120. (let ((directory-name (substring filename 0 pos)))
  4121. (if (not (member directory-name <em class=red>*load-path*</em>))
  4122. (set! <em class=red>*load-path*</em> (cons directory-name *load-path*)))))))))
  4123. </pre>
  4124. <div class="separator"></div>
  4125. <p>As in Common Lisp, <b><em class=def id="featureslist">*features*</em></b> is a list describing what is currently loaded into s7. You can
  4126. check it with the <b>provided?</b> function, or add something to it with <b>provide</b>. In my version of Snd,
  4127. at startup *features* is:
  4128. </p>
  4129. <pre class="indented">
  4130. &gt; *features*
  4131. <em class="gray">(snd-16.7 snd15 snd audio snd-s7 snd-gtk gsl alsa gtk2 xg clm6 clm sndlib linux
  4132. dlopen complex-numbers system-extras ratio s7-3.26 s7) </em>
  4133. &gt; (provided? 'gsl)
  4134. <em class="gray">#t</em>
  4135. </pre>
  4136. <p>The other side of <code>provide</code> is <em class=def id="requires7">require</em>.
  4137. <code>(require . things)</code> finds each thing
  4138. (via <a href="#autoload">autoload</a>), and if that thing has not already been loaded,
  4139. loads the associated file. <code>(require integrate-envelope)</code>
  4140. loads "env.scm", for example; in this case it is equivalent to
  4141. simply using integrate-envelope, but if placed at the start of
  4142. a file, it documents that you're using that function.
  4143. In the more normal use, <code>(require snd-ws.scm)</code>
  4144. looks for the file that has <code>(provide 'snd-ws.scm)</code>
  4145. and if it hasn't already been loaded, loads it ("ws.scm" in this case).
  4146. To add your own files to this mechanism, add the provided symbol via <a href="#autoload">autoload</a>.
  4147. Since load can take an environment argument, *features* and its friends follow block structure.
  4148. So, for example, (let () (require stuff.scm) ...) loads "stuff.scm" into the local environment,
  4149. not globally.
  4150. </p>
  4151. <div class="indented">
  4152. <p>*features* is an odd variable: it is spread out across the chain of environments, and
  4153. can hold features in an intermediate environment that aren't in subsequent (nested) values.
  4154. One simple way this can happen is to load a file in a let, but cause the load to happen
  4155. at the top level. The provided entities get added to the top-level *features* value,
  4156. not the current let's value, but they are actually accessible locally. So *features*
  4157. is a merge of all its currently accessible values, vaguely like call-next-method in
  4158. CLOS. We can mimic this behavior:
  4159. </p>
  4160. <pre class="indented">
  4161. (let ((x '(a)))
  4162. (let ((x '(b)))
  4163. (define (transparent-memq sym var e)
  4164. (let ((val (symbol-&gt;value var e)))
  4165. (or (and (pair? val)
  4166. (memq sym val))
  4167. (and (not (eq? e (rootlet)))
  4168. (transparent-memq sym var (outlet e))))))
  4169. (let ((ce (curlet)))
  4170. (list (transparent-memq 'a 'x ce)
  4171. (transparent-memq 'b 'x ce)
  4172. (transparent-memq 'c 'x ce)))))
  4173. '((a) (b) #f)
  4174. </pre>
  4175. </div>
  4176. <!--
  4177. (let ((spread-function (lambda (x e) (+ x 1))))
  4178. (let ((spread-function (lambda (x e) (+ x 2))))
  4179. (let ((x 3))
  4180. (define (spread-function x e)
  4181. (let ((val x))
  4182. (do ((e1 e (outlet e1)))
  4183. ((eq? e1 (rootlet)) val)
  4184. (let ((f (symbol->value 'spread-function e1)))
  4185. (if (procedure? f)
  4186. (set! val (f val (rootlet))))))))
  4187. (spread-function x (curlet)))))
  4188. 6
  4189. -->
  4190. <div class="separator"></div>
  4191. <p>Multi-line and in-line comments can be enclosed in #| and |#.
  4192. <code>(+ #| add |# 1 2)</code>.
  4193. </p>
  4194. <div class="indented">
  4195. <p>Leaving aside this case and the booleans, #f and #t, you can specify your own handlers for
  4196. tokens that start with "#". <b><em class=def id="sharpreaders">*#readers*</em></b> is a list of pairs: <code>(char . func)</code>.
  4197. "char" refers to the first character after the sharp sign (#). "func" is a function of
  4198. one argument, the string that follows the #-sign up to the next delimiter. "func" is called
  4199. when #&lt;char&gt; is encountered. If it returns something other than #f, the #-expression
  4200. is replaced with that value. Scheme has several predefined #-readers for cases such
  4201. as #b1, #\a, #i123, and so on, but you can override these if you like. If the string
  4202. passed in is not the complete #-expression, the function can use read-char or read to get the
  4203. rest. Say we'd like #t&lt;number&gt; to interpret the number in base 12:
  4204. </p>
  4205. <pre class="indented">
  4206. (set! *#readers* (cons (cons #\t (lambda (str) (string-&gt;number (substring str 1) 12))) *#readers*))
  4207. &gt; #tb
  4208. <em class="gray">11</em>
  4209. &gt; #t11.3
  4210. <em class="gray">13.25</em>
  4211. </pre>
  4212. <p>Or have #c(real imag) be read as a complex number:
  4213. </p>
  4214. <pre class="indented">
  4215. (set! *#readers* (cons (cons #\c (lambda (str) (apply complex (read)))) *#readers*))
  4216. &gt; #c(1 2)
  4217. <em class="gray">1+2i</em>
  4218. </pre>
  4219. <p>Here's a reader macro for read-time evaluation:
  4220. </p>
  4221. <pre class="indented">
  4222. (set! *#readers*
  4223. (cons (cons #\. (lambda (str)
  4224. (and (string=? str ".") (eval (read)))))
  4225. *#readers*))
  4226. &gt; '(1 2 #.(* 3 4) 5)
  4227. <em class="gray">(1 2 12 5)</em>
  4228. </pre>
  4229. <p>And a reader that implements #[...]# for literal hash-tables:
  4230. </p>
  4231. <pre class="indented">
  4232. &gt; (set! *#readers*
  4233. (list (cons #\[ (lambda (str)
  4234. (let ((h (make-hash-table)))
  4235. (do ((c (read) (read)))
  4236. ((eq? c ']#) h) ; ]# is a symbol from the reader's point of view
  4237. (set! (h (car c)) (cdr c))))))))
  4238. <em class="gray">((#\[ . #&lt;lambda (str)&gt;))</em>
  4239. &gt; #[(a . 1) (b . #[(c . 3)]#)]#
  4240. <em class="gray">(hash-table '(b . (hash-table '(c . 3))) '(a . 1))</em>
  4241. </pre>
  4242. <p>To return no value from a reader, use <code>(values)</code>.
  4243. </p>
  4244. <pre class="indented">
  4245. &gt; (set! *#readers* (cons (cons #\; (lambda (str) (if (string=? str ";") (read)) (values))) *#readers*))
  4246. <em class="gray">((#\; . #&lt;lambda (str)&gt;))</em>
  4247. &gt; (+ 1 #;(* 2 3) 4)
  4248. <em class="gray">5</em>
  4249. </pre>
  4250. <p>Here is CL's #+ reader:
  4251. </p>
  4252. <pre class="indented">
  4253. (define (sharp-plus str)
  4254. ;; str here is "+", we assume either a symbol or an expression involving symbols follows
  4255. (let ((e (if (string=? str "+")
  4256. (read) ; must be #+(...)
  4257. (string-&gt;symbol (substring str 1)))) ; #+feature
  4258. (expr (read))) ; this is the expression following #+
  4259. (if (symbol? e)
  4260. (if (provided? e)
  4261. expr
  4262. (values))
  4263. (if (not (pair? e))
  4264. (error "strange #+ chooser: ~S~%" e)
  4265. (begin ; evaluate the #+(...) expression as in cond-expand
  4266. (define (traverse tree)
  4267. (if (pair? tree)
  4268. (cons (traverse (car tree))
  4269. (if (null? (cdr tree)) () (traverse (cdr tree))))
  4270. (if (memq tree '(and or not)) tree
  4271. (and (symbol? tree) (provided? tree)))))
  4272. (if (eval (traverse e))
  4273. expr
  4274. (values)))))))
  4275. </pre>
  4276. <p>See also the <a href="#circularlistreader">#n=</a> reader below.</p>
  4277. </div>
  4278. <div class="separator"></div>
  4279. <p id="makelist">(<b>make-list</b> length (initial-element #f)) returns a list of 'length' elements defaulting to 'initial-element'.
  4280. </p>
  4281. <div class="separator"></div>
  4282. <pre class="indented">
  4283. (<em class=def id="charposition">char-position</em> char-or-string searched-string (start 0))
  4284. (<em class=def id="stringposition">string-position</em> substring searched-string (start 0))
  4285. </pre>
  4286. <p>
  4287. <b>char-position</b> and <b>string-position</b> search a string for the occurrence of a character,
  4288. any of a set of characters, or a string. They return either #f if none is found, or the position
  4289. within the searched string of the first occurrence. The optional third argument sets where the
  4290. search starts in the second argument.
  4291. </p>
  4292. <p>If char-position's first argument is a string, it is treated as a set of characters, and
  4293. char-position looks for the first occurrence of any member of that set.
  4294. Currently, the strings involved are assumed to be C strings (don't expect embedded nulls
  4295. to work right in this context).
  4296. </p>
  4297. <pre class="indented">
  4298. (call-with-input-file "s7.c" ; report any lines with "static " but no following open paren
  4299. (lambda (file)
  4300. (let loop ((line (read-line file #t)))
  4301. (or (eof-object? line)
  4302. (let ((pos (<em class=red>string-position</em> "static " line)))
  4303. (if (and pos
  4304. (not (<em class=red>char-position</em> #\( (substring line pos))))
  4305. (if (&gt; (length line) 80)
  4306. (begin (display (substring line 0 80)) (newline))
  4307. (display line))))
  4308. (loop (read-line file #t)))))))
  4309. </pre>
  4310. <div class="separator"></div>
  4311. <p id="keywords">
  4312. Keywords exist mainly for define*'s benefit. The keyword functions are:
  4313. <b>keyword?</b>, <b>make-keyword</b>, <b>symbol-&gt;keyword</b>, and <b>keyword-&gt;symbol</b>.
  4314. A keyword is a symbol that starts or ends with a colon. The colon
  4315. is considered to be a part of the symbol name. A keyword is a constant that evaluates to itself.
  4316. </p>
  4317. <div class="separator"></div>
  4318. <pre class="indented">
  4319. (<em class=def id="symboltable">symbol-table</em>)
  4320. (<em class=def id="symboltovalue">symbol-&gt;value</em> sym (env (curlet)))
  4321. (<em class=def id="symboltodynamicvalue">symbol-&gt;dynamic-value</em> sym)
  4322. (<em class=def id="definedp">defined?</em> sym (env (curlet)) ignore-global-env)
  4323. </pre>
  4324. <p>
  4325. <code>defined?</code> returns #t if the symbol is defined in the environment:
  4326. </p>
  4327. <pre class="indented">
  4328. (define-macro (defvar name value)
  4329. `(unless (defined? ',name)
  4330. (define ,name ,value)))
  4331. </pre>
  4332. <p>If ignore-global-env is #t, the search is confined to the given environment.
  4333. <code>symbol-&gt;value</code> returns the value (lexically) bound to the symbol, whereas <code>symbol-&gt;dynamic-value</code>
  4334. returns the value dynamically bound to it. A variable can access both of its values:
  4335. </p>
  4336. <pre class="indented">
  4337. &gt; (let ((x 32))
  4338. (define (gx) ; return both bindings of 'x
  4339. (list x (<em class=red>symbol-&gt;value</em> 'x) (<em class=red>symbol-&gt;dynamic-value</em> 'x)))
  4340. (let ((x 100))
  4341. (let ((x 12))
  4342. (values (gx))))) ; this 'values' looks dumb, it is dumb, but see my unconvincing explanantion <a href="#weaselwords">below</a>.
  4343. ; briefly: "dynamic binding" in s7 is not "lexically apparent dynamic binding"
  4344. <em class="gray">(32 32 12)</em>
  4345. </pre>
  4346. <p>
  4347. <code>symbol-table</code> returns a vector containing the symbols currently in the symbol-table.
  4348. Here we scan the symbol table looking for any function that doesn't have documentation:
  4349. </p>
  4350. <pre class="indented">
  4351. (for-each
  4352. (lambda (sym)
  4353. (if (<em class=red>defined?</em> sym)
  4354. (let ((val (<em class=red>symbol-&gt;value</em> sym)))
  4355. (if (and (procedure? val)
  4356. (string=? "" (procedure-documentation val)))
  4357. (format *stderr* "~S " sym)))))
  4358. (<em class=red>symbol-table</em>))
  4359. </pre>
  4360. <div class="indented">
  4361. <p>Here's a better example, an automatic software tester.
  4362. </p>
  4363. <pre class="indented">
  4364. (for-each
  4365. (lambda (sym)
  4366. (if (<em class=red>defined?</em> sym)
  4367. (let ((val (<em class=red>symbol-&gt;value</em> sym)))
  4368. (if (procedure? val)
  4369. (let ((max-args (cdr (arity val))))
  4370. (if (or (&gt; max-args 4)
  4371. (memq sym '(exit abort)))
  4372. (format () ";skip ~S for now~%" sym)
  4373. (begin
  4374. (format () ";whack on ~S...~%" sym)
  4375. (let ((constants (list #f #t pi () 1 1.5 3/2 1.5+i)))
  4376. (let autotest ((args ()) (args-left max-args))
  4377. (catch #t (lambda () (apply func args)) (lambda any #f))
  4378. (if (&gt; args-left 0)
  4379. (for-each
  4380. (lambda (c)
  4381. (autotest (cons c args) (- args-left 1)))
  4382. constants)))))))))))
  4383. (<em class=red>symbol-table</em>))
  4384. </pre>
  4385. </div>
  4386. <details id="weaselwords">
  4387. <summary class="indented">more on dynamic values</summary>
  4388. <div class="indented">
  4389. <p>Why the useless 'values' in our dynamic binding example? The short answer: tail calls.
  4390. The long winded one goes something like this. symbol-&gt;dynamic-value searches the stack to find
  4391. the latest binding of its argument. But because we want to support tail calls, "let" does not
  4392. push anything on the stack. If we call a function as the last thing that happens in that let's body,
  4393. and it tries (internally) to access a dynamic binding, the let that launched the function no longer exists; it might already
  4394. be garbage collected, and it certainly isn't on the stack. Take our earlier example without the
  4395. 'values':
  4396. </p>
  4397. <pre class="indented">
  4398. (let ((x 32))
  4399. (define (gx)
  4400. (symbol-&gt;dynamic-value 'x))
  4401. (let ((x 100))
  4402. (gx)))
  4403. </pre>
  4404. <p>
  4405. This returns 32 because the <code>(x 100)</code> binding no longer exists anywhere when the gx body is evaluated.
  4406. So, in s7, the "dynamic binding" of x is the last binding of x that is accessible
  4407. to s7. This may not be the last binding that we can see in the code text, but I don't see that as
  4408. an inconsistency. It's not lexical after all.
  4409. Leaving aside this special case, so to speak,
  4410. dynamic binding does what you'd expect, even in the context of call/cc. See s7test.scm for
  4411. the MIT-Scheme test of that interaction.
  4412. </p>
  4413. <p>There is another way to get the call-time value:
  4414. </p>
  4415. <pre class="indented">
  4416. (define-macro (elambda args . body)
  4417. `(define-macro (,(gensym) ,@args)
  4418. `((lambda* ,(append ',args `((*env* (curlet))))
  4419. ,'(begin ,@body))
  4420. ,,@args)))
  4421. (define efunc (elambda (x) (+ (*env* 'y) x))) ; add x to the run-time value of y
  4422. (let ((y 3)) (efunc 1)) ; returns 4
  4423. </pre>
  4424. <p>elambda does not suffer from the symbol-&gt;dynamic-value defects mentioned above, but
  4425. it's probably slower. We have to wrap the function in a macro because lambda*'s argument default
  4426. values are evaluated in the definition environment, but we want the run-time environment.
  4427. </p>
  4428. <pre class="indented">
  4429. (define-macro* (rlambda args . body) ; lambda* but eval arg defaults in run-time env
  4430. (let ((arg-names (map (lambda (arg) (if (pair? arg) (car arg) arg)) args))
  4431. (arg-defaults (map (lambda (arg) (if (pair? arg) `(,(car arg) (eval ,(cadr arg))) arg)) args)))
  4432. `(define-bacro* (,(gensym) ,@arg-defaults)
  4433. `((lambda ,',arg-names ,'(begin ,@body)) ,,@arg-names))))
  4434. <!-- ( -->
  4435. (let ()
  4436. (define rx (rlambda ((a x))
  4437. (if (> a 0)
  4438. (let ((x (- x 1))) ;:)
  4439. (rx))
  4440. 0)))
  4441. (let ((x 3))
  4442. (rx)))
  4443. </pre>
  4444. <p>Now putting that idea with the procedure-annotation macro given earlier, and the __func__ business
  4445. (to get the caller's name), and taking care to handle default arguments correctly, we make a
  4446. macro that returns an anonymous macro that returns an anonymous function that &mdash; where was I?
  4447. </p>
  4448. <pre class="indented">
  4449. (define-macro (Display definition) ; (Display (define (f1 x) (+ x 1))) -&gt; an annotated version of f1
  4450. (let ((func (caadr definition))
  4451. (args (cdadr definition)))
  4452. (let ((arg-names (map (lambda (a) (if (symbol? a) a (car a))) args))
  4453. (body (proc-walk `(begin ,@(cddr definition))))) ; from procedure-annotation above
  4454. `(define ,func
  4455. (define-macro* (,(gensym) ,@args)
  4456. (let ((e (gensym))
  4457. (result (gensym)))
  4458. `((lambda* ,(append ',arg-names `((,e (curlet)))) ; the calling environment
  4459. (let ((,result '?))
  4460. (dynamic-wind
  4461. (lambda () ; display the caller, if any, as well as the incoming arguments
  4462. (format *stderr* "(~A~{~^ ~A~})" ',',func
  4463. (map (lambda (slot)
  4464. (if (gensym? (car slot)) (values) slot))
  4465. (outlet (outlet (curlet)))))
  4466. (let ((caller (eval '__func__ ,e)))
  4467. (if (not (eq? caller #&lt;undefined&gt;))
  4468. (format *stderr* " ;called from ~S" caller))
  4469. (newline *stderr*)))
  4470. (lambda () ; evaluate the original function's body with annotations
  4471. (set! ,result ,',body))
  4472. (lambda () ; display the result (it is returned by the set! above)
  4473. (format *stderr* " -&gt; ~S~%" ,result)))))
  4474. ,,@arg-names)))))))
  4475. </pre>
  4476. <p>stuff.scm has a more mature version of this macro.
  4477. </p>
  4478. </div>
  4479. </details>
  4480. <div class="separator"></div>
  4481. <p id="s7help"><b>help</b> tries to find information about its argument.
  4482. </p>
  4483. <pre class="indented">
  4484. &gt; (help 'caadar)
  4485. <em class="gray">"(caadar lst) returns (car (car (cdr (car lst)))): (caadar '((1 (2 3)))) -&gt; 2"</em>
  4486. </pre>
  4487. <div class="separator"></div>
  4488. <p id="s7gc"><b>gc</b> calls the garbage collector. <code>(gc #f)</code> turns off the GC, and <code>(gc #t)</code> turns it on.
  4489. </p>
  4490. <div class="separator"></div>
  4491. <pre class="indented">
  4492. (<b><em class=def id="morallyequalp">morally-equal?</em></b> x y)
  4493. </pre>
  4494. <p>
  4495. Say we want to check that two different computations came to the same result, and that result might
  4496. involve circular structures. Will equal? be our friend?
  4497. </p>
  4498. <pre class="indented">
  4499. &gt; (equal? 2 2.0)
  4500. <em class="gray">#f</em>
  4501. &gt; (let ((x +nan.0)) (equal? x x))
  4502. <em class="gray">#f</em>
  4503. &gt; (equal? .1 1/10)
  4504. <em class="gray">#f </em>
  4505. &gt; (= .1 1/10)
  4506. <em class="gray">#f</em>
  4507. &gt; (= 0.0 0+1e-300i)
  4508. <em class="gray">#f</em>
  4509. </pre>
  4510. <p>No! We need an equality check that ignores epsilonic differences in real and
  4511. complex numbers, and knows that NaNs are equal for all practical purposes.
  4512. Leaving aside numbers,
  4513. closed ports are not equal, yet nothing can be done with them.
  4514. #() is not equal to #2d(). And two closures are never equal, even if their
  4515. arguments, environments, and bodies are equal.
  4516. Since there might be circles, it is not easy to write
  4517. a replacement for equal? in Scheme.
  4518. So, in s7, if one thing is basically the same as
  4519. some other thing, they satisfy the function morally-equal?.
  4520. </p>
  4521. <pre class="indented">
  4522. &gt; (morally-equal? 2 2.0) ; would "equal!?" be a better name?
  4523. <em class="gray">#t</em>
  4524. &gt; (morally-equal? 1/0 1/0) ; NaN
  4525. <em class="gray">#t</em>
  4526. &gt; (morally-equal? .1 1/10)
  4527. <em class="gray">#t</em> ; floating-point epsilon here is 1.0e-15 or thereabouts
  4528. &gt; (morally-equal? 0.0 1e-300)
  4529. <em class="gray">#t</em>
  4530. &gt; (morally-equal? 0.0 1e-14)
  4531. <em class="gray">#f</em> ; its not always #t!
  4532. &gt; (morally-equal? (lambda () #f) (lambda () #f))
  4533. <em class="gray">#t</em>
  4534. </pre>
  4535. <p>The *s7* field morally-equal-float-epsilon sets the floating-point fudge factor.
  4536. I can't decide how bignums should interact with morally-equal?. Currently,
  4537. if a bignum is involved, either here or in a hash-table, s7 uses equal?.
  4538. Finally, if either argument is an environment with a 'morally-equal? method,
  4539. that method is invoked.
  4540. </p>
  4541. <div class="separator"></div>
  4542. <p>
  4543. <b><em class=def id="expansion">define-expansion</em></b> defines a macro that expands at read-time.
  4544. It has the same syntax as
  4545. define-macro, and (in normal use) the same result, but it is much faster because it expands only once.
  4546. (See define-with-macros in s7test.scm for a way to expand macros in a function body at definition time).
  4547. Since the reader knows almost nothing
  4548. about the code it is reading,
  4549. you need to make sure the expansion is defined at the top level and that its name is unique!
  4550. The reader does know about global variables, so:
  4551. </p>
  4552. <pre class="indented">
  4553. (define *debugging* #t)
  4554. (define-expansion (assert assertion)
  4555. (if *debugging* ; or maybe better, (eq? (symbol-&gt;value '*debugging*) #t)
  4556. `(unless ,assertion
  4557. (format *stderr* "~A: ~A failed~%" __func__ ',assertion))
  4558. (values)))
  4559. </pre>
  4560. <p>Now the assertion code is only present in the function body (or wherever)
  4561. if *debugging* is #t; otherwise assert expands into nothing. Another very handy
  4562. use is to embed a source file line number into a message; see for example lint-format
  4563. in lint.scm.
  4564. Leaving aside
  4565. read-time expansion and splicing, the real difference between define-macro and define-expansion
  4566. is that the expansion's result is not evaluated.
  4567. I'm no historian, but I believe that means that define-expansion creates
  4568. a (gasp!) f*xpr. In fact:
  4569. </p>
  4570. <pre>
  4571. (define-macro (define-f*xpr name-and-args . body)
  4572. `(define ,(car name-and-args)
  4573. (apply define-expansion
  4574. (append (list (append (list (gensym)) ',(cdr name-and-args))) ',body))))
  4575. &gt; (define-f*xpr (mac a) `(+ ,a 1))
  4576. <em class="gray">mac</em>
  4577. &gt; (mac (* 2 3))
  4578. <em class="gray">(+ (* 2 3) 1)</em>
  4579. </pre>
  4580. <p>
  4581. You can do something similar with a normal macro, or make the indirection explicit:
  4582. </p>
  4583. <pre class="indented">
  4584. &gt; (define-macro (fx x) `'(+ 1 ,x)) ; quote result to avoid evaluation
  4585. <em class="gray">fx</em>
  4586. &gt; (let ((a 3)) (fx a))
  4587. <em class="gray">(+ 1 a)</em>
  4588. &gt; (define-expansion (ex x) `(+ 1 ,x))
  4589. <em class="gray">ex</em>
  4590. &gt; (let ((x ex) (a 3)) (x a)) ; avoid read-time splicing
  4591. <em class="gray">(+ 1 a)</em>
  4592. &gt; (let ((a 3)) (ex a)) ; spliced in at read-time
  4593. <em class="gray">4</em>
  4594. </pre>
  4595. <p>As this example shows, the reader knows nothing about the program context,
  4596. so if it does not see a list whose first element is a expansion name, it does
  4597. not do anything special. In the <code>(x a)</code> case above, the
  4598. expansion happens when the code is evaluated, and the expansion result
  4599. is simply returned, unevaluated.
  4600. </p>
  4601. <p>You can also use macroexpand to cancel the evaluation of a macro's expansion:
  4602. </p>
  4603. <pre>
  4604. (define-macro (rmac . args)
  4605. (if (null? args)
  4606. ()
  4607. (if (null? (cdr args))
  4608. `(display ',(car args))
  4609. (list 'begin
  4610. `(display ',(car args))
  4611. (apply macroexpand (list (cons 'rmac (cdr args))))))))
  4612. &gt; (macroexpand (rmac a b c))
  4613. <em class="gray">(begin (display 'a) (begin (display 'b) (display 'c)))</em>
  4614. &gt; (begin (rmac a b c d) (newline))
  4615. <em class="gray">abcd</em>
  4616. </pre>
  4617. <p>The main built-in expansion is <b><em class=def id="readercond">reader-cond</em></b>. The syntax is based on cond:
  4618. the car of each clause is evaluated (in the read-time context), and if it is not false,
  4619. the remainder of that clause is spliced into the code as if you had typed it from the start.
  4620. </p>
  4621. <pre class="indented">
  4622. &gt; '(1 2 (reader-cond ((> 1 0) 3) (else 4)) 5 6)
  4623. <em class="gray">(1 2 3 5 6)</em>
  4624. &gt; ((reader-cond ((> 1 0) list 1 2) (else cons)) 5 6)
  4625. <em class="gray">(1 2 5 6)</em>
  4626. </pre>
  4627. <!-- from kanren
  4628. (define-syntax conj*
  4629. (syntax-rules ()
  4630. ((conj*) succeed)
  4631. ((conj* g) g)
  4632. ((conj* g gs ...)
  4633. (conj g (lambda (s) ((conj* gs ...) s))))))
  4634. is the same (in that context) as:
  4635. (define-macro (conj* . args)
  4636. (if (null? args)
  4637. succeed
  4638. (if (null? (cdr args))
  4639. (car args)
  4640. `(conj ,(car args)
  4641. (lambda (s) ((conj* ,@(cdr args)) s))))))
  4642. -->
  4643. <div class="separator"></div>
  4644. <p id="profiling">If you build s7 with the flag -DWITH_PROFILE=1, s7 accumulates profiling data
  4645. in the (*s7* 'profile-info) hash-table. The line number reported sometimes points to the end of the form.
  4646. Also, do loops and other iterations are sometimes highly optimized, so only the outer form is counted.
  4647. profile.scm shows one way to sort and display this data. To clear the counts, <code>(fill! (*s7* 'profile-info) #f)</code>.
  4648. </p>
  4649. <div class="separator"></div>
  4650. <p id="s7env"><b>*s7*</b> is an environment that gives access to some of s7's internal
  4651. state:
  4652. </p>
  4653. <pre class="indented">
  4654. print-length number of elements of a sequence to print
  4655. max-string-length max size arg to make-string and read-string
  4656. max-list-length max size arg to make-list
  4657. max-vector-length max size arg to make-vector and make-hash-table
  4658. max-vector-dimensions make-vector dimensions limit
  4659. default-hash-table-length default size for make-hash-table (8, tables resize as needed)
  4660. initial-string-port-length 128, initial size of a string port's buffer
  4661. history-size eval history buffer size if s7 built WITH_HISTORY=1
  4662. profile-info profiling data if s7 built WITH_PROFILE=1
  4663. default-rationalize-error 1e-12 (settable)
  4664. morally-equal-float-epsilon 1e-15 (settable)
  4665. hash-table-float-epsilon 1e-12 (settable, but currently limited to less than 1e-3).
  4666. bignum-precision bits for bignum floats (128)
  4667. float-format-precision digits to print for floats (16)
  4668. default-random-state the default arg for random (settable)
  4669. cpu-time run time so far
  4670. file-names currently loaded files (a list)
  4671. safety 0
  4672. undefined-identifier-warnings #f
  4673. catches a list of the currently active catch tags
  4674. exits a list of active call-with-exit exit functions
  4675. c-types a list of c-object type names (from s7_new_type, etc)
  4676. input-ports, output-ports, strings, gensyms, vectors, hash-tables, continuations
  4677. stack-top current stack location
  4678. stack-size current stack size
  4679. max-stack-size max stack size (settable)
  4680. stack the current stack entries
  4681. stacktrace-defaults stacktrace formatting info for error handler
  4682. symbol-table a vector
  4683. symbol-table-locked? #f (if #t, no new symbols can be added to the symbol table)
  4684. rootlet-size the number of globals
  4685. heap-size total cells currently available
  4686. free-heap-size the number of currently unused cells
  4687. gc-freed number of cells freed by the last GC pass
  4688. gc-protected-objects vector of the objects permanently protected from the GC
  4689. gc-stats #f (#t turns on printout of the GC activity)
  4690. memory-usage a description of current memory allocations
  4691. </pre>
  4692. <p>
  4693. Use the standard environment syntax to access these fields:
  4694. <code>(*s7* 'stack-top)</code>. stuff.scm has the function
  4695. *s7*-&gt;list that returns most of these fields in a list.
  4696. </p>
  4697. <p>
  4698. Set (*s7* 'safety) to 2 or higher
  4699. to turn off optimization.
  4700. </p>
  4701. <p>stacktrace-defaults is a list of four integers and a boolean that tell the error
  4702. handler how to format stacktrace information. The four integers are:
  4703. how many frames to display,
  4704. how many columns are devoted to code display,
  4705. how many columns are available for a line of data,
  4706. and where to place comments.
  4707. The boolean sets whether the entire output should be displayed as a comment.
  4708. The defaults are '(3 45 80 45 #t).
  4709. </p>
  4710. <pre class="indented">
  4711. (<em class=def id="cobject">c-object?</em> obj)
  4712. (<em class=def id="cpointer">c-pointer?</em> obj)
  4713. (<em class=def id="cpoint">c-pointer</em> int)
  4714. </pre>
  4715. <p>
  4716. You can wrap up raw C pointers and
  4717. pass them around in s7 code. The function c-pointer returns a wrapped pointer,
  4718. and c-pointer? returns #t if passed one. <code>(define NULL (c-pointer 0))</code>.
  4719. c-object? returns the object's type tag if passed such an object (otherwise #f of course). This tag is also the position
  4720. of the object's type in the (*s7* 'c-types) list.
  4721. (*s7* 'c-types) returns a list of the types created by s7_new_type_x and friends.
  4722. </p>
  4723. <div class="separator"></div>
  4724. <blockquote>
  4725. <div class="indented">
  4726. <p id="s7vsr5rs">Some other differences from r5rs:
  4727. </p>
  4728. <ul>
  4729. <li>no force or delay (see <a href="#r7rs">below</a>).
  4730. <li>no syntax-rules or any of its friends.
  4731. <li>no scheme-report-environment, null-environment, or interaction-environment (use curlet).
  4732. <li>no transcript-on or transcript-off.
  4733. <li>begin returns the value of the last form; it can contain both definitions and other statements.
  4734. <li>#&lt;unspecified&gt;, #&lt;eof&gt;, and #&lt;undefined&gt; are first-class objects.
  4735. <li>for-each and map accept different length arguments; the operation stops when any argument reaches its end.
  4736. <li>for-each and map accept any applicable object as the first argument, and any sequence or iterator as a trailing argument.
  4737. <li>letrec*, but without conviction.
  4738. <li>set! and *-set! return the new value (modulo symbol-access), not #&lt;unspecified&gt;.
  4739. <li>define and its friends return the new value.
  4740. <li>port-closed?
  4741. <li>list? means "pair or null", proper-list? is r5rs list?, float? means "real and not rational", sequence? = length.
  4742. <!-- a vector can be a member of itself, and yet vector? returns #t, why is list? different; we even call it a circular list! -->
  4743. <!-- <li>current-input-port, current-output-port, and current-error-port have setters (but I may remove these) -->
  4744. <li>the default IO ports are named *stdin*, *stdout*, and *stderr*.
  4745. <li>#f as an output port means nothing is output (#f is /dev/null, I guess).
  4746. <li>member and assoc accept an optional third argument, the comparison function (equal? is the default).
  4747. <li>case accepts =&gt; much like cond (the function argument is the selector).
  4748. <li>if WITH_SYSTEM_EXTRAS is 1, the following are built-in: directory?, file-exists?, delete-file, system, directory-&gt;list, getenv.
  4749. <li>s7 is case sensitive.
  4750. <li>when and unless (for r7rs), returning the value of the last form.
  4751. <li>the "d", "f", "s", and "l" exponent markers are not supported by default (use "e", "E", or "@").
  4752. <li>quasiquoted vector constants are not supported (use the normal list expansions wrapped in list-&gt;vector).
  4753. </ul>
  4754. <p>In s7 if a built-in function like gcd is referred to in a function
  4755. body, the optimizer is free to replace it with #_function. That is, <code>(gcd ...)</code> can be changed
  4756. to <code>(#_gcd ...)</code> at s7's whim, if gcd has its original value at the time the optimizer
  4757. sees the expression using it. A subsequent <code>(set! gcd +)</code> does not affect this optimized call.
  4758. I think I could wave my hands and mumble about "aggressive lexical scope" or something, but actually the
  4759. choice here is that speed trumps that ol' hobgoblin consistency. If you want to change gcd to +, do it before
  4760. loading code that calls gcd.
  4761. I think most Schemes handle macros this way: the macro call is replaced by its expansion using its current
  4762. definition, and a later redefinition does not affect earlier uses.
  4763. </p>
  4764. <!-- another case: (with-let (inlet '+ -) (+ 2 3)) -> 5 -->
  4765. <!-- also, (eq? (if #f #f) (apply values ())) is #t, but memq and assq don't treat them as equal -->
  4766. </div>
  4767. <!-- null-environment does not fit very well; how to shadow earlier define-constant for example
  4768. one of which is unlet; perhaps make a special environment at init time?
  4769. the code for that is save_null_environment, but it is untested and commented out.
  4770. -->
  4771. <div class="indented">
  4772. <p>Here are some changes I'd make to s7 if I didn't care about compatibility with other Schemes:
  4773. </p>
  4774. <ul>
  4775. <li>remove the exact/inexact distinction including #i and #e
  4776. <li>remove call-with-values and its friends
  4777. <li>remove char-ready?
  4778. <li>change eof-object? to eof? or just omit it (you can use eq? #&lt;eof&gt;)
  4779. <li>change make-rectangular to complex, and remove make-polar.
  4780. <li>remove unquote (the name, not the functionality).
  4781. <li>remove cond-expand.
  4782. <li>remove *-ci functions
  4783. <li>remove #d
  4784. </ul>
  4785. <p>(most of these are removed if you set the compiler flag WITH_PURE_S7), and perhaps:
  4786. </p>
  4787. <ul>
  4788. <li>remove even? and odd?, gcd and lcm.
  4789. <li>remove string-length and vector-length.
  4790. <li>remove list-ref|set!, string-ref|set!, vector-ref|set!, hash-table-ref|set!, set-car!|cdr!, and set-current-output|input|error-port.
  4791. <li>change file-exists? to file? (or omit it and assume the use of libc.scm &mdash; why reinvent the wheel?).
  4792. <li>remove all the conversion and copy functions like vector-&gt;list and vector-copy (use copy or map).
  4793. <li>add typeq? and perhaps make null? generic (see stuff.scm).
  4794. <li>change string-&gt;symbol to symbol (what to do with symbol-&gt;string in that case?)
  4795. <li>change with-output-to-* and with-input-from-* to omit the pointless lambda.
  4796. <li>remove the with-* IO functions (e.g. with-input-from-string), keeping the call-with-* versions (call-with-input-string).
  4797. <li>remove assq, assv, memq, and memv (these are pointless now that assoc and member can be passed eq? and eqv?).
  4798. </ul>
  4799. <p>There are several less-than-ideal names. Perhaps s7 should use *pi*, *most-negative-fixnum*,
  4800. *most-positive-fixnum* (*fixmost*?) so that all the built-in variables and constants have the
  4801. same kind of name (or +pi+ to show it is a constant?).
  4802. Perhaps object-&gt;string should be -&gt;string.
  4803. get-output-string should be current-output-string. write-char behaves like display, not write.
  4804. provided? should be feature? or *features* should be *provisions*.
  4805. </p>
  4806. <p>
  4807. The name "cond-expand" is bad &mdash; we're not expanding anything, and the macro's point is to make it easy to
  4808. operate with the *features* list; perhaps "cond-provided"? Not only is cond-expand poorly named, but the whole
  4809. idea is clumsy. Take libgsl.scm; different versions of the GSL library have different functions. We need to know
  4810. when we're building the FFI what GSL version we're dealing with. It would be nuts to start pushing and checking dozens
  4811. of library version symbols when all we actually want is <code>(&gt; version 23.19)</code>. (We are also politely
  4812. trying to ignore the ridiculous little language built into cond-expand; are we not running Scheme?).
  4813. In place of cond-expand, s7 uses <a href="#readercond">reader-cond</a>,
  4814. so the read-time decision involves normal evaluation.
  4815. </p>
  4816. <p>Then there's the case case: a case clause without a result appears to be an error in r7rs.
  4817. But the notation used to indicate that is the same as that used for begin.
  4818. So if we allow <code>(begin)</code>, we should allow case clauses to have no explicit result.
  4819. Currently in s7, the case case is an error and <code>(begin)</code> returns nil, which strikes me
  4820. as, *horrors*, inconsistent. But in cond,
  4821. the "implicit progn" (in CL terminology) includes the test expression, so a clause without a result returns
  4822. the test result (if true of course). In the case case, a similar approach might return
  4823. the selector value. So should <code>(case x ((0 1)))</code> be an error, or equivalent
  4824. to <code>(case x ((0 1) (begin)))</code> as in CL, or (my favorite) <code>(case x ((0 1) => values))</code>.
  4825. If the latter, an empty else statement would also return the selector since it would be the
  4826. same as <code>(else => values)</code>.
  4827. </p>
  4828. <p>
  4829. Better ideas are always welcome!
  4830. </p>
  4831. <p>Here are the built-in s7 variables:
  4832. </p>
  4833. <ul>
  4834. <li>*features* ; a list of symbols
  4835. <li>*libraries* ; a list of (filename . let) pairs
  4836. <li>*load-path* ; a list of directories
  4837. <li>*cload-directory* ; directory for cload output
  4838. <li>*autoload* ; autoload info
  4839. <li>*#readers* ; a list of (char . handler) pairs
  4840. </ul>
  4841. <p>And the built-in constants:
  4842. </p>
  4843. <ul>
  4844. <li>pi
  4845. <li>*stdin* *stdout* *stderr*
  4846. <li>*s7*
  4847. <li>nan.0 -nan.0 inf.0 -inf.0 (what crappy names! nan.0 is an inexact integer that is not a number?)
  4848. <li>most-positive-fixnum most-negative-fixnum
  4849. <li>*unbound-variable-hook* *missing-close-paren-hook* *load-hook* *error-hook* *read-error-hook*
  4850. </ul>
  4851. <p>__func__ is the name (or name and location) of the function currently being called, as in C.
  4852. </p>
  4853. <p>Currently WITH_PURE_S7:
  4854. </p>
  4855. <ul>
  4856. <li>places 'pure-s7 in *features*
  4857. <li>omits char-ready, char-ci*, string-ci*
  4858. <li>omits string-copy, string-fill!, vector-fill!, vector-append
  4859. <li>omits list-&gt;string, list-&gt;vector, string-&gt;list, vector-&gt;list, let-&gt;list
  4860. <li>omits string-length and vector-length
  4861. <li>omits cond-expand, multiple-values-bind|set!, call-with-values, defmacro(*)
  4862. <li>omits unquote (the name)
  4863. <li>omits d/f/s/l exponents
  4864. <li>omits make-polar and make-rectangular (use complex)
  4865. <li>omits integer-length, exact?, inexact?, exact-&gt;inexact, inexact-&gt;exact, #i and #e
  4866. <li>omits set-current-output-port and set-current-input-port
  4867. </ul>
  4868. </div>
  4869. <details>
  4870. <summary class="indented">quotes</summary>
  4871. <div class="indented">
  4872. <p>Schemes vary in their treatment of (). s7 considers it a constant that evaluates to itself,
  4873. so you don't need to quote it. <code>(eq? () '())</code> is #t.
  4874. This is consistent with, for example,
  4875. <code>(eq? #f '#f)</code> which is also #t.
  4876. The standard says "the empty list is a special object of its own type", so surely either choice is
  4877. acceptable in that regard. One place where the quote matters is in a case statement; the selector is
  4878. evaluated but the key is not:
  4879. </p>
  4880. <pre class="indented">
  4881. &gt; (case '() ((()) 2) (else 1))
  4882. <em class="gray">2</em>
  4883. &gt; (case '() (('()) 2) (else 1)) ; (eqv? '() ''()) is #f
  4884. <em class="gray">1</em>
  4885. ;;; which parallels #f (or a number such as 2 etc):
  4886. &gt; (case '#f ((#f) 2) (else 1))
  4887. <em class="gray">2</em>
  4888. &gt; (case '#f (('#f) 2) (else 1)) ; (eqv? '#f ''#f) is #f
  4889. <em class="gray">1</em>
  4890. </pre>
  4891. <p>Similarly, vector constants do not have to be quoted. A list constant is quoted
  4892. to keep it from being evaluated, but
  4893. #(1 2 3) is as unproblematic as "123" or 123.
  4894. </p>
  4895. <!-- there's another sense in which '() is a constant: you can't apply it to anything. ('() 0) -> error
  4896. -->
  4897. <p>These examples bring up another odd corner of scheme: else. In <code>(cond (else 1))</code>
  4898. the 'else is evaluated (like any cond test), so its value might be #f; in <code>(case 0 (else 1))</code>
  4899. it is not evaluated (like any case key), so it's just a symbol.
  4900. Since symbol accessors are local in s7,
  4901. someone can <code>(let ((else #f)) (cond (else 1)))</code> even if we protect the rootlet 'else.
  4902. Of course, in scheme this kind of trouble is pervasive, so rather than make 'else a constant
  4903. I think the best path is to use unlet:
  4904. <code>(let ((else #f)) (cond (#_else 1)))</code>. This is 1 (not ()) because the initial value of 'else
  4905. can't be changed.
  4906. </p>
  4907. </div>
  4908. </details>
  4909. <details>
  4910. <summary class="indented">mutable constants</summary>
  4911. <div class="indented">
  4912. <p>How should s7 treat this:
  4913. <code>(string-set! "hiho" 1 #\z)</code>, or
  4914. <code>(vector-set! #(1 2 3) 1 32)</code>, or
  4915. <code>(list-set! '(1 2 3) 1 32)</code>?
  4916. Originally, in s7, the first two were errors, and the third was allowed, which doesn't make much sense.
  4917. Guile and Common Lisp accept all three, but that leads to weird cases where we can reach
  4918. into a function's body:
  4919. </p>
  4920. <pre class="indented">
  4921. &gt; (let ((x (lambda () '(1 2 3)))) (list-set! (x) 1 32) (x))
  4922. <em class="gray">(1 32 3)</em> ; s7, Guile
  4923. &gt; (flet ((x () '(1 2 3))) (setf (nth 1 (x)) 32) (x))
  4924. <em class="gray">(1 32 3)</em> ; Clisp
  4925. &gt; (let ((x (lambda () (list 1 2 3)))) (list-set! (x) 1 32) (x))
  4926. <em class="gray">(1 2 3)</em>
  4927. </pre>
  4928. <p>
  4929. But it's possible to reach into a function's closure, even when the
  4930. closed-over thing is a constant:
  4931. </p>
  4932. <pre class="indented">
  4933. &gt; (flet ((x () '(1 2 3))) (setf (nth 1 (x)) 32) (x))
  4934. <em class="gray">(1 32 3)</em>
  4935. &gt; (let ((xx (let ((x '(1 2 3))) (lambda () x)))) (list-set! (xx) 1 32) (xx))
  4936. <em class="gray">(1 32 3)</em>
  4937. &gt; (let ((xx (let ((x (list 1 2 3))) (lambda () x)))) (list-set! (xx) 1 32) (xx))
  4938. <em class="gray">(1 32 3)</em>
  4939. </pre>
  4940. <p>
  4941. And it's possible to reach into a constant list via list-set! (or set-car! of course):
  4942. </p>
  4943. <pre class="indented">
  4944. &gt; (let* ((x '(1 2)) (y (list x)) (z (car y))) (list-set! z 1 32) (list x y z))
  4945. <em class="gray">((1 32) ((1 32)) (1 32))</em>
  4946. </pre>
  4947. <p>
  4948. It would be a programmer's nightmare to have to keep track of which piece of a list is
  4949. constant, and an implementor's nightmare to copy every list. set! in all its forms is
  4950. used for its side-effects, so why should we try to put a fence around them?
  4951. If we flush "immutable constant" because it is a ham-fisted, whack-it-with-a-shovel approach,
  4952. the only real problem I can see is symbol-&gt;string. In CL, this is explicitly an error:
  4953. </p>
  4954. <pre class="indented">
  4955. &gt; (setf (elt (symbol-name 'xyz) 1) #\X)
  4956. <em class="gray">*** - Attempt to modify a read-only string: "XYZ"</em>
  4957. </pre>
  4958. <p>And in Guile:
  4959. </p>
  4960. <pre class="indented">
  4961. &gt; (string-set! (symbol-&gt;string 'symbol-&gt;string) 1 #\X)
  4962. <em class="gray">ERROR: string is read-only: "symbol-&gt;string"</em>
  4963. </pre>
  4964. <p>So both have a notion of immutable strings.
  4965. I wonder what other Scheme programmers (not implementors!) want in this situation.
  4966. Currently, there are no immutable list, string, or vector constants, and
  4967. symbol-&gt;string
  4968. returns a copy of the string.
  4969. copy can protect some values. Or combine object-&gt;string and string-&gt;symbol:
  4970. </p>
  4971. <pre class="indented">
  4972. &gt; (let ((x (lambda () (copy "hiho")))) (string-set! (x) 1 #\x) (x))
  4973. <em class="gray">"hiho"</em>
  4974. &gt; (let ((x (string-&gt;symbol "hiho"))) (string-set! (symbol-&gt;string x) 1 #\x) (symbol-&gt;string x))
  4975. <em class="gray">"hiho"</em>
  4976. &gt; (define (immutable obj) (string-&gt;symbol (object-&gt;string obj :readable)))
  4977. <em class="gray">immutable</em>
  4978. &gt; (define (symbol-&gt;object sym) (eval-string (symbol-&gt;string sym)))
  4979. <em class="gray">symbol-&gt;object</em>
  4980. &gt; (symbol-&gt;object (immutable (list 1 2 3)))
  4981. <em class="gray">(1 2 3)</em>
  4982. </pre>
  4983. <p>s7 normally tries to optimize garbage collection by
  4984. removing some list constants from the heap. If you later
  4985. set a member of it to something that needs GC protection, nobody in the heap points to it, so
  4986. it is GC'd. Here is an example:
  4987. </p>
  4988. <pre class="indented">
  4989. (define (bad-idea)
  4990. (let* ((lst '(1 2 3))
  4991. (result (list-ref lst 1)))
  4992. (list-set! lst 1 (* 2.0 16.6))
  4993. (gc)
  4994. result))
  4995. </pre>
  4996. <p>Put this is a file, load it into the interpreter, then call <code>(bad-idea)</code> a
  4997. few times. You can turn off the optimization in question by setting the variable <code>(*s7* 'safety)</code>
  4998. to 1. <code>(*s7* 'safety)</code> defaults to 0.
  4999. </p>
  5000. <p>A similar problem arises when you want to walk a function's source or reuse a piece of
  5001. code directly. When the function is evaluated, the optimizer changes the program source
  5002. to speed up subsequent evaluation. This annotation process means that nothing in that
  5003. source is what it appears to be, so a tree walker will be confused, and if you copy that
  5004. source and try to insert it into some other program source, the existing annotations
  5005. will not fit the new context. In both cases, you can get a clean version of the code
  5006. by copying it with :readable as the second argument to copy. There is an example
  5007. in lint.scm, and in the snd file tools/tgen.scm.
  5008. </p>
  5009. </div>
  5010. </details>
  5011. <details id="circle">
  5012. <summary class="indented">circular lists</summary>
  5013. <div class="indented">
  5014. <p>s7 handles circular lists and vectors and dotted lists with its customary aplomb.
  5015. You can pass them to memq, or print them, for example; you can even evaluate them.
  5016. The print syntax is borrowed from CL:
  5017. </p>
  5018. <pre class="indented">
  5019. &gt; (let ((lst (list 1 2 3)))
  5020. (set! (cdr (cdr (cdr lst))) lst)
  5021. lst)
  5022. <em class="gray">#1=(1 2 3 . #1#)</em>
  5023. &gt; (let* ((x (cons 1 2))
  5024. (y (cons 3 x)))
  5025. (list x y))
  5026. <em class="gray">(#1=(1 . 2) (3 . #1#))</em>
  5027. </pre>
  5028. <p id="circularlistreader">
  5029. But should this syntax be readable as well? I'm inclined to say no because
  5030. then it is part of the language, and it doesn't look like the rest of the language.
  5031. (I think it's kind of ugly). Perhaps we could implement it via *#readers*:
  5032. </p>
  5033. <pre>
  5034. (define circular-list-reader
  5035. (let ((known-vals #f)
  5036. (top-n -1))
  5037. (lambda (str)
  5038. (define (replace-syms lst)
  5039. ;; walk through the new list, replacing our special keywords
  5040. ;; with the associated locations
  5041. (define (replace-sym tree getter)
  5042. (if (keyword? (getter tree))
  5043. (let ((n (string-&gt;number (symbol-&gt;string (keyword-&gt;symbol (getter tree))))))
  5044. (if (integer? n)
  5045. (let ((lst (assoc n known-vals)))
  5046. (if lst
  5047. (set! (getter tree) (cdr lst))
  5048. (format *stderr* "#~D# is not defined~%" n)))))))
  5049. (let walk-tree ((tree (cdr lst)))
  5050. (if (pair? tree)
  5051. (begin
  5052. (if (pair? (car tree)) (walk-tree (car tree)) (replace-sym tree car))
  5053. (if (pair? (cdr tree)) (walk-tree (cdr tree)) (replace-sym tree cdr))))
  5054. tree))
  5055. ;; str is whatever followed the #, first char is a digit
  5056. (let* ((len (length str))
  5057. (last-char (str (- len 1))))
  5058. (and (memv last-char '(#\= #\#)) ; is it #n= or #n#?
  5059. (let ((n (string-&gt;number (substring str 0 (- len 1)))))
  5060. (and (integer? n)
  5061. (begin
  5062. (if (not known-vals) ; save n so we know when we're done
  5063. (begin
  5064. (set! known-vals ())
  5065. (set! top-n n)))
  5066. (if (char=? last-char #\=) ; #n=
  5067. (and (eqv? (peek-char) #\() ; eqv? since peek-char can return #&lt;eof&gt;
  5068. (let ((cur-val (assoc n known-vals)))
  5069. ;; associate the number and the list it points to
  5070. ;; if cur-val, perhaps complain? (#n# redefined)
  5071. (let ((lst (catch #t
  5072. read
  5073. (lambda args ; a read error
  5074. (set! known-vals #f) ; so clear our state
  5075. (apply throw args))))) ; and pass the error on up
  5076. (if cur-val
  5077. (set! (cdr cur-val) lst)
  5078. (set! known-vals
  5079. (cons (set! cur-val (cons n lst)) known-vals))))
  5080. (if (= n top-n) ; replace our special keywords
  5081. (let ((result (replace-syms cur-val)))
  5082. (set! known-vals #f) ; '#1=(#+gsl #1#) -&gt; '(:1)!
  5083. result)
  5084. (cdr cur-val))))
  5085. ; #n=&lt;not a list&gt;?
  5086. ;; else it's #n# &mdash; set a marker for now since we may not
  5087. ;; have its associated value yet. We use a symbol name that
  5088. ;; string-&gt;number accepts.
  5089. (symbol-&gt;keyword
  5090. (symbol (number-&gt;string n) (string #\null) " "))))))
  5091. ; #n&lt;not an integer&gt;?
  5092. ))))) ; #n&lt;something else&gt;?
  5093. (do ((i 0 (+ i 1)))
  5094. ((= i 10))
  5095. ;; load up all the #n cases
  5096. (set! *#readers*
  5097. (cons (cons (integer-&gt;char (+ i (char-&gt;integer #\0))) circular-list-reader)
  5098. *#readers*)))
  5099. <!-- ) -->
  5100. &gt; '#1=(1 2 . #1#)
  5101. <em class="gray">#1=(1 2 . #1#)</em>
  5102. &gt; '#1=(1 #2=(2 . #2#) . #1#)
  5103. <em class="gray">#2=(1 #1=(2 . #1#) . #2#)</em>
  5104. </pre>
  5105. <p>And of course, we can treat these as labels:
  5106. </p>
  5107. <pre class="indented">
  5108. (let ((ctr 0)) #1=(begin (format () "~D " ctr) (set! ctr (+ ctr 1)) (if (&lt; ctr 4) #1# (newline))))
  5109. </pre>
  5110. <p>which prints "0 1 2 3" and a newline.
  5111. </p>
  5112. <br>
  5113. <p>Length returns +inf.0 if passed a circular list, and returns a negative
  5114. number if passed a dotted list. In the dotted case, the absolute value of the length is the list length not counting
  5115. the final cdr. <code>(define (circular? lst) (infinite? (length lst)))</code>.
  5116. </p>
  5117. <p>
  5118. <em class=def id="cyclicsequences">cyclic-sequences</em> returns a list of the cyclic
  5119. sequences in its argument, or nil.
  5120. <code>(define (cyclic? obj) (pair? (cyclic-sequences obj)))</code>.
  5121. </p>
  5122. <p>Here's an amusing use of circular lists:
  5123. </p>
  5124. <pre class="indented">
  5125. (define (for-each-permutation func vals)
  5126. ;; apply func to every permutation of vals:
  5127. ;; (for-each-permutation (lambda args (format () "~{~A~^ ~}~%" args)) '(1 2 3))
  5128. (define (pinner cur nvals len)
  5129. (if (= len 1)
  5130. (apply func (car nvals) cur)
  5131. (do ((i 0 (+ i 1))) ; I suppose a named let would be more Schemish
  5132. ((= i len))
  5133. (let ((start nvals))
  5134. (set! nvals (cdr nvals))
  5135. (let ((cur1 (cons (car nvals) cur))) ; add (car nvals) to our arg list
  5136. (set! (cdr start) (cdr nvals)) ; splice out that element and
  5137. (pinner cur1 (cdr start) (- len 1)) ; pass a smaller circle on down, "wheels within wheels"
  5138. (set! (cdr start) nvals)))))) ; restore original circle
  5139. (let ((len (length vals)))
  5140. (set-cdr! (list-tail vals (- len 1)) vals) ; make vals into a circle
  5141. (pinner () vals len)
  5142. (set-cdr! (list-tail vals (- len 1)) ()))) ; restore its original shape
  5143. </pre>
  5144. </div>
  5145. </details>
  5146. <details>
  5147. <summary class="indented">unprintable symbols</summary>
  5148. <div class="indented">
  5149. <p>s7 and Snd use "*" in a variable name, *features* for example, to indicate
  5150. that the variable is predefined. It may occur unprotected in a macro, for
  5151. example. The "*" doesn't mean that the variable is special in the CL sense of dynamic scope,
  5152. but some clear marker is needed for a global variable so that the programmer
  5153. doesn't accidentally step on it.
  5154. </p>
  5155. <p>Although a variable name's first character is more restricted, currently
  5156. only #\null, #\newline, #\tab, #\space, #\), #\(, #\", and #\; can't
  5157. occur within the name. I did not originally include double-quote in this set, so wild stuff like
  5158. <code>(let ((nam""e 1)) nam""e)</code>
  5159. would work, but that means that <code>'(1 ."hi")</code> is parsed as a 1 and the
  5160. symbol <code>."hi"</code>, and <code>(string-set! x"hi")</code> is an error.
  5161. The first character should not be #\#, #\', #\`, #\,, #\:, or any of those mentioned above,
  5162. and some characters can't occur by themselves. For example, "." is not a legal variable
  5163. name, but ".." is.
  5164. These weird symbols have to be printed sometimes:
  5165. </p>
  5166. <pre class="indented">
  5167. &gt; (list 1 (string-&gt;symbol (string #\; #\" #\\)) 2)
  5168. <em class="gray">(1 ;"\ 2)</em> <!-- " -->
  5169. &gt; (list 1 (string-&gt;symbol (string #\.)) 2)
  5170. <em class="gray">(1 . 2)</em>
  5171. </pre>
  5172. <p>which is a mess. Guile prints the first as <code>(1 #{\;\"\\}# 2)</code>.
  5173. In CL and some Schemes:
  5174. </p>
  5175. <pre class="indented">
  5176. [1]&gt; (list 1 (intern (coerce (list #\; #\" #\\) 'string)) 2) ; thanks to Rob Warnock
  5177. <em class="gray">(1 |;"\\| 2)</em> <!-- " -->
  5178. [2]&gt; (equalp 'A '|A|) ; in CL case matters here
  5179. <em class="gray">T</em>
  5180. </pre>
  5181. <p>This is clean, and has the weight of tradition behind it, but
  5182. I think I'll use "symbol" instead:
  5183. </p>
  5184. <pre class="indented">
  5185. &gt; (list 1 (string-&gt;symbol (string #\; #\" #\\)) 2)
  5186. <em class="gray">(1 (symbol ";\"\\") 2)</em> <!-- " -->
  5187. </pre>
  5188. <p>
  5189. This output is readable, and does not eat up perfectly good
  5190. characters like vertical bar, but it means we can't easily use
  5191. variable names like "| e t c |". We could allow a name to
  5192. contain any characters if it starts and ends with "|",
  5193. but then one vertical bar is trouble. (The symbol function
  5194. actually accepts any number of string arguments which it concatenates
  5195. to form the new symbol name).
  5196. </p>
  5197. <p>
  5198. These symbols are not just an optimization of string comparison:
  5199. </p>
  5200. <pre class="indented">
  5201. &gt; (define-macro (hi a)
  5202. (let ((funny-name (string-&gt;symbol ";")))
  5203. `(let ((,funny-name ,a)) (+ 1 ,funny-name))))
  5204. <em class="gray">hi</em>
  5205. &gt; (hi 2)
  5206. <em class="gray">3</em>
  5207. &gt; (macroexpand (hi 2))
  5208. <em class="gray">(let ((; 2)) (+ 1 ;))</em> ; for a good time, try (string #\")
  5209. &gt; (define-macro (hi a)
  5210. (let ((funny-name (string-&gt;symbol "| e t c |")))
  5211. `(let ((,funny-name ,a)) (+ 1 ,funny-name))))
  5212. <em class="gray">hi</em>
  5213. &gt; (hi 2)
  5214. <em class="gray">3</em>
  5215. &gt; (macroexpand (hi 2))
  5216. <em class="gray">(let ((| e t c | 2)) (+ 1 | e t c |))</em>
  5217. &gt; (let ((funny-name (string-&gt;symbol "| e t c |"))) ; now use it as a keyword arg to a function
  5218. (apply define* `((func (,funny-name 32)) (+ ,funny-name 1)))
  5219. ;; (procedure-source func) is (lambda* ((| e t c | 32)) (+ | e t c | 1))
  5220. (apply func (list (symbol-&gt;keyword funny-name) 2)))
  5221. <em class="gray">3</em>
  5222. </pre>
  5223. <p>I hope that makes you as happy as it makes me!
  5224. </p>
  5225. </div>
  5226. </details>
  5227. <div class="indented">
  5228. <p id="legolambda">The built-in syntactic forms, such as "begin", are almost first-class citizens.
  5229. </p>
  5230. <pre class="indented">
  5231. &gt; (let ((progn begin))
  5232. (progn
  5233. (define x 1)
  5234. (set! x 3)
  5235. (+ x 4)))
  5236. <em class="gray">7</em>
  5237. &gt; (let ((function lambda))
  5238. ((function (a b) (list a b)) 3 4))
  5239. <em class="gray">(3 4)</em>
  5240. &gt; (apply begin '((define x 3) (+ x 2)))
  5241. <em class="gray">5</em>
  5242. &gt; ((lambda (n) (apply n '(((x 1)) (+ x 2)))) let)
  5243. <em class="gray">3</em>
  5244. (define-macro (symbol-set! var val) ; like CL's set
  5245. `(apply set! ,var ',val ())) ; trailing nil is just to make apply happy &mdash; apply*?
  5246. (define-macro (progv vars vals . body)
  5247. `(apply (apply lambda ,vars ',body) ,vals))
  5248. &gt; (let ((s '(one two)) (v '(1 2))) (progv s v (+ one two)))
  5249. <em class="gray">3</em>
  5250. </pre>
  5251. <p>We can snap together program fragments ("look Ma, no macros!"):
  5252. </p>
  5253. <pre class="indented">
  5254. (let* ((x 3)
  5255. (arg '(x))
  5256. (body `((+ ,x x 1))))
  5257. ((apply lambda arg body) 12)) ; "legolambda"?
  5258. (define (engulph form)
  5259. (let ((body `(let ((L ()))
  5260. (do ((i 0 (+ i 1)))
  5261. ((= i 10) (reverse L))
  5262. (set! L (cons ,form L))))))
  5263. (define function (apply lambda () (list (copy body :readable))))
  5264. (function)))
  5265. (let ()
  5266. (define (hi a) (+ a x))
  5267. ((apply let '((x 32)) (list (procedure-source hi))) 12)) ; one function, many closures?
  5268. (let ((ctr -1)) ; (enum zero one two) but without using a macro
  5269. (apply begin
  5270. (map (lambda (symbol)
  5271. (set! ctr (+ ctr 1))
  5272. (list 'define symbol ctr)) ; e.g. '(define zero 0)
  5273. '(zero one two)))
  5274. (+ zero one two))
  5275. </pre>
  5276. <p>But there's a prettier way to implement enum ("transparent-for-each"):
  5277. </p>
  5278. <pre class="indented">
  5279. &gt; (define-macro (enum . args)
  5280. `(for-each define ',args (iota (length ',args))))
  5281. <em class="gray">enum</em>
  5282. &gt; (enum a b c)
  5283. <em class="gray">#&lt;unspecified&gt;</em>
  5284. &gt; b
  5285. <em class="gray">1</em>
  5286. </pre>
  5287. <p><code>(apply define ...)</code> is similar to CL's set.
  5288. </p>
  5289. <pre class="indented">
  5290. &gt; ((apply define-macro '((m a) `(+ 1 ,a))) 3)
  5291. <em class="gray">4</em>
  5292. &gt; ((apply define '((hi a) (+ a 1))) 3)
  5293. <em class="gray">4</em>
  5294. </pre>
  5295. <p>This gives us a way to make anonymous macros, just as lambda returns an anonymous function:
  5296. </p>
  5297. <pre class="indented">
  5298. &gt; (define-macro (mu args . body)
  5299. `(apply define-macro '((,(gensym) ,@args) ,@body)))
  5300. <em class="gray">mu</em>
  5301. &gt; ((mu (a) `(+ 1 ,a)) 3)
  5302. <em class="gray">4</em>
  5303. &gt; (define-macro (glambda args) ; returns an anonymous macro that will return a function given a body
  5304. `(define-macro (,(gensym) . body)
  5305. `(lambda ,',args ,@body)))
  5306. <em class="gray">glambda</em>
  5307. &gt; (let ((gf (glambda (a b)))) ; gf is now ready for any body that involves arguments 'a and 'b
  5308. ((gf (+ a b)) 1 2)) ; apply (lambda (a b) (+ a b)) to '(1 2)
  5309. <em class="gray">3</em>
  5310. </pre>
  5311. <p>catch, dynamic-wind, and many of the other functions that take function
  5312. arguments in standard Scheme, accept macros in s7.
  5313. </p>
  5314. <p>Apply let is very similar to eval:
  5315. </p>
  5316. <pre>
  5317. &gt; (apply let '((a 2) (b 3)) '((+ a b)))
  5318. <em class="gray">5</em>
  5319. &gt; (eval '(+ a b) (inlet 'a 2 'b 3))
  5320. <em class="gray">5</em>
  5321. &gt; ((apply lambda '(a b) '((+ a b))) 2 3)
  5322. <em class="gray">5</em>
  5323. &gt; (apply let '((a 2) (b 3)) '((list + a b))) ; a -&gt; 2, b -&gt; 3
  5324. <em class="gray">(+ 2 3)</em>
  5325. </pre>
  5326. <p>The redundant-looking double lists are for apply's benefit. We could
  5327. use a trailing null instead (mimicking apply* in some ancient lisps):
  5328. </p>
  5329. <pre>
  5330. &gt; (apply let '((a 2) (b 3)) '(list + a b) ())
  5331. <em class="gray">(+ 2 3)</em>
  5332. </pre>
  5333. <p>
  5334. Currently, you can't set! a built-in syntactic keyword to some new value:
  5335. <code>(set! if 3)</code>.
  5336. I hope this kind of thing is not actually very useful, but let me
  5337. know if you need it. The issue is purely one of speed.
  5338. </p>
  5339. <p>Speaking of speed... It is widely believed
  5340. that a Scheme with first class everything can't hope to compete with any
  5341. "real" Scheme. Humph I say. Take this little example (which is not
  5342. so misleading that I feel guilty about it):
  5343. </p>
  5344. <pre class="indented">
  5345. (define (do-loop n)
  5346. (do ((i 0 (+ i 1)))
  5347. ((= i n))
  5348. (if (zero? (modulo i 1000))
  5349. (display ".")))
  5350. (newline))
  5351. (for-each
  5352. (lambda (n) (do-loop n))
  5353. (list 1000 1000000 10000000))
  5354. </pre>
  5355. <p>In s7, that takes 0.24 seconds on my home machine. In tinyScheme, from
  5356. whence we sprang, it takes 85 seconds. In the chicken interpreter, 5.3
  5357. seconds, and after compilation (using -O2) of the chicken compiler output,
  5358. 0.75 seconds. So, s7 is comparable to chicken in speed, even though chicken
  5359. is compiling to C. I think Guile 2.0.9 takes about 1 second.
  5360. The equivalent in CL:
  5361. clisp interpreted 9.3 seconds, compiled 0.85 seconds; sbcl 0.21 seconds.
  5362. </p>
  5363. </div>
  5364. <div class="indented">
  5365. <p>In s7, there is only one kind of begin statement,
  5366. and it can contain both definitions and expressions. These are evaluated in the order
  5367. in which they occur, and in the environment at the point of the evaluation. I think
  5368. of it as being a little REPL. begin does not introduce a new frame in
  5369. the current environment, so defines happen in the enclosing environment.
  5370. </p>
  5371. </div>
  5372. <div class="indented">
  5373. <p id="r7rs">The r7rs compatibility code is in r7rs.scm. I used to include it here, but
  5374. as r7rs grew, this section got too large. In general, all the conversion routines in
  5375. r7rs are handled in s7 via generic functions, records are classes, byte-vectors are
  5376. strings, and so on.
  5377. </p>
  5378. </div>
  5379. <details>
  5380. <summary class="indented">threads</summary>
  5381. <div class="indented">
  5382. <p>s7 originally had multithreading support, but I removed it in August, 2011.
  5383. It turned out to be less useful than I hoped,
  5384. mainly because s7 threads shared the heap and therefore had to coordinate
  5385. all cell allocations. It was faster and simpler to use multiple
  5386. processes each running a separate s7 interpreter, rather than one s7
  5387. running multiple s7 threads. In CLM, there was also contention for access
  5388. to the output stream. In GUI-related situations,
  5389. threads were not useful mainly because the GUI toolkits are not thread safe.
  5390. Last but not least, the effort to make the non-threaded
  5391. s7 faster messed up parts of the threaded version. Rather than
  5392. waste a lot of time fixing this, I chose to flush multithreading.
  5393. Here's a very simple example of using an s7 interpreter per thread:
  5394. </p>
  5395. <pre class="indented">
  5396. #include &lt;stdlib.h&gt;
  5397. #include &lt;stdio.h&gt;
  5398. #include &lt;string.h&gt;
  5399. #include &lt;pthread.h&gt;
  5400. #include "s7.h"
  5401. typedef struct {
  5402. s7_scheme *sc;
  5403. s7_pointer func;
  5404. pthread_t *thread;
  5405. } thred;
  5406. static void *run_thread(void *obj)
  5407. {
  5408. thred *f = (thred *)obj;
  5409. return((void *)s7_call(f-&gt;sc, f-&gt;func, s7_nil(f-&gt;sc)));
  5410. }
  5411. static thred *make_thread(s7_function func)
  5412. {
  5413. thred *f;
  5414. f = (thred *)malloc(sizeof(thred));
  5415. f-&gt;sc = s7_init();
  5416. f-&gt;func = s7_make_function(f-&gt;sc, "a-test", func, 0, 0, false, "a test");
  5417. f-&gt;thread = (pthread_t *)malloc(sizeof(pthread_t));
  5418. pthread_create(f-&gt;thread, NULL, run_thread, (void *)f);
  5419. return(f);
  5420. }
  5421. static s7_pointer a_test(s7_scheme *sc, s7_pointer args)
  5422. {
  5423. fprintf(stderr, "I am %p\n", sc);
  5424. /* do something time-consuming... */
  5425. return(args);
  5426. }
  5427. int main(int argc, char **argv)
  5428. {
  5429. thred *f1, *f2;
  5430. f1 = make_thread(a_test);
  5431. f2 = make_thread(a_test);
  5432. pthread_join(*(f1-&gt;thread), NULL);
  5433. pthread_join(*(f2-&gt;thread), NULL);
  5434. }
  5435. /* build s7 with -DWITH_THREADS, then
  5436. * gcc -o repl repl.c s7.o -g3 -Wl,-export-dynamic -lpthread -lm -I. -ldl
  5437. */
  5438. </pre>
  5439. <p>Unfortunately, there's no way yet to
  5440. free all the resources s7_init allocates (the heap, stack, etc).
  5441. </p>
  5442. </div>
  5443. </details>
  5444. <div class="indented">
  5445. <p>"Life", a poem.
  5446. </p>
  5447. <pre class="indented">
  5448. (+(*(+))(*)(+(+)(+)(*)))
  5449. (((((lambda () (lambda () (lambda () (lambda () 1))))))))
  5450. (+ (((lambda () values)) 1 2 3))
  5451. (map apply (list map) (list map) (list (list *)) '((((1 2)) ((3 4 5)))))
  5452. (do ((do do do)) (do do do))
  5453. (*(*)(*) (+)(+) 1)
  5454. </pre>
  5455. </div>
  5456. </blockquote>
  5457. <br><br>
  5458. <div class="topheader" id="FFIexamples">FFI examples</div>
  5459. <p>s7 exists only to serve as an extension of some other application, so
  5460. it is primarily a foreign function interface. s7.h has lots of comments about the individual
  5461. functions. Here I'll collect some complete examples. s7.c depends on the following
  5462. compile-time flags:
  5463. </p>
  5464. <pre class="indented">
  5465. SIZEOF_VOID_P 8 (default) or 4.
  5466. WITH_GMP 1 if you want multiprecision arithmetic (requires gmp, mpfr, and mpc, default is 0)
  5467. HAVE_COMPLEX_NUMBERS 1 if your compiler supports complex numbers
  5468. HAVE_COMPLEX_TRIG 1 if your math library has complex versions of the trig functions
  5469. DISABLE_DEPRECATED 1 if you want to make sure you're not using any deprecated s7 stuff (default is 0)
  5470. WITH_IMMUTATBLE_UNQUOTE 1 if you want "unquote" omitted (default is 0)
  5471. WITH_EXTRA_EXPONENT_MARKERS 1 if you want "d", "f", "l", and "s" in addition to "e" as exponent markers (default is 0)
  5472. if someone defends these exponent markers, ask him to read 1l11+11l1i
  5473. (in 2 million lines of open-source Scheme, there is not one use of these silly things)
  5474. WITH_SYSTEM_EXTRAS 1 if you want some additional OS-related functions built-in (default is 0)
  5475. WITH_MAIN 1 if you want s7.c to include a main program section that runs a REPL.
  5476. WITH_C_LOADER 1 if you want to be able to load shared object files with load.
  5477. </pre>
  5478. <p>See the comment at the start of s7.c for more information about these switches.
  5479. s7.h defines the two main number types: s7_int and s7_double.
  5480. The examples that follow show:
  5481. </p>
  5482. <ul>
  5483. <li><a href="#repl">read-eval-print loop (and emacs)</a>
  5484. <li><a href="#defun">define a function with arguments and a returned value, and define a variable </a>
  5485. <li><a href="#defvar">call a Scheme function from C, and get/set Scheme variable values in C</a>
  5486. <li><a href="#juce">C++ and Juce</a>
  5487. <li><a href="#sndlib">load sndlib using the Xen functions and macros</a>
  5488. <li><a href="#pwstype">add a new Scheme type and a procedure with a setter</a>
  5489. <li><a href="#functionportexample">redirect display output to a C procedure</a>
  5490. <li><a href="#extendop">extend a built-in operator ("+" in this case)</a>
  5491. <li><a href="#definestar1">C-side define* (s7_define_function_star)</a>
  5492. <li><a href="#definemacro1">C-side define-macro (s7_define_macro)</a>
  5493. <li><a href="#definegeneric">define a generic function in C</a>
  5494. <li><a href="#signal">signal handling (C-C to break out of an infinite loop)</a>
  5495. <li><a href="#vector">direct multidimensional vector element access</a>
  5496. <li><a href="#notify">notification in C that a Scheme variable has been set!</a>
  5497. <li><a href="#namespace">Load C defined stuff into a separate namespace</a>
  5498. <li><a href="#Cerrors">Error handling in C</a>
  5499. <li><a href="#testhook">Hooks in C and Scheme</a>
  5500. <li><a href="#dload">Load a C module dynamically</a>
  5501. <li><a href="#gmpex">gmp and friends</a>
  5502. <li><a href="#glistener">glistener.c</a>
  5503. <li><a href="#gdb">gdb</a>
  5504. </ul>
  5505. <div class="header" id="repl"><h4>A simple listener</h4></div>
  5506. <div class="indented">
  5507. <pre>
  5508. #include &lt;stdlib.h&gt;
  5509. #include &lt;stdio.h&gt;
  5510. #include &lt;string.h&gt;
  5511. #include "s7.h"
  5512. int main(int argc, char **argv)
  5513. {
  5514. s7_scheme *s7;
  5515. char buffer[512];
  5516. char response[1024];
  5517. s7 = <em class=red>s7_init</em>(); /* initialize the interpreter */
  5518. while (1) /* fire up a read-eval-print loop */
  5519. {
  5520. fprintf(stdout, "\n&gt; "); /* prompt for input */
  5521. fgets(buffer, 512, stdin);
  5522. if ((buffer[0] != '\n') ||
  5523. (strlen(buffer) &gt; 1))
  5524. { /* evaluate the input and print the result */
  5525. sprintf(response, "(write %s)", buffer);
  5526. <em class=red>s7_eval_c_string</em>(s7, response);
  5527. }
  5528. }
  5529. }
  5530. /* make mus-config.h (it can be empty), then
  5531. *
  5532. * gcc -c s7.c -I.
  5533. * gcc -o repl repl.c s7.o -lm -I. -ldl
  5534. *
  5535. * run it:
  5536. *
  5537. * repl
  5538. * &gt; (+ 1 2)
  5539. * <em class="gray">3</em>
  5540. * &gt; (define (add1 x) (+ 1 x))
  5541. * <em class="gray">add1</em>
  5542. * &gt; (add1 2)
  5543. * <em class="gray">3</em>
  5544. * &gt; (exit)
  5545. *
  5546. * for long-term happiness in linux use:
  5547. * gcc -o repl repl.c s7.o -Wl,-export-dynamic -lm -I. -ldl
  5548. * freebsd:
  5549. * gcc -o repl repl.c s7.o -Wl,-export-dynamic -lm -I.
  5550. * osx:
  5551. * gcc -o repl repl.c s7.o -lm -I.
  5552. * openbsd:
  5553. * gcc -o repl repl.c s7.o -I. -ftrampolines -Wl,-export-dynamic -lm
  5554. */
  5555. </pre>
  5556. </div>
  5557. <p>Since this reads stdin and writes stdout, it can be run as a Scheme subjob of emacs.
  5558. One (inconvenient) way to do this is to set the emacs variable scheme-program-name to
  5559. the name of the exectuable created above ("doc7"), then call the emacs function run-scheme:
  5560. M-x eval-expression in emacs, followed by (setq scheme-program-name "doc7"), then
  5561. M-x run-scheme, and you're talking to s7 in emacs. Of course, this connection can be
  5562. customized indefinitely. See, for example, inf-snd.el in the Snd package.
  5563. </p>
  5564. <p>Here are the not-always-built-in indentations I use in emacs:
  5565. </p>
  5566. <pre class="indented">
  5567. (put 'with-let 'scheme-indent-function 1)
  5568. (put 'with-baffle 'scheme-indent-function 0)
  5569. (put 'with-sound 'scheme-indent-function 1)
  5570. (put 'catch 'scheme-indent-function 1)
  5571. (put 'lambda* 'scheme-indent-function 1)
  5572. (put 'when 'scheme-indent-function 1)
  5573. (put 'let-temporarily 'scheme-indent-function 1)
  5574. (put 'let*-temporarily 'scheme-indent-function 1)
  5575. (put 'call-with-input-string 'scheme-indent-function 1)
  5576. (put 'unless 'scheme-indent-function 1)
  5577. (put 'letrec* 'scheme-indent-function 1)
  5578. (put 'sublet 'scheme-indent-function 1)
  5579. (put 'varlet 'scheme-indent-function 1)
  5580. </pre>
  5581. <p>To read stdin while working in a GUI-based program is trickier. In glib/gtk, you can use
  5582. something like this:
  5583. </p>
  5584. <blockquote>
  5585. <div class="indented">
  5586. <pre>
  5587. static gboolean read_stdin(GIOChannel *source, GIOCondition condition, gpointer data)
  5588. {
  5589. /* here read from g_io_channel_unix_get_fd(source) and call s7_eval_string */
  5590. return(true);
  5591. }
  5592. /* ... during initialization ... */
  5593. GIOChannel *channel;
  5594. channel = g_io_channel_unix_new(STDIN_FILENO); /* watch stdin */
  5595. stdin_id = g_io_add_watch_full(channel, /* and call read_stdin above if input is noticed */
  5596. G_PRIORITY_DEFAULT,
  5597. (GIOCondition)(G_IO_IN | G_IO_HUP | G_IO_ERR),
  5598. <em class=red>read_stdin</em>, NULL, NULL);
  5599. g_io_channel_unref(channel);
  5600. </pre></div>
  5601. </blockquote>
  5602. <details>
  5603. <summary class="indented">repl with libtecla</summary>
  5604. <p>Here's a version that uses libtecla for the line editor:
  5605. </p>
  5606. <blockquote>
  5607. <div class="indented">
  5608. <pre>
  5609. #include &lt;stdlib.h&gt;
  5610. #include &lt;stdio.h&gt;
  5611. #include &lt;string.h&gt;
  5612. #include &lt;libtecla.h&gt;
  5613. #include "s7.h"
  5614. int main(int argc, char **argv)
  5615. {
  5616. s7_scheme *s7;
  5617. char *buffer;
  5618. char response[1024];
  5619. GetLine *gl; /* The tecla line editor */
  5620. gl = new_GetLine(500, 5000);
  5621. s7 = s7_init();
  5622. while (1)
  5623. {
  5624. buffer = gl_get_line(gl, "&gt; ", NULL, 0);
  5625. if ((buffer[0] != '\n') ||
  5626. (strlen(buffer) &gt; 1))
  5627. {
  5628. sprintf(response, "(write %s)", buffer);
  5629. s7_eval_c_string(s7, response);
  5630. fprintf(stdout, "\n");
  5631. }
  5632. }
  5633. gl = del_GetLine(gl);
  5634. }
  5635. /*
  5636. * gcc -c s7.c -I. -O2 -g3
  5637. * gcc -o ex1 ex1.c s7.o -lm -I. -ltecla -ldl
  5638. */
  5639. </pre></div>
  5640. </blockquote>
  5641. </details>
  5642. <p>A repl (based on repl.scm) is built into s7. Include the compiler flag -DWITH_MAIN:
  5643. </p>
  5644. <pre class="indented">
  5645. in Linux: gcc s7.c -o repl -DWITH_MAIN -I. -O2 -g -ldl -lm -Wl,-export-dynamic
  5646. in *BSD: gcc s7.c -o repl -DWITH_MAIN -I. -O2 -g -lm -Wl,-export-dynamic
  5647. in OSX: gcc s7.c -o repl -DWITH_MAIN -I. -O2 -g -lm
  5648. </pre>
  5649. <details>
  5650. <summary class="indented">repl in C++</summary>
  5651. <p>If you prefer C++, here's a C++ version of the listener, extracted from Rick Taube's
  5652. Common Music package:
  5653. </p>
  5654. <blockquote>
  5655. <div class="indented">
  5656. <pre>
  5657. #include &lt;iostream&gt;
  5658. #include "s7.h"
  5659. static s7_pointer main_quit(s7_scheme *sc, s7_pointer args);
  5660. static bool is_balanced(std::string str);
  5661. static bool is_not_white(std::string str);
  5662. int main(int argc, const char* argv[])
  5663. {
  5664. s7_scheme* s7 = s7_init();
  5665. s7_pointer val;
  5666. std::string str;
  5667. try
  5668. {
  5669. while (std::cin)
  5670. {
  5671. std::cout &lt;&lt; "\ns7&gt; ";
  5672. str = "";
  5673. while (true)
  5674. {
  5675. std::string lin;
  5676. std::getline(std::cin, lin);
  5677. str = str + lin + "\n";
  5678. if (is_balanced(str))
  5679. break;
  5680. }
  5681. if (is_not_white(str))
  5682. {
  5683. val = s7_eval_c_string(s7, str.c_str());
  5684. std::cout &lt;&lt; s7_object_to_c_string(s7, val);
  5685. }
  5686. }
  5687. }
  5688. catch(...)
  5689. {
  5690. }
  5691. std::cout &lt;&lt; "Bye!\n";
  5692. return 0;
  5693. }
  5694. static s7_pointer main_quit(s7_scheme *sc, s7_pointer args)
  5695. {
  5696. throw 0;
  5697. return(s7_nil(sc));
  5698. }
  5699. static bool is_balanced(std::string str)
  5700. {
  5701. int parens = 0;
  5702. int quotes = 0;
  5703. unsigned i = 0;
  5704. while (i &lt; str.size())
  5705. {
  5706. if (str[i] == ';')
  5707. {
  5708. for (i = i + 1; i &lt; str.size(); i++)
  5709. {
  5710. if (str[i] == '\n')
  5711. break;
  5712. }
  5713. }
  5714. else if (str[i] == '"')
  5715. {
  5716. if (i == 0 || str[i - 1] != '\\')
  5717. {
  5718. quotes = 1;
  5719. for (i = i + 1; i &lt; str.size(); i++)
  5720. {
  5721. if (str[i] == '"' &amp;&amp; str[i - 1] != '\\')
  5722. {
  5723. quotes = 0;
  5724. break;
  5725. }
  5726. }
  5727. if (quotes)
  5728. return false;
  5729. }
  5730. }
  5731. else if (str[i] == '(')
  5732. parens++;
  5733. else if (str[i] == ')')
  5734. parens--;
  5735. i++;
  5736. }
  5737. return (parens == 0) &amp;&amp; (quotes == 0);
  5738. }
  5739. static bool is_not_white(std::string str)
  5740. {
  5741. for (unsigned i = 0; (i &lt; str.size() &amp;&amp; str[i] != ';'); i++)
  5742. if (str[i] != ' ' && str[i] != '\n' &amp;&amp; str[i] != '\t')
  5743. return true;
  5744. return false;
  5745. }
  5746. /* g++ -I. -c repl.cpp
  5747. * g++ -o repl repl.o s7.o -ldl
  5748. */
  5749. </pre></div>
  5750. </blockquote>
  5751. </details>
  5752. <p id="beginhook">
  5753. Common Lisp has something called "evalhook" that makes it possible
  5754. to insert your own function into the eval loop. In s7, we have a "begin_hook" which sits at the opening of many begin blocks
  5755. (implicit or explicit). begin_hook is a (C) function;
  5756. if it sets its bool argument to true,
  5757. s7 interrupts the current evaluation.
  5758. Here is a version of the REPL in which begin_hook watches for C-g to interrupt
  5759. some long computation:
  5760. </p>
  5761. <blockquote>
  5762. <div class="indented">
  5763. <pre>
  5764. /* terminal-based REPL,
  5765. * an expansion of the <a href="#repl">read-eval-print loop</a> program above.
  5766. * type C-g to interrupt an evaluation.
  5767. */
  5768. #include &lt;stdlib.h&gt;
  5769. #include &lt;stdio.h&gt;
  5770. #include &lt;string.h&gt;
  5771. #include &lt;termios.h&gt;
  5772. #include &lt;signal.h&gt;
  5773. #include "s7.h"
  5774. static struct termios save_buf, buf;
  5775. static void sigcatch(int n)
  5776. {
  5777. /* put things back the way they were */
  5778. tcsetattr(fileno(stdin), TCSAFLUSH, &amp;save_buf);
  5779. exit(0);
  5780. }
  5781. static char buffer[512];
  5782. static int type_ahead_point = 0;
  5783. static void <em class=red>watch_for_c_g</em>(s7_scheme *sc, bool *all_done)
  5784. {
  5785. char c;
  5786. /* watch for C-g without blocking, save other chars as type-ahead */
  5787. tcsetattr(fileno(stdin), TCSAFLUSH, &amp;buf);
  5788. if (read(fileno(stdin), &amp;c, 1) == 1)
  5789. {
  5790. if (c == 7) /* C-g */
  5791. {
  5792. *all_done = true;
  5793. type_ahead_point = 0;
  5794. }
  5795. else buffer[type_ahead_point++] = c;
  5796. }
  5797. tcsetattr(fileno(stdin), TCSAFLUSH, &amp;save_buf);
  5798. }
  5799. int main(int argc, char **argv)
  5800. {
  5801. s7_scheme *s7;
  5802. bool use_begin_hook;
  5803. use_begin_hook = (tcgetattr(fileno(stdin), &amp;save_buf) &gt;= 0);
  5804. if (use_begin_hook)
  5805. {
  5806. buf = save_buf;
  5807. buf.c_lflag &amp;= ~ICANON;
  5808. buf.c_cc[VMIN] = 0;
  5809. buf.c_cc[VTIME] = 0;
  5810. signal(SIGINT, sigcatch);
  5811. signal(SIGQUIT, sigcatch);
  5812. signal(SIGTERM, sigcatch);
  5813. }
  5814. s7 = s7_init();
  5815. if (argc == 2)
  5816. {
  5817. fprintf(stderr, "load %s\n", argv[1]);
  5818. s7_load(s7, argv[1]);
  5819. }
  5820. else
  5821. {
  5822. char response[1024];
  5823. while (1)
  5824. {
  5825. fprintf(stdout, "\n&gt; ");
  5826. fgets((char *)(buffer + type_ahead_point), 512 - type_ahead_point, stdin);
  5827. type_ahead_point = 0;
  5828. if ((buffer[0] != '\n') ||
  5829. (strlen(buffer) &gt; 1))
  5830. {
  5831. sprintf(response, "(write %s)", buffer);
  5832. if (use_begin_hook)
  5833. <em class=red>s7_set_begin_hook</em>(s7, watch_for_c_g);
  5834. s7_eval_c_string(s7, response);
  5835. if (use_begin_hook)
  5836. <em class=red>s7_set_begin_hook</em>(s7, NULL);
  5837. }
  5838. }
  5839. }
  5840. if (use_begin_hook)
  5841. tcsetattr(fileno(stdin), TCSAFLUSH, &amp;save_buf);
  5842. }
  5843. </pre></div>
  5844. </blockquote>
  5845. <div class="header" id="defun"><h4>Define a function with arguments and a returned value, and a variable</h4></div>
  5846. <div class="indented">
  5847. <pre>
  5848. #include &lt;stdlib.h&gt;
  5849. #include &lt;stdio.h&gt;
  5850. #include &lt;string.h&gt;
  5851. #include "s7.h"
  5852. static s7_pointer add1(s7_scheme *sc, s7_pointer args)
  5853. {
  5854. /* all added functions have this form, args is a list,
  5855. * s7_car(args) is the first arg, etc
  5856. */
  5857. if (<em class=red>s7_is_integer</em>(s7_car(args)))
  5858. return(<em class=red>s7_make_integer</em>(sc, 1 + <em class=red>s7_integer</em>(s7_car(args))));
  5859. return(s7_wrong_type_arg_error(sc, "add1", 1, s7_car(args), "an integer"));
  5860. }
  5861. int main(int argc, char **argv)
  5862. {
  5863. s7_scheme *s7;
  5864. char buffer[512];
  5865. char response[1024];
  5866. s7 = s7_init();
  5867. s7_define_function(s7, "add1", add1, 1, 0, false, "(add1 int) adds 1 to int");
  5868. /* add the function "add1" to the interpreter.
  5869. * 1, 0, false -&gt; one required arg,
  5870. * no optional args,
  5871. * no "rest" arg
  5872. */
  5873. <em class=red>s7_define_variable</em>(s7, "my-pi", <em class=red>s7_make_real</em>(s7, 3.14159265));
  5874. while (1) /* fire up a "repl" */
  5875. {
  5876. fprintf(stdout, "\n&gt; "); /* prompt for input */
  5877. fgets(buffer, 512, stdin);
  5878. if ((buffer[0] != '\n') ||
  5879. (strlen(buffer) &gt; 1))
  5880. {
  5881. sprintf(response, "(write %s)", buffer);
  5882. s7_eval_c_string(s7, response); /* evaluate input and write the result */
  5883. }
  5884. }
  5885. }
  5886. /* doc7
  5887. * &gt; my-pi
  5888. * <em class="gray">3.14159265</em>
  5889. * &gt; (+ 1 (add1 1))
  5890. * <em class="gray">3</em>
  5891. * &gt; (exit)
  5892. */
  5893. </pre></div>
  5894. <div class="header" id="defvar"><h4>Call a Scheme-defined function from C, and get/set Scheme variable values in C</h4></div>
  5895. <div class="indented">
  5896. <pre>
  5897. #include &lt;stdlib.h&gt;
  5898. #include &lt;stdio.h&gt;
  5899. #include &lt;string.h&gt;
  5900. #include "s7.h"
  5901. int main(int argc, char **argv)
  5902. {
  5903. s7_scheme *s7;
  5904. s7 = s7_init();
  5905. s7_define_variable(s7, "an-integer", s7_make_integer(s7, 1));
  5906. s7_eval_c_string(s7, "(define (add1 a) (+ a 1))");
  5907. fprintf(stderr, "an-integer: %lld\n",
  5908. s7_integer(<em class=red>s7_name_to_value</em>(s7, "an-integer")));
  5909. <em class=red>s7_symbol_set_value</em>(s7, <em class=red>s7_make_symbol</em>(s7, "an-integer"), s7_make_integer(s7, 32));
  5910. fprintf(stderr, "now an-integer: %lld\n",
  5911. s7_integer(<em class=red>s7_name_to_value</em>(s7, "an-integer")));
  5912. fprintf(stderr, "(add1 2): %lld\n",
  5913. s7_integer(<em class=red>s7_call</em>(s7,
  5914. s7_name_to_value(s7, "add1"),
  5915. s7_cons(s7, s7_make_integer(s7, 2), s7_nil(s7)))));
  5916. }
  5917. /*
  5918. * doc7
  5919. * an-integer: 1
  5920. * now an-integer: 32
  5921. * (add1 2): 3
  5922. */
  5923. </pre></div>
  5924. <div class="header" id="juce"><h4>C++ and Juce, from Rick Taube</h4></div>
  5925. <div class="indented">
  5926. <pre>
  5927. int main(int argc, const char* argv[])
  5928. {
  5929. initialiseJuce_NonGUI();
  5930. s7_scheme *s7 = s7_init();
  5931. if (!s7)
  5932. {
  5933. std::cout &lt;&lt; "Can't start S7!\n";
  5934. return -1;
  5935. }
  5936. s7_pointer val;
  5937. std::string str;
  5938. while (true)
  5939. {
  5940. std::cout &lt;&lt; "\ns7&gt; ";
  5941. std::getline(std::cin, str);
  5942. val = s7_eval_c_string(s7, str.c_str());
  5943. std::cout &lt;&lt; s7_object_to_c_string(s7, val);
  5944. }
  5945. free(s7);
  5946. std::cout &lt;&lt; "Bye!\n";
  5947. return 0;
  5948. }
  5949. </pre></div>
  5950. <div class="header" id="sndlib"><h4>Load sndlib into an s7 repl</h4></div>
  5951. <div class="indented">
  5952. <pre>
  5953. #include &lt;stdlib.h&gt;
  5954. #include &lt;stdio.h&gt;
  5955. #include &lt;string.h&gt;
  5956. #include &lt;unistd.h&gt;
  5957. /* assume we've configured and built sndlib, so it has created a mus-config.h file.
  5958. * also assume we've built s7 with WITH_SYSTEM_EXTRAS set, so we have file-exists? and delete-file
  5959. */
  5960. #include "mus-config.h"
  5961. #include "s7.h"
  5962. #include "xen.h"
  5963. #include "clm.h"
  5964. #include "clm2xen.h"
  5965. /* we need to redirect clm's mus_error calls to s7_error */
  5966. static void mus_error_to_s7(int type, char *msg)
  5967. {
  5968. s7_error(s7, /* s7 is declared in xen.h, defined in xen.c */
  5969. s7_make_symbol(s7, "mus-error"),
  5970. s7_cons(s7, s7_make_string(s7, msg), s7_nil(s7)));
  5971. }
  5972. int main(int argc, char **argv)
  5973. {
  5974. char buffer[512];
  5975. char response[1024];
  5976. s7 = s7_init(); /* initialize the interpreter */
  5977. s7_xen_initialize(s7); /* initialize the xen stuff (hooks and the xen s7 FFI used by sndlib) */
  5978. Init_sndlib(); /* initialize sndlib with all the functions linked into s7 */
  5979. mus_error_set_handler(mus_error_to_s7); /* catch low-level errors and pass them to s7-error */
  5980. while (1) /* fire up a "repl" */
  5981. {
  5982. fprintf(stdout, "\n&gt; "); /* prompt for input */
  5983. fgets(buffer, 512, stdin);
  5984. if ((buffer[0] != '\n') ||
  5985. (strlen(buffer) &gt; 1))
  5986. {
  5987. sprintf(response, "(write %s)", buffer);
  5988. s7_eval_c_string(s7, response); /* evaluate input and write the result */
  5989. }
  5990. }
  5991. }
  5992. /* gcc -o doc7 doc7.c -lm -I. /usr/local/lib/libsndlib.a -lasound -ldl
  5993. *
  5994. * (load "sndlib-ws.scm")
  5995. * (with-sound () (outa 10 .1))
  5996. * (load "v.scm")
  5997. * (with-sound () (fm-violin 0 .1 440 .1))
  5998. *
  5999. * you might also need -lgsl -lgslcblas -lfftw3
  6000. */
  6001. </pre>
  6002. </div>
  6003. <p>If you built libsndlib.so, it is possible to use it directly in the s7 repl:
  6004. </p>
  6005. <pre>
  6006. repl ; this is a bare s7 running repl.scm via -DWITH_MAIN=1
  6007. loading libc_s7.so
  6008. &gt; (load "/home/bil/test/sndlib/libsndlib.so" (inlet 'init_func 's7_init_sndlib))
  6009. #t ; s7_init_sndlib ties all the sndlib functions and variables into s7
  6010. &gt; (load "sndlib-ws.scm")
  6011. tmpnam
  6012. &gt; (set! *clm-player* (lambda (file) (system (format #f "sndplay ~A" file))))
  6013. &gt; (load "v.scm")
  6014. fm-violin
  6015. &gt; (with-sound (:play #t) (fm-violin 0 1 440 .1))
  6016. "test.snd"
  6017. </pre>
  6018. <p>You can use autoload to load libsndlib when needed:
  6019. </p>
  6020. <pre class="indented">
  6021. (define (find-library name)
  6022. (if (or (file-exists? name)
  6023. (char=? (name 0) #\/))
  6024. name
  6025. (call-with-exit
  6026. (lambda (return)
  6027. (for-each
  6028. (lambda (path)
  6029. (let ((new-name (string-append path "/" name)))
  6030. (if (file-exists? new-name)
  6031. (return new-name))))
  6032. *load-path*)
  6033. (let ((libs (getenv "LD_LIBRARY_PATH")) ; colon separated directory names
  6034. (start 0))
  6035. (do ((colon (char-position #\: libs) (char-position #\: libs start)))
  6036. ((or (not colon)
  6037. (let ((new-name (string-append (substring libs start colon) "/" name)))
  6038. (and (file-exists? new-name)
  6039. (return new-name)))))
  6040. (set! start (+ colon 1))))
  6041. name))))
  6042. (<em class=red>autoload</em> 'clm
  6043. (lambda (e)
  6044. (load (find-library "libsndlib.so") (inlet '(init_func . s7_init_sndlib)))
  6045. (set! *features* (cons 'clm *features*))
  6046. (with-let (rootlet) (define clm #t))
  6047. (load "sndlib-ws.scm")
  6048. (set! *clm-player* (lambda (file) (system (format #f "sndplay ~A" file))))))
  6049. </pre>
  6050. <p>and use the repl's vt100 stuff to (for example) post the current begin time
  6051. as a note list computes:
  6052. </p>
  6053. <pre class="indented">
  6054. (define (clm-notehook . args)
  6055. ;; assume second arg is begin time (first is instrument name)
  6056. (when (and (pair? args)
  6057. (pair? (cdr args))
  6058. (number? (cadr args)))
  6059. (with-let (sublet (*repl* 'repl-let) :begin-time (cadr args))
  6060. (let ((coords (cursor-coords))
  6061. (col (floor (/ last-col 2))))
  6062. (let ((str (number-&gt;string begin-time)))
  6063. (format *stderr* "~C[~D;~DH" #\escape prompt-row col)
  6064. (format *stderr* "~C[K~A" #\escape (if (&gt; (length str) col) (substring str 0 (- col 1)) str)))
  6065. (format *stderr* "~C[~D;~DH" #\escape (cdr coords) (car coords))))))
  6066. (set! *clm-notehook* clm-notehook)
  6067. </pre>
  6068. <div class="header" id="pwstype"><h4>Add a new Scheme type and a procedure with a setter</h4></div>
  6069. <div class="indented">
  6070. <pre>
  6071. #include &lt;stdlib.h&gt;
  6072. #include &lt;stdio.h&gt;
  6073. #include &lt;string.h&gt;
  6074. #include "s7.h"
  6075. /* define *listener-prompt* in scheme, add two accessors for C get/set */
  6076. static const char *listener_prompt(s7_scheme *sc)
  6077. {
  6078. return(s7_string(s7_name_to_value(sc, "*listener-prompt*")));
  6079. }
  6080. static void set_listener_prompt(s7_scheme *sc, const char *new_prompt)
  6081. {
  6082. s7_symbol_set_value(sc, s7_make_symbol(sc, "*listener-prompt*"), s7_make_string(sc, new_prompt));
  6083. }
  6084. /* now add a new type, a struct named "dax" with two fields, a real "x" and a list "data" */
  6085. /* since the data field is an s7 object, we'll need to mark it to protect it from the GC */
  6086. typedef struct {
  6087. s7_double x;
  6088. s7_pointer data;
  6089. } dax;
  6090. static char *print_dax(s7_scheme *sc, void *val)
  6091. {
  6092. char *data_str, *str;
  6093. int data_str_len;
  6094. dax *o = (dax *)val;
  6095. data_str = s7_object_to_c_string(sc, o-&gt;data);
  6096. data_str_len = strlen(data_str);
  6097. str = (char *)calloc(data_str_len + 32, sizeof(char));
  6098. snprintf(str, data_str_len + 32, "#&lt;dax %.3f %s&gt;", o-&gt;x, data_str);
  6099. free(data_str);
  6100. return(str);
  6101. }
  6102. static void free_dax(void *val)
  6103. {
  6104. if (val) free(val);
  6105. }
  6106. static bool equal_dax(void *val1, void *val2)
  6107. {
  6108. return(val1 == val2);
  6109. }
  6110. static void mark_dax(void *val)
  6111. {
  6112. dax *o = (dax *)val;
  6113. if (o) s7_mark_object(o-&gt;data);
  6114. }
  6115. static int dax_type_tag = 0;
  6116. static s7_pointer make_dax(s7_scheme *sc, s7_pointer args)
  6117. {
  6118. dax *o;
  6119. o = (dax *)malloc(sizeof(dax));
  6120. o-&gt;x = s7_real(s7_car(args));
  6121. if (s7_cdr(args) != s7_nil(sc))
  6122. o-&gt;data = s7_cadr(args);
  6123. else o-&gt;data = s7_nil(sc);
  6124. return(<em class=red>s7_make_object</em>(sc, dax_type_tag, (void *)o));
  6125. }
  6126. static s7_pointer is_dax(s7_scheme *sc, s7_pointer args)
  6127. {
  6128. return(s7_make_boolean(sc,
  6129. <em class=red>s7_is_object</em>(s7_car(args)) &amp;&amp;
  6130. <em class=red>s7_object_type</em>(s7_car(args)) == dax_type_tag));
  6131. }
  6132. static s7_pointer dax_x(s7_scheme *sc, s7_pointer args)
  6133. {
  6134. dax *o;
  6135. o = (dax *)<em class=red>s7_object_value</em>(s7_car(args));
  6136. return(s7_make_real(sc, o-&gt;x));
  6137. }
  6138. static s7_pointer set_dax_x(s7_scheme *sc, s7_pointer args)
  6139. {
  6140. dax *o;
  6141. o = (dax *)s7_object_value(s7_car(args));
  6142. o-&gt;x = s7_real(s7_cadr(args));
  6143. return(s7_cadr(args));
  6144. }
  6145. static s7_pointer dax_data(s7_scheme *sc, s7_pointer args)
  6146. {
  6147. dax *o;
  6148. o = (dax *)s7_object_value(s7_car(args));
  6149. return(o-&gt;data);
  6150. }
  6151. static s7_pointer set_dax_data(s7_scheme *sc, s7_pointer args)
  6152. {
  6153. dax *o;
  6154. o = (dax *)s7_object_value(s7_car(args));
  6155. o-&gt;data = s7_cadr(args);
  6156. return(o-&gt;data);
  6157. }
  6158. int main(int argc, char **argv)
  6159. {
  6160. s7_scheme *s7;
  6161. char buffer[512];
  6162. char response[1024];
  6163. s7 = s7_init();
  6164. s7_define_variable(s7, "*listener-prompt*", s7_make_string(s7, "&gt;"));
  6165. dax_type_tag = <em class=red>s7_new_type</em>("dax", print_dax, free_dax, equal_dax, mark_dax, NULL, NULL);
  6166. s7_define_function(s7, "make-dax", make_dax, 2, 0, false, "(make-dax x data) makes a new dax");
  6167. s7_define_function(s7, "dax?", is_dax, 1, 0, false, "(dax? anything) returns #t if its argument is a dax object");
  6168. s7_define_variable(s7, "dax-x",
  6169. <em class=red>s7_dilambda</em>(s7, "dax-x", dax_x, 1, 0, set_dax_x, 2, 0, "dax x field"));
  6170. s7_define_variable(s7, "dax-data",
  6171. <em class=red>s7_dilambda</em>(s7, "dax-data", dax_data, 1, 0, set_dax_data, 2, 0, "dax data field"));
  6172. while (1)
  6173. {
  6174. fprintf(stdout, "\n%s ", listener_prompt(s7));
  6175. fgets(buffer, 512, stdin);
  6176. if ((buffer[0] != '\n') ||
  6177. (strlen(buffer) &gt; 1))
  6178. {
  6179. sprintf(response, "(write %s)", buffer);
  6180. s7_eval_c_string(s7, response); /* evaluate input and write the result */
  6181. }
  6182. }
  6183. }
  6184. /*
  6185. * &gt; *listener-prompt*
  6186. * <em class="gray">"&gt;"</em>
  6187. * &gt; (set! *listener-prompt* ":")
  6188. * <em class="gray">":"</em>
  6189. * : (define obj (make-dax 1.0 (list 1 2 3)))
  6190. * <em class="gray">obj</em>
  6191. * : obj
  6192. * <em class="gray">#&lt;dax 1.000 (1 2 3)&gt;</em>
  6193. * : (dax-x obj)
  6194. * <em class="gray">1.0</em>
  6195. * : (dax-data obj)
  6196. * <em class="gray">(1 2 3)</em>
  6197. * : (set! (dax-x obj) 123.0)
  6198. * <em class="gray">123.0</em>
  6199. * : obj
  6200. * <em class="gray">#&lt;dax 123.000 (1 2 3)&gt;</em>
  6201. * : (dax? obj)
  6202. * <em class="gray">#t</em>
  6203. * : (exit)
  6204. */
  6205. </pre></div>
  6206. <div class="header" id="functionportexample"><h4>Redirect output (and input) to a C procedure</h4></div>
  6207. <div class="indented">
  6208. <pre>
  6209. #include &lt;stdlib.h&gt;
  6210. #include &lt;stdio.h&gt;
  6211. #include &lt;string.h&gt;
  6212. #include "s7.h"
  6213. static void my_print(s7_scheme *sc, unsigned char c, s7_pointer port)
  6214. {
  6215. fprintf(stderr, "[%c] ", c);
  6216. }
  6217. static s7_pointer my_read(s7_scheme *sc, s7_read_t peek, s7_pointer port)
  6218. {
  6219. return(<em class=red>s7_make_character</em>(sc, fgetc(stdin)));
  6220. }
  6221. int main(int argc, char **argv)
  6222. {
  6223. s7_scheme *s7;
  6224. char buffer[512];
  6225. char response[1024];
  6226. s7 = s7_init();
  6227. <em class=red>s7_set_current_output_port</em>(s7, <em class=red>s7_open_output_function</em>(s7, my_print));
  6228. s7_define_variable(s7, "io-port", <em class=red>s7_open_input_function</em>(s7, my_read));
  6229. while (1)
  6230. {
  6231. fprintf(stdout, "\n&gt; ");
  6232. fgets(buffer, 512, stdin);
  6233. if ((buffer[0] != '\n') ||
  6234. (strlen(buffer) &gt; 1))
  6235. {
  6236. sprintf(response, "(write %s)", buffer);
  6237. s7_eval_c_string(s7, response);
  6238. }
  6239. }
  6240. }
  6241. /*
  6242. * &gt; (+ 1 2)
  6243. * <em class="gray">[3]</em>
  6244. * &gt; (display "hiho")
  6245. * <em class="gray">[h] [i] [h] [o] [#] [&lt;] [u] [n] [s] [p] [e] [c] [i] [f] [i] [e] [d] [&gt;] </em>
  6246. * &gt; (define (add1 x) (+ 1 x))
  6247. * <em class="gray">[a] [d] [d] [1] </em>
  6248. * &gt; (add1 123)
  6249. * <em class="gray">[1] [2] [4] </em>
  6250. * &gt; (read-char io-port)
  6251. * a ; here I typed "a" in the shell
  6252. * <em class="gray">[#] [\] [a] </em>
  6253. */
  6254. </pre></div>
  6255. <div class="header" id="extendop"><h4>Extend a built-in operator ("+" in this case)</h4></div>
  6256. <p>There are several ways to do this. In the first example, we save the original function,
  6257. and replace it with ours, calling the original whenever possible:
  6258. </p>
  6259. <div class="indented">
  6260. <pre>
  6261. #include &lt;stdlib.h&gt;
  6262. #include &lt;stdio.h&gt;
  6263. #include &lt;string.h&gt;
  6264. #include "s7.h"
  6265. static s7_pointer old_add; /* the original "+" function for non-string cases */
  6266. static s7_pointer old_string_append; /* same, for "string-append" */
  6267. static s7_pointer our_add(s7_scheme *sc, s7_pointer args)
  6268. {
  6269. /* this will replace the built-in "+" operator, extending it to include strings:
  6270. * (+ "hi" "ho") -&gt; "hiho" and (+ 3 4) -&gt; 7
  6271. */
  6272. if ((s7_is_pair(args)) &amp;&amp;
  6273. (s7_is_string(s7_car(args))))
  6274. return(<em class=red>s7_apply_function</em>(sc, old_string_append, args));
  6275. return(s7_apply_function(sc, old_add, args));
  6276. }
  6277. int main(int argc, char **argv)
  6278. {
  6279. s7_scheme *s7;
  6280. char buffer[512];
  6281. char response[1024];
  6282. s7 = s7_init();
  6283. /* get built-in + and string-append */
  6284. old_add = s7_name_to_value(s7, "+");
  6285. old_string_append = s7_name_to_value(s7, "string-append");
  6286. /* redefine "+" */
  6287. s7_define_function(s7, "+", our_add, 0, 0, true, "(+ ...) adds or appends its arguments");
  6288. while (1)
  6289. {
  6290. fprintf(stdout, "\n&gt; ");
  6291. fgets(buffer, 512, stdin);
  6292. if ((buffer[0] != '\n') ||
  6293. (strlen(buffer) &gt; 1))
  6294. {
  6295. sprintf(response, "(write %s)", buffer);
  6296. s7_eval_c_string(s7, response);
  6297. }
  6298. }
  6299. }
  6300. /* &gt; (+ 1 2)
  6301. * <em class="gray">3</em>
  6302. * &gt; (+ "hi" "ho")
  6303. * <em class="gray">"hiho"</em>
  6304. */
  6305. </pre></div>
  6306. <p>In the next example, we use the method (inlet) machinery:
  6307. </p>
  6308. <div class="indented">
  6309. <pre>
  6310. #include &lt;stdlib.h&gt;
  6311. #include &lt;stdio.h&gt;
  6312. #include &lt;string.h&gt;
  6313. #include &lt;math.h&gt;
  6314. #include "s7.h"
  6315. static s7_pointer our_abs(s7_scheme *sc, s7_pointer args)
  6316. {
  6317. s7_pointer x;
  6318. x = s7_car(args);
  6319. if (!s7_is_number(x))
  6320. {
  6321. s7_pointer method;
  6322. method = <em class=red>s7_method</em>(sc, x, s7_make_symbol(sc, "abs"));
  6323. if (method == s7_undefined(sc)) /* no method found, so raise an error */
  6324. s7_wrong_type_arg_error(sc, "abs", 1, x, "a real");
  6325. return(s7_apply_function(sc, method, args)); /* else apply the method to the args */
  6326. }
  6327. return(s7_make_real(sc, (s7_double)fabs(s7_number_to_real(sc, x))));
  6328. }
  6329. int main(int argc, char **argv)
  6330. {
  6331. s7_scheme *s7;
  6332. char buffer[512];
  6333. char response[1024];
  6334. s7 = s7_init();
  6335. s7_define_function(s7, "our-abs", our_abs, 1, 0, false, "abs replacement");
  6336. while (1)
  6337. {
  6338. fprintf(stdout, "\n&gt; ");
  6339. fgets(buffer, 512, stdin);
  6340. if ((buffer[0] != '\n') ||
  6341. (strlen(buffer) &gt; 1))
  6342. {
  6343. sprintf(response, "(write %s)", buffer);
  6344. s7_eval_c_string(s7, response);
  6345. }
  6346. }
  6347. }
  6348. /* &gt; (our-abs -1)
  6349. * <em class="gray">1.0</em>
  6350. * &gt; (our-abs (openlet (inlet 'value -3.0 'abs (lambda (x) (abs (x 'value))))))
  6351. * <em class="gray">3.0</em>
  6352. */
  6353. </pre>
  6354. </div>
  6355. <div class="header" id="definestar1"><h4>C-side define* (s7_define_function_star)</h4></div>
  6356. <div class="indented">
  6357. <pre>
  6358. #include &lt;stdlib.h&gt;
  6359. #include &lt;stdio.h&gt;
  6360. #include &lt;string.h&gt;
  6361. #include "s7.h"
  6362. static s7_pointer plus(s7_scheme *sc, s7_pointer args)
  6363. {
  6364. /* (define* (plus (red 32) blue) (+ (* 2 red) blue)) */
  6365. return(s7_make_integer(sc, 2 * s7_integer(s7_car(args)) + s7_integer(s7_cadr(args))));
  6366. }
  6367. int main(int argc, char **argv)
  6368. {
  6369. s7_scheme *s7;
  6370. char buffer[512];
  6371. char response[1024];
  6372. s7 = s7_init();
  6373. <em class=red>s7_define_function_star</em>(s7, "plus", plus, "(red 32) blue", "an example of define* from C");
  6374. while (1)
  6375. {
  6376. fprintf(stdout, "\n&gt; ");
  6377. fgets(buffer, 512, stdin);
  6378. if ((buffer[0] != '\n') ||
  6379. (strlen(buffer) &gt; 1))
  6380. {
  6381. sprintf(response, "(write %s)", buffer);
  6382. s7_eval_c_string(s7, response);
  6383. }
  6384. }
  6385. }
  6386. /*
  6387. * &gt; (plus 2 3)
  6388. * <em class="gray">7</em>
  6389. * &gt; (plus :blue 3)
  6390. * <em class="gray">67</em>
  6391. * &gt; (plus :blue 1 :red 4)
  6392. * <em class="gray">9</em>
  6393. * &gt; (plus 2 :blue 3)
  6394. * <em class="gray">7</em>
  6395. * &gt; (plus :blue 3 :red 1)
  6396. * <em class="gray">5</em>
  6397. */
  6398. </pre></div>
  6399. <div class="header" id="definemacro1"><h4>C-side define-macro (s7_define_macro)</h4></div>
  6400. <div class="indented">
  6401. <pre>
  6402. #include &lt;stdlib.h&gt;
  6403. #include &lt;stdio.h&gt;
  6404. #include &lt;string.h&gt;
  6405. #include "s7.h"
  6406. static s7_pointer plus(s7_scheme *sc, s7_pointer args)
  6407. {
  6408. /* (define-macro (plus a b) `(+ ,a ,b)) */
  6409. s7_pointer a, b;
  6410. a = s7_car(args);
  6411. b = s7_cadr(args);
  6412. return(s7_list(sc, 3, s7_make_symbol(sc, "+"), a, b));
  6413. }
  6414. int main(int argc, char **argv)
  6415. {
  6416. s7_scheme *s7;
  6417. char buffer[512];
  6418. char response[1024];
  6419. s7 = s7_init();
  6420. <em class=red>s7_define_macro</em>(s7, "plus", plus, 2, 0, false, "plus adds its two arguments");
  6421. while (1)
  6422. {
  6423. fprintf(stdout, "\n&gt; ");
  6424. fgets(buffer, 512, stdin);
  6425. if ((buffer[0] != '\n') ||
  6426. (strlen(buffer) &gt; 1))
  6427. {
  6428. sprintf(response, "(write %s)", buffer);
  6429. s7_eval_c_string(s7, response);
  6430. }
  6431. }
  6432. }
  6433. /*
  6434. * &gt; (plus 2 3)
  6435. * <em class="gray">5</em>
  6436. */
  6437. </pre></div>
  6438. <div class="header" id="definegeneric"><h4>define a generic function in C</h4></div>
  6439. <p>In scheme, a function becomes generic simply by <code>(apply ((car args) 'func) args)</code>.
  6440. To accomplish the same thing in C, we use s7_method and s7_apply_function:
  6441. </p>
  6442. <div class="indented">
  6443. <pre>
  6444. #include &lt;stdlib.h&gt;
  6445. #include &lt;stdio.h&gt;
  6446. #include &lt;string.h&gt;
  6447. #include "s7.h"
  6448. static s7_pointer plus(s7_scheme *sc, s7_pointer args)
  6449. {
  6450. #define plus_help "(plus obj ...) applies obj's plus method to obj and any trailing arguments."
  6451. s7_pointer obj, method;
  6452. obj = s7_car(args);
  6453. method = <em class=red>s7_method</em>(sc, obj, s7_make_symbol(sc, "plus"));
  6454. if (s7_is_procedure(method))
  6455. return(<em class=red>s7_apply_function</em>(sc, method, args));
  6456. return(s7_f(sc));
  6457. }
  6458. int main(int argc, char **argv)
  6459. {
  6460. s7_scheme *s7;
  6461. s7 = s7_init();
  6462. s7_define_function(s7, "plus", plus, 1, 0, true, plus_help);
  6463. while (1)
  6464. {
  6465. char buffer[512];
  6466. char response[1024];
  6467. fprintf(stdout, "\n&gt; ");
  6468. fgets(buffer, 512, stdin);
  6469. if ((buffer[0] != '\n') ||
  6470. (strlen(buffer) &gt; 1))
  6471. {
  6472. sprintf(response, "(write %s)", buffer);
  6473. s7_eval_c_string(s7, response);
  6474. }
  6475. }
  6476. }
  6477. /* gcc -c s7.c -I.
  6478. * gcc -o ex15 ex15.c s7.o -I. -lm -ldl
  6479. *
  6480. * &gt; (plus 1 2)
  6481. * <em class="gray">#f</em>
  6482. * &gt; (define obj (openlet (inlet 'plus (lambda args (apply + 1 (cdr args))))))
  6483. * <em class="gray">obj</em>
  6484. * &gt; (plus obj 2 3)
  6485. * <em class="gray">6</em>
  6486. */
  6487. </pre>
  6488. </div>
  6489. <div class="header" id="signal"><h4>Signal handling and continuations</h4></div>
  6490. <div class="indented">
  6491. <pre>
  6492. #include &lt;stdlib.h&gt;
  6493. #include &lt;stdio.h&gt;
  6494. #include &lt;string.h&gt;
  6495. #include &lt;signal.h&gt;
  6496. #include "s7.h"
  6497. static s7_scheme *s7;
  6498. struct sigaction new_act, old_act;
  6499. static void handle_sigint(int ignored)
  6500. {
  6501. fprintf(stderr, "interrupted!\n");
  6502. s7_symbol_set_value(s7, s7_make_symbol(s7, "*interrupt*"), <em class=red>s7_make_continuation</em>(s7)); /* save where we were interrupted */
  6503. sigaction(SIGINT, &amp;new_act, NULL);
  6504. s7_quit(s7); /* get out of the eval loop if possible */
  6505. }
  6506. static s7_pointer our_sleep(s7_scheme *sc, s7_pointer args)
  6507. {
  6508. /* slow down our infinite loop for demo purposes */
  6509. sleep(1);
  6510. return(s7_f(sc));
  6511. }
  6512. int main(int argc, char **argv)
  6513. {
  6514. char buffer[512];
  6515. char response[1024];
  6516. s7 = s7_init();
  6517. s7_define_function(s7, "sleep", our_sleep, 0, 0, false, "(sleep) sleeps");
  6518. s7_define_variable(s7, "*interrupt*", s7_f(s7));
  6519. /* Scheme variable *interrupt* holds the continuation at the point of the interrupt */
  6520. sigaction(SIGINT, NULL, &amp;old_act);
  6521. if (old_act.sa_handler != SIG_IGN)
  6522. {
  6523. memset(&amp;new_act, 0, sizeof(new_act));
  6524. new_act.sa_handler = &amp;handle_sigint;
  6525. sigaction(SIGINT, &amp;new_act, NULL);
  6526. }
  6527. while (1)
  6528. {
  6529. fprintf(stderr, "\n&gt; ");
  6530. fgets(buffer, 512, stdin);
  6531. if ((buffer[0] != '\n') ||
  6532. (strlen(buffer) &gt; 1))
  6533. {
  6534. sprintf(response, "(write %s)", buffer);
  6535. s7_eval_c_string(s7, response);
  6536. }
  6537. }
  6538. }
  6539. /*
  6540. * &gt; (do ((i 0 (+ i 1))) ((= i -1)) (format () "~D " i) (sleep))
  6541. * ;;; now type C-C to break out of this loop
  6542. * 0 1 2 ^Cinterrupted!
  6543. * ;;; call the continuation to continue from where we were interrupted
  6544. * &gt; (*interrupt*)
  6545. * 3 4 5 ^Cinterrupted!
  6546. * &gt; *interrupt*
  6547. * #&lt;continuation&gt;
  6548. * &gt; (+ 1 2)
  6549. * 3
  6550. */
  6551. </pre></div>
  6552. <div class="header" id="vector"><h4>Multidimensional vector element access</h4></div>
  6553. <div class="indented">
  6554. <pre>
  6555. #include &lt;stdlib.h&gt;
  6556. #include &lt;stdio.h&gt;
  6557. #include &lt;string.h&gt;
  6558. #include &lt;stdarg.h&gt;
  6559. #include "s7.h"
  6560. static s7_pointer multivector_ref(s7_scheme *sc, s7_pointer vector, int indices, ...)
  6561. {
  6562. /* multivector_ref returns an element of a multidimensional vector */
  6563. int ndims;
  6564. ndims = <em class=red>s7_vector_rank</em>(vector);
  6565. if (ndims == indices)
  6566. {
  6567. va_list ap;
  6568. s7_int index = 0;
  6569. va_start(ap, indices);
  6570. if (ndims == 1)
  6571. {
  6572. index = va_arg(ap, s7_int);
  6573. va_end(ap);
  6574. return(s7_vector_ref(sc, vector, index));
  6575. }
  6576. else
  6577. {
  6578. int i;
  6579. s7_pointer *elements;
  6580. s7_int *offsets, *dimensions;
  6581. elements = <em class=red>s7_vector_elements</em>(vector);
  6582. dimensions = <em class=red>s7_vector_dimensions</em>(vector);
  6583. offsets = <em class=red>s7_vector_offsets</em>(vector);
  6584. for (i = 0; i &lt; indices; i++)
  6585. {
  6586. int ind;
  6587. ind = va_arg(ap, int);
  6588. if ((ind &lt; 0) ||
  6589. (ind &gt;= dimensions[i]))
  6590. {
  6591. va_end(ap);
  6592. return(s7_out_of_range_error(sc,
  6593. "multivector_ref", i,
  6594. s7_make_integer(sc, ind),
  6595. "index should be between 0 and the dimension size"));
  6596. }
  6597. index += (ind * offsets[i]);
  6598. }
  6599. va_end(ap);
  6600. return(elements[index]);
  6601. }
  6602. }
  6603. return(s7_wrong_number_of_args_error(sc,
  6604. "multivector_ref: wrong number of indices: ~A",
  6605. s7_make_integer(sc, indices)));
  6606. }
  6607. int main(int argc, char **argv)
  6608. {
  6609. char buffer[512];
  6610. char response[1024];
  6611. s7_scheme *s7;
  6612. s7 = s7_init();
  6613. s7_eval_c_string(s7, "(define vect (make-vector '(2 3 4) 0))");
  6614. s7_eval_c_string(s7, "(set! (vect 1 1 1) 32)");
  6615. fprintf(stdout, "vect[0,0,0]: %s, vect[1,1,1]: %s\n",
  6616. s7_object_to_c_string(s7, <em class=red>multivector_ref</em>(s7, s7_name_to_value(s7, "vect"), 3, 0, 0, 0)),
  6617. s7_object_to_c_string(s7, <em class=red>multivector_ref</em>(s7, s7_name_to_value(s7, "vect"), 3, 1, 1, 1)));
  6618. }
  6619. /* vect[0,0,0]: 0, vect[1,1,1]: 32
  6620. */
  6621. </pre>
  6622. </div>
  6623. <p>Much later... I decided to add s7_vector_ref_n and s7_vector_set_n to s7.
  6624. </p>
  6625. <div class="header" id="notify"><h4>Notification from Scheme that a given Scheme variable has been set</h4></div>
  6626. <div class="indented">
  6627. <pre>
  6628. #include &lt;stdlib.h&gt;
  6629. #include &lt;stdio.h&gt;
  6630. #include &lt;string.h&gt;
  6631. #include "s7.h"
  6632. static s7_pointer scheme_set_notification(s7_scheme *sc, s7_pointer args)
  6633. {
  6634. /* this function is called when the Scheme variable is set! */
  6635. fprintf(stderr, "%s set to %s\n",
  6636. s7_object_to_c_string(sc, s7_car(args)),
  6637. s7_object_to_c_string(sc, s7_cadr(args)));
  6638. return(s7_cadr(args));
  6639. }
  6640. int main(int argc, char **argv)
  6641. {
  6642. s7_scheme *s7;
  6643. s7 = s7_init();
  6644. s7_define_function(s7, "notify-C", scheme_set_notification, 2, 0, false, "called if notified-var is set!");
  6645. s7_define_variable(s7, "notified-var", s7_make_integer(s7, 0));
  6646. <em class=red>s7_symbol_set_access</em>(s7, s7_make_symbol(s7, "notified-var"), s7_name_to_value(s7, "notify-C"));
  6647. if (argc == 2)
  6648. {
  6649. fprintf(stderr, "load %s\n", argv[1]);
  6650. s7_load(s7, argv[1]);
  6651. }
  6652. else
  6653. {
  6654. char buffer[512];
  6655. char response[1024];
  6656. while (1)
  6657. {
  6658. fprintf(stdout, "\n&gt; ");
  6659. fgets(buffer, 512, stdin);
  6660. if ((buffer[0] != '\n') ||
  6661. (strlen(buffer) &gt; 1))
  6662. {
  6663. sprintf(response, "(write %s)", buffer);
  6664. s7_eval_c_string(s7, response);
  6665. }
  6666. }
  6667. }
  6668. }
  6669. /* &gt; notified-var
  6670. * <em class="gray">0</em>
  6671. * &gt; (set! notified-var 32)
  6672. * <em class="gray">notified-var set to 32</em>
  6673. * <em class="gray">32</em>
  6674. */
  6675. </pre></div>
  6676. <div class="header" id="namespace"><h4>Load C defined stuff into a separate namespace</h4></div>
  6677. <div class="indented">
  6678. <pre>
  6679. #include &lt;stdlib.h&gt;
  6680. #include &lt;stdio.h&gt;
  6681. #include &lt;string.h&gt;
  6682. #include "s7.h"
  6683. static s7_pointer func1(s7_scheme *sc, s7_pointer args)
  6684. {
  6685. return(s7_make_integer(sc, s7_integer(s7_car(args)) + 1));
  6686. }
  6687. int main(int argc, char **argv)
  6688. {
  6689. s7_scheme *s7;
  6690. s7_pointer new_env;
  6691. s7 = s7_init();
  6692. /* "func1" and "var1" will be placed in an anonymous environment,
  6693. * accessible from Scheme via the global variable "lib-exports"
  6694. */
  6695. new_env = <em class=red>s7_inlet</em>(s7, s7_curlet(s7), s7_nil(s7));
  6696. /* make a private environment for func1 and var1 below (this is our "namespace") */
  6697. s7_gc_protect(s7, new_env);
  6698. s7_define(s7, <em class=red>new_env</em>,
  6699. s7_make_symbol(s7, "func1"),
  6700. <em class=red>s7_make_function</em>(s7, "func1", func1, 1, 0, false, "func1 adds 1 to its argument"));
  6701. s7_define(s7, <em class=red>new_env</em>, s7_make_symbol(s7, "var1"), s7_make_integer(s7, 32));
  6702. /* those two symbols are now defined in the new environment */
  6703. /* add "lib-exports" to the global environment */
  6704. s7_define_variable(s7, "lib-exports", <em class=red>s7_let_to_list</em>(s7, new_env));
  6705. if (argc == 2)
  6706. {
  6707. fprintf(stderr, "load %s\n", argv[1]);
  6708. s7_load(s7, argv[1]);
  6709. }
  6710. else
  6711. {
  6712. char buffer[512];
  6713. char response[1024];
  6714. while (1)
  6715. {
  6716. fprintf(stdout, "\n&gt; ");
  6717. fgets(buffer, 512, stdin);
  6718. if ((buffer[0] != '\n') ||
  6719. (strlen(buffer) &gt; 1))
  6720. {
  6721. sprintf(response, "(write %s)", buffer);
  6722. s7_eval_c_string(s7, response);
  6723. }
  6724. }
  6725. }
  6726. }
  6727. /* &gt; func1
  6728. * <em class="gray">;func1: unbound variable, line 1</em>
  6729. * &gt; lib-exports
  6730. * <em class="gray">((var1 . 32) (func1 . func1))</em>
  6731. * ;; so lib-exports has the C-defined names and values
  6732. * ;; we can use these directly:
  6733. *
  6734. * &gt; (define lib-env (apply <em class=red>sublet</em> (curlet) lib-exports))
  6735. * <em class="gray">lib-env</em>
  6736. * &gt; (<em class=red>with-let</em> lib-env (func1 var1))
  6737. * <em class="gray">33</em>
  6738. *
  6739. * ;; or rename them to prepend "lib:"
  6740. * &gt; (define lib-env (apply sublet
  6741. (curlet)
  6742. (map (lambda (binding)
  6743. (cons (string-&gt;symbol
  6744. (string-append "lib:" (symbol-&gt;string (car binding))))
  6745. (cdr binding)))
  6746. lib-exports)))
  6747. * <em class="gray">lib-env</em>
  6748. * &gt; (with-let lib-env (lib:func1 lib:var1))
  6749. * <em class="gray">33</em>
  6750. *
  6751. * ;;; now for convenience, place "func1" in the global environment under the name "func2"
  6752. * &gt; (define func2 (cdadr lib-exports))
  6753. * <em class="gray">func2</em>
  6754. * &gt; (func2 1)
  6755. * <em class="gray">2</em>
  6756. */
  6757. </pre></div>
  6758. <div class="header" id="Cerrors"><h4>Handle scheme errors in C</h4></div>
  6759. <div class="indented">
  6760. <pre>
  6761. #include &lt;stdlib.h&gt;
  6762. #include &lt;stdio.h&gt;
  6763. #include &lt;string.h&gt;
  6764. #include "s7.h"
  6765. static s7_pointer error_handler(s7_scheme *sc, s7_pointer args)
  6766. {
  6767. fprintf(stdout, "error: %s\n", s7_string(s7_car(args)));
  6768. return(s7_f(sc));
  6769. }
  6770. int main(int argc, char **argv)
  6771. {
  6772. s7_scheme *s7;
  6773. char buffer[512];
  6774. char response[1024];
  6775. bool with_error_hook = false;
  6776. s7 = s7_init();
  6777. s7_define_function(s7, "error-handler", error_handler, 1, 0, false, "our error handler");
  6778. if (with_error_hook)
  6779. s7_eval_c_string(s7, "(set! (hook-functions *error-hook*) \n\
  6780. (list (lambda (hook) \n\
  6781. (error-handler \n\
  6782. (apply format #f (hook 'data))) \n\
  6783. (set! (hook 'result) 'our-error))))");
  6784. while (1)
  6785. {
  6786. fprintf(stdout, "\n&gt; ");
  6787. fgets(buffer, 512, stdin);
  6788. if ((buffer[0] != '\n') ||
  6789. (strlen(buffer) &gt; 1))
  6790. {
  6791. s7_pointer old_port, result;
  6792. int gc_loc = -1;
  6793. const char *errmsg = NULL;
  6794. /* trap error messages */
  6795. old_port = s7_set_current_error_port(s7, s7_open_output_string(s7));
  6796. if (old_port != s7_nil(s7))
  6797. gc_loc = s7_gc_protect(s7, old_port);
  6798. /* evaluate the input string */
  6799. result = s7_eval_c_string(s7, buffer);
  6800. /* print out the value wrapped in "{}" so we can tell it from other IO paths */
  6801. fprintf(stdout, "{%s}", s7_object_to_c_string(s7, result));
  6802. /* look for error messages */
  6803. errmsg = s7_get_output_string(s7, s7_current_error_port(s7));
  6804. /* if we got something, wrap it in "[]" */
  6805. if ((errmsg) &amp;&amp; (*errmsg))
  6806. fprintf(stdout, "[%s]", errmsg);
  6807. s7_close_output_port(s7, s7_current_error_port(s7));
  6808. s7_set_current_error_port(s7, old_port);
  6809. if (gc_loc != -1)
  6810. s7_gc_unprotect_at(s7, gc_loc);
  6811. }
  6812. }
  6813. }
  6814. /*
  6815. * gcc -c s7.c -I. -g3
  6816. * gcc -o ex3 ex3.c s7.o -lm -I. -ldl
  6817. *
  6818. * if with_error_hook is false,
  6819. *
  6820. * &gt; (+ 1 2)
  6821. * <em class="gray">{3}</em>
  6822. * &gt; (+ 1 #\c)
  6823. * <em class="gray">{wrong-type-arg}[</em>
  6824. * <em class="gray">;+ argument 2, #\c, is character but should be a number, line 1</em>
  6825. * ]
  6826. *
  6827. * so s7 by default prepends ";" to the error message, and appends "\n",
  6828. * sending that to current-error-port, and the error type ('wrong-type-arg here)
  6829. * is returned.
  6830. *
  6831. * if with_error_hook is true,
  6832. *
  6833. * &gt; (+ 1 2)
  6834. * <em class="gray">{3}</em>
  6835. * &gt; (+ 1 #\c)
  6836. * <em class="gray">error: + argument 2, #\c, is character but should be a number</em>
  6837. * <em class="gray">{our-error}</em>
  6838. *
  6839. * so now the *error-hook* code handles both the error reporting and
  6840. * the value returned ('our-error in this case).
  6841. */
  6842. </pre></div>
  6843. <div class="header" id="testhook"><h4>C and Scheme hooks</h4></div>
  6844. <div class="indented">
  6845. <pre>
  6846. #include &lt;stdlib.h&gt;
  6847. #include &lt;stdio.h&gt;
  6848. #include &lt;string.h&gt;
  6849. #include "s7.h"
  6850. static s7_pointer my_hook_function(s7_scheme *sc, s7_pointer args)
  6851. {
  6852. fprintf(stderr, "a is %s\n", s7_object_to_c_string(sc, s7_symbol_local_value(sc, s7_make_symbol(sc, "a"), s7_car(args))));
  6853. return(s7_car(args));
  6854. }
  6855. int main(int argc, char **argv)
  6856. {
  6857. s7_scheme *s7;
  6858. char buffer[512];
  6859. char response[1024];
  6860. s7_pointer test_hook;
  6861. s7 = s7_init();
  6862. /* define test_hook in C, test-hook in Scheme, arguments are named a and b */
  6863. test_hook = <em class=red>s7_eval_c_string</em>(s7, "(make-hook 'a 'b)");
  6864. s7_define_constant(s7, "test-hook", test_hook);
  6865. /* add my_hook_function to the test_hook function list */
  6866. <em class=red>s7_hook_set_functions</em>(s7, test_hook,
  6867. s7_cons(s7,
  6868. s7_make_function(s7, "my-hook-function", my_hook_function, 1, 0, false, "my hook-function"),
  6869. s7_hook_functions(s7, test_hook)));
  6870. while (1)
  6871. {
  6872. fprintf(stdout, "\n&gt; ");
  6873. fgets(buffer, 512, stdin);
  6874. if ((buffer[0] != '\n') ||
  6875. (strlen(buffer) &gt; 1))
  6876. {
  6877. sprintf(response, "(write %s)", buffer);
  6878. s7_eval_c_string(s7, response);
  6879. }
  6880. }
  6881. }
  6882. /*
  6883. * &gt; test-hook
  6884. * <em class="gray">#&lt;lambda (hook)&gt;</em>
  6885. * &gt; (hook-functions test-hook)
  6886. * <em class="gray">(my-hook-function)</em>
  6887. * &gt; (test-hook 1 2)
  6888. * <em class="gray">a is 1</em>
  6889. * <em class="gray">#&lt;unspecified&gt;</em>
  6890. */
  6891. </pre></div>
  6892. <div class="header" id="dload"><h4>Load a shared library</h4></div>
  6893. <p>We can use dlopen to load a shared library, and dlsym to initialize
  6894. that library in our main program. The tricky part is to conjure up the right
  6895. compiler and loader flags.
  6896. First we define a module that defines a new s7 function, add-1 that we'll tie
  6897. into s7 explicitly, and another
  6898. function that we'll try to call by waving a wand.
  6899. </p>
  6900. <div class="indented">
  6901. <pre>
  6902. #include &lt;stdlib.h&gt;
  6903. #include &lt;stdio.h&gt;
  6904. #include &lt;string.h&gt;
  6905. #include "s7.h"
  6906. double a_function(double an_arg);
  6907. double a_function(double an_arg)
  6908. {
  6909. return(an_arg + 1.0);
  6910. }
  6911. static s7_pointer add_1(s7_scheme *sc, s7_pointer args)
  6912. {
  6913. return(s7_make_integer(sc, s7_integer(s7_car(args)) + 1));
  6914. }
  6915. void init_ex(s7_scheme *sc);
  6916. void init_ex(s7_scheme *sc) /* this needs to be globally accessible (not "static") */
  6917. {
  6918. /* tell s7 about add-1, but leave a_function hidden */
  6919. s7_define_function(sc, "add-1", add_1, 1, 0, false, "(add-1 x) adds 1 to x");
  6920. }
  6921. </pre></div>
  6922. <p>And here is our main program:
  6923. </p>
  6924. <div class="indented">
  6925. <pre>
  6926. #include &lt;stdlib.h&gt;
  6927. #include &lt;stdio.h&gt;
  6928. #include &lt;string.h&gt;
  6929. #include "s7.h"
  6930. #include &lt;dlfcn.h&gt;
  6931. static void *library = NULL;
  6932. static s7_pointer try(s7_scheme *sc, s7_pointer args)
  6933. {
  6934. /* try tries to call an arbitrary function in the shared library */
  6935. void *func;
  6936. func = <em class=red>dlsym</em>(library, s7_string(s7_car(args)));
  6937. if (func)
  6938. {
  6939. /* we'll assume double f(double) */
  6940. typedef double (*dl_func)(double arg);
  6941. return(s7_make_real(sc, ((dl_func)<em class=red>func</em>)(s7_real(s7_cadr(args)))));
  6942. }
  6943. return(s7_error(sc, s7_make_symbol(sc, "can't find function"),
  6944. s7_list(sc, 2, s7_make_string(sc, "loader error: ~S"),
  6945. s7_make_string(sc, dlerror()))));
  6946. }
  6947. static s7_pointer cload(s7_scheme *sc, s7_pointer args)
  6948. {
  6949. /* cload loads a shared library */
  6950. #define CLOAD_HELP "(cload so-file-name) loads the module"
  6951. library = dlopen(s7_string(s7_car(args)), RTLD_LAZY);
  6952. if (library)
  6953. {
  6954. /* call our init func to define add-1 in s7 */
  6955. void *init_func;
  6956. init_func = <em class=red>dlsym</em>(library, s7_string(s7_cadr(args)));
  6957. if (init_func)
  6958. {
  6959. typedef void *(*dl_func)(s7_scheme *sc);
  6960. ((dl_func)<em class=red>init_func</em>)(sc); /* call the initialization function (init_ex above) */
  6961. return(s7_t(sc));
  6962. }
  6963. }
  6964. return(s7_error(sc, s7_make_symbol(sc, "load-error"),
  6965. s7_list(sc, 2, s7_make_string(sc, "loader error: ~S"),
  6966. s7_make_string(sc, dlerror()))));
  6967. }
  6968. int main(int argc, char **argv)
  6969. {
  6970. char buffer[512];
  6971. char response[1024];
  6972. s7_scheme *s7;
  6973. s7 = s7_init();
  6974. s7_define_function(s7, "cload", cload, 2, 0, false, CLOAD_HELP);
  6975. s7_define_function(s7, "try", try, 2, 0, false,
  6976. "(try name num) tries to call name in the shared library with the argument num.");
  6977. while (1)
  6978. {
  6979. fprintf(stdout, "\n&gt; ");
  6980. fgets(buffer, 512, stdin);
  6981. if ((buffer[0] != '\n') ||
  6982. (strlen(buffer) &gt; 1))
  6983. {
  6984. sprintf(response, "(write %s)", buffer);
  6985. s7_eval_c_string(s7, response);
  6986. }
  6987. }
  6988. }
  6989. /* Put the module in the file ex3a.c and the main program in ex3.c, then
  6990. *
  6991. * in Linux:
  6992. * gcc -c -fPIC ex3a.c
  6993. * gcc ex3a.o -shared -o ex3a.so
  6994. * gcc -c s7.c -I. -fPIC -shared
  6995. * gcc -o ex3 ex3.c s7.o -lm -ldl -I. -Wl,-export-dynamic
  6996. * # omit -ldl in freeBSD, openBSD might want -ftrampolines
  6997. *
  6998. * in Mac OSX:
  6999. * gcc -c ex3a.c
  7000. * gcc ex3a.o -o ex3a.so -dynamic -bundle -undefined suppress -flat_namespace
  7001. * gcc -c s7.c -I. -dynamic -bundle -undefined suppress -flat_namespace
  7002. * gcc -o ex3 ex3.c s7.o -lm -ldl -I.
  7003. *
  7004. * and run it:
  7005. * ex3
  7006. * &gt; (cload "/home/bil/snd-16/ex3a.so" "init_ex")
  7007. * <em class="gray">#t</em>
  7008. * &gt; (add-1 2)
  7009. * <em class="gray">3</em>
  7010. * &gt; (try "a_function" 2.5)
  7011. * <em class="gray">3.5</em>
  7012. */
  7013. </pre></div>
  7014. <p>All of this is just boring boilerplate, so with a little support from s7,
  7015. we can write a script to do the entire linkage. The s7 side is an extension
  7016. to "load" that loads a shared object file if its extension is "so", and
  7017. runs an initialization function whose name is defined in the load
  7018. environment (the optional second argument to load). An example of the scheme side is cload.scm,
  7019. included in the s7 tarball. It defines a function that can be
  7020. called:
  7021. </p>
  7022. <pre class="indented">
  7023. (c-define '(double j0 (double)) "m" "math.h")
  7024. </pre>
  7025. <p>This links the s7 function m:j0 to the math library
  7026. function j0. See <a href="#cload">cload.scm</a> for more details.
  7027. </p>
  7028. <div class="header" id="gmpex"><h4>Bignums in C</h4></div>
  7029. <p>Bignum support depends on gmp, mpfr, and mpc. In this example, we define "add-1" which adds
  7030. 1 to any kind of number. The s7_big_* functions return the underlying gmp/mpfr/mpc pointer,
  7031. so we have to copy that into a new number before adding.
  7032. </p>
  7033. <div class="indented">
  7034. <pre>
  7035. #include &lt;stdlib.h&gt;
  7036. #include &lt;stdio.h&gt;
  7037. #include &lt;string.h&gt;
  7038. #include &lt;gmp.h&gt;
  7039. #include &lt;mpfr.h&gt;
  7040. #include &lt;mpc.h&gt;
  7041. #include "s7.h"
  7042. static s7_pointer big_add_1(s7_scheme *sc, s7_pointer args)
  7043. {
  7044. /* add 1 to either a normal number or a bignum */
  7045. s7_pointer x;
  7046. x = s7_car(args);
  7047. if (s7_is_bignum(x))
  7048. {
  7049. s7_pointer n;
  7050. if (s7_is_integer(x))
  7051. {
  7052. mpz_t *big_n;
  7053. n = s7_make_big_integer(sc, s7_big_integer(x)); /* copy x */
  7054. big_n = s7_big_integer(n); /* get mpz_t pointer of copy */
  7055. mpz_add_ui(*big_n, *big_n, 1); /* add 1 to that */
  7056. return(n); /* return the new bignum */
  7057. }
  7058. if (s7_is_ratio(x))
  7059. {
  7060. mpq_t *big_q;
  7061. mpz_t num, den;
  7062. n = s7_make_big_ratio(sc, s7_big_ratio(x));
  7063. big_q = s7_big_ratio(n);
  7064. mpz_init_set(num, mpq_numref(*big_q));
  7065. mpz_init_set(den, mpq_denref(*big_q));
  7066. mpz_add(num, num, den);
  7067. mpq_set_num(*big_q, num);
  7068. mpz_clear(num);
  7069. mpz_clear(den);
  7070. return(n);
  7071. }
  7072. if (s7_is_real(x))
  7073. {
  7074. mpfr_t *big_x;
  7075. n = s7_make_big_real(sc, s7_big_real(x));
  7076. big_x = s7_big_real(n);
  7077. mpfr_add_ui(*big_x, *big_x, 1, GMP_RNDN);
  7078. return(n);
  7079. }
  7080. /* x must be big complex */
  7081. {
  7082. mpc_t *big_z;
  7083. n = s7_make_big_complex(sc, s7_big_complex(x));
  7084. big_z = s7_big_complex(n);
  7085. mpc_add_ui(*big_z, *big_z, 1, MPC_RNDNN);
  7086. return(n);
  7087. }
  7088. }
  7089. else
  7090. {
  7091. if (s7_is_integer(x))
  7092. return(s7_make_integer(sc, 1 + s7_integer(x)));
  7093. if (s7_is_rational(x))
  7094. return(s7_make_ratio(sc, s7_numerator(x) + s7_denominator(x), s7_denominator(x)));
  7095. if (s7_is_real(x))
  7096. return(s7_make_real(sc, 1.0 + s7_real(x)));
  7097. if (s7_is_complex(x))
  7098. return(s7_make_complex(sc, 1.0 + s7_real_part(x), s7_imag_part(x)));
  7099. }
  7100. return(s7_wrong_type_arg_error(sc, "add-1", 0, x, "a number"));
  7101. }
  7102. int main(int argc, char **argv)
  7103. {
  7104. s7_scheme *s7;
  7105. char buffer[512];
  7106. char response[1024];
  7107. s7 = s7_init();
  7108. s7_define_function(s7, "add-1", big_add_1, 1, 0, false, "(add-1 num) adds 1 to num");
  7109. while (1)
  7110. {
  7111. fprintf(stdout, "\n&gt; ");
  7112. fgets(buffer, 512, stdin);
  7113. if ((buffer[0] != '\n') ||
  7114. (strlen(buffer) &gt; 1))
  7115. {
  7116. sprintf(response, "(write %s)", buffer);
  7117. s7_eval_c_string(s7, response);
  7118. }
  7119. }
  7120. }
  7121. /*
  7122. * gcc -DWITH_GMP=1 -c s7.c -I. -O2 -g3
  7123. * gcc -DWITH_GMP=1 -o ex2 ex2.c s7.o -I. -O2 -lm -ldl -lgmp -lmpfr -lmpc
  7124. *
  7125. * ex2
  7126. * &gt; (add-1 1)
  7127. * <em class="gray">2</em>
  7128. * &gt; (add-1 2/3)
  7129. * <em class="gray">5/3</em>
  7130. * &gt; (add-1 1.4)
  7131. * <em class="gray">2.4</em>
  7132. * &gt; (add-1 1.5+i)
  7133. * <em class="gray">2.5+1i</em>
  7134. * &gt; (add-1 (bignum "3"))
  7135. * <em class="gray">4</em> ; this is the bignum 4
  7136. * &gt; (add-1 (bignum "3/4"))
  7137. * <em class="gray">7/4</em>
  7138. * &gt; (add-1 (bignum "1.4"))
  7139. * <em class="gray">2.399999999999999911182158029987476766109E0</em>
  7140. * &gt; (add-1 (bignum "1.5+i"))
  7141. * <em class="gray">2.500E0+1.000E0i</em>
  7142. */
  7143. </pre></div>
  7144. <div class="header" id="glistener"><h4>glistener.c</h4></div>
  7145. <p>glistener.c is a gtk-based repl. It is not specific to s7:
  7146. Snd uses it as its Forth and Ruby listener as well as for s7.
  7147. Here's a short example:
  7148. </p>
  7149. <div class="indented">
  7150. <pre>
  7151. #include &lt;stdlib.h&gt;
  7152. #include &lt;stdio.h&gt;
  7153. #include &lt;string.h&gt;
  7154. #include &lt;stdbool.h&gt;
  7155. #include &lt;gtk/gtk.h&gt;
  7156. #include "s7.h"
  7157. #include "glistener.h"
  7158. static s7_scheme *s7;
  7159. static gint quit_repl(GtkWidget *w, GdkEvent *event, gpointer context) {exit(0);}
  7160. static void evaluator(glistener *g, const char *text)
  7161. {
  7162. /* this sends "text" to s7 for evaluation, then displays the result */
  7163. int gc_loc;
  7164. s7_pointer old_port, result;
  7165. const char *errmsg = NULL;
  7166. char *msg = NULL;
  7167. old_port = s7_set_current_error_port(s7, s7_open_output_string(s7));
  7168. gc_loc = s7_gc_protect(s7, old_port);
  7169. result = s7_eval_c_string(s7, text);
  7170. errmsg = s7_get_output_string(s7, s7_current_error_port(s7));
  7171. if ((errmsg) && (*errmsg))
  7172. {
  7173. msg = (char *)calloc(strlen(errmsg) + 1, sizeof(char));
  7174. strcpy(msg, errmsg);
  7175. }
  7176. s7_close_output_port(s7, s7_current_error_port(s7));
  7177. s7_set_current_error_port(s7, old_port);
  7178. s7_gc_unprotect_at(s7, gc_loc);
  7179. glistener_append_text(g, "\n");
  7180. if (msg) /* some error occurred during evaluation */
  7181. glistener_append_text(g, msg);
  7182. else
  7183. { /* evaluation produced an s7 object which we need to display */
  7184. msg = s7_object_to_c_string(s7, result);
  7185. glistener_append_text(g, msg);
  7186. }
  7187. if (msg) free(msg);
  7188. glistener_append_prompt(g); /* prompt for more input */
  7189. }
  7190. static void listener_init(glistener *g, GtkWidget *w)
  7191. {
  7192. /* this is the glistener initialization function. "w" above is the new text-view widget,
  7193. * "g" is the new glistener pointer, passed to any function that wants to talk to this
  7194. * listener.
  7195. */
  7196. unsigned char prompt[4] = {0xce, 0xbb, '&gt;', '\0'}; /* lambda as prompt */
  7197. GtkTextBuffer *buffer;
  7198. buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(w));
  7199. glistener_set_font(g, pango_font_description_from_string("Monospace 10"));
  7200. /* our prompt will be a red lambda */
  7201. glistener_set_prompt_tag(g, gtk_text_buffer_create_tag(buffer, "glistener_prompt_tag",
  7202. "weight", PANGO_WEIGHT_BOLD,
  7203. "foreground", "red",
  7204. NULL));
  7205. glistener_set_prompt(g, prompt);
  7206. }
  7207. static const char *helper(glistener *g, const char *text)
  7208. {
  7209. /* this function is called whenever the listener thinks help is needed.
  7210. * Any string it returns is posted in the listener statusbar.
  7211. */
  7212. s7_pointer sym;
  7213. sym = s7_symbol_table_find_name(s7, text);
  7214. if (sym)
  7215. return(s7_help(s7, sym));
  7216. glistener_clear_status(g);
  7217. return(NULL);
  7218. }
  7219. static void completer(glistener *g, bool (*symbol_func)(const char *symbol_name, void *data), void *data)
  7220. {
  7221. /* this function is called when &lt;tab&gt; is typed after a partial symbol name.
  7222. * "symbol_func" above should be called on each member of the symbol-table, passing it
  7223. * the symbol name (as a string) and the data passed as "completer's" third argument.
  7224. * If symbol_func returns true, it is done, so the loop through the symbol-table can stop.
  7225. */
  7226. s7_for_each_symbol_name(s7, symbol_func, data);
  7227. }
  7228. int main(int argc, char **argv)
  7229. {
  7230. GtkWidget *shell, *frame;
  7231. glistener *g;
  7232. s7 = s7_init();
  7233. gtk_init(&amp;argc, &amp;argv);
  7234. shell = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  7235. g_signal_connect(G_OBJECT(shell), "delete_event", G_CALLBACK(quit_repl), NULL);
  7236. frame = gtk_frame_new(NULL);
  7237. gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_ETCHED_IN);
  7238. gtk_widget_show(frame);
  7239. gtk_container_add(GTK_CONTAINER(shell), frame);
  7240. /* make a new listener */
  7241. g = glistener_new(frame, listener_init);
  7242. glistener_set_evaluator(g, evaluator);
  7243. glistener_set_helper(g, helper);
  7244. glistener_set_completer(g, completer);
  7245. gtk_widget_show(shell);
  7246. gdk_window_resize(gtk_widget_get_window(shell), 400, 200);
  7247. gtk_main();
  7248. }
  7249. /* in gtk-2: gcc gcall.c -o gcall s7.o glistener.o `pkg-config --libs gtk+-2.0 --cflags` -lm -ldl
  7250. * in gtk-3: gcc gcall.c -o gcall s7.o glistener.o `pkg-config --libs gtk+-3.0 --cflags` -lm -ldl
  7251. */
  7252. </pre>
  7253. <div class="listener">
  7254. <pre>
  7255. <em class=redb>&lambda;&gt;</em> (define &lambda; lambda)
  7256. <em class="gray">&lambda;</em>
  7257. <em class=redb>&lambda;&gt;</em> ((&lambda; (a b) (+ a b)) 1 2)
  7258. <em class="gray">3</em>
  7259. <em class=redb>&lambda;&gt;</em>
  7260. </pre>
  7261. </div>
  7262. <br>
  7263. <p>The five or six functions supplied by the caller (evaluator, helper,
  7264. completer, checker, colorizer, keyer) all have defaults, so you don't have to supply
  7265. anything but an evaluator. The default evaluator just prints "?" and prompts
  7266. for more input. See glistener.h for the full API and an earnest attempt
  7267. at helpful documentation.
  7268. </p>
  7269. <p>A multi-listener test program is the Snd file tools/gcall.c which
  7270. is used by tools/gtest.scm for regression testing. One way to name unicode characters
  7271. is: <code>(define-constant |lambda| #u8(#xce #xbb))</code>. This can be embedded
  7272. in an ordinary s7 string with any string operation: <code>(string-append |lambda| "ambda")</code>
  7273. which returns "&lambda;ambda". (string-length will still return the number of bytes; to get
  7274. the number of characters in a case like this, use g_utf8_strlen).
  7275. So, to set the prompt to be a red lambda and the font to be "Nimbus mono 10" from Scheme,
  7276. assuming we have the usual Scheme-to-C linkages (see snd-glistener.c):
  7277. </p>
  7278. <pre class="indented">
  7279. (set! (listener-prompt) (byte-vector #xce #xbb (char-&gt;integer #\&gt;) (char-&gt;integer #\space)))
  7280. (set! (listener-font) "Nimbus mono 10")
  7281. (listener-set-prompt-tag *listener* ; ideally this too would be a setter
  7282. (gtk_text_buffer_create_tag
  7283. (GTK_TEXT_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (listener-text-widget *listener*))))
  7284. "" (list "weight" PANGO_WEIGHT_BOLD "foreground" "red")))
  7285. </pre>
  7286. <p>In Snd, all the gtk code is in the *gtk* environment, so we need to use:
  7287. </p>
  7288. <pre class="indented">
  7289. (listener-set-prompt-tag *listener*
  7290. (with-let (sublet *gtk* 'textw (listener-text-widget *listener*)) ; use *gtk*
  7291. (gtk_text_buffer_create_tag
  7292. (GTK_TEXT_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW textw)))
  7293. "" (list "weight" PANGO_WEIGHT_BOLD "foreground" "red"))))
  7294. </pre>
  7295. </div>
  7296. <div class="header" id="gdb"><h4>gdb</h4></div>
  7297. <p>It is possible to make a mistake while writing C code.
  7298. I switched from Common Lisp to Scheme a long time ago
  7299. partly because it was so painful to debug FFI troubles in Common Lisp, and I
  7300. chose Guile at that time partly because I thought gdb would have native support
  7301. for it. As far as I know it is still impossible to debug CL FFI troubles, 20 years later!
  7302. And in gdb Python has muscled Guile aside. Anyway, say you have hit a segfault
  7303. and find yourself staring at a stackful of opaque pointers. Print statements are your
  7304. friend, of course, and at the gdb command level, the main one in this context is
  7305. s7_object_to_c_string. Here are some commands (intended for your .gdbinit file)
  7306. that can speed up the process. They assume the s7_scheme pointer is named "sc".
  7307. (These are now included in the gdbinit file in the s7 tarball).
  7308. </p>
  7309. <pre class="indented">
  7310. define s7print
  7311. print s7_object_to_c_string(sc, $arg0)
  7312. end
  7313. document s7print
  7314. interpret the argument as an s7 value and display it
  7315. end
  7316. # the current expression is sc-&gt;cur_code
  7317. # the current environment is sc-&gt;envir
  7318. # the error environment is sc-&gt;owlet
  7319. # so for example, to see the current local variables, s7p sc-&gt;envir
  7320. define s7eval
  7321. print s7_object_to_c_string(sc, s7_eval_c_string(sc, $arg0))
  7322. end
  7323. document s7eval
  7324. eval the argument (a string)
  7325. end
  7326. define s7stack
  7327. print s7_object_to_c_string(sc, s7_stacktrace(sc))
  7328. end
  7329. document s7stack
  7330. display the current stack
  7331. end
  7332. define s7value
  7333. print s7_object_to_c_string(sc, s7_name_to_value(sc, $arg0))
  7334. end
  7335. document s7value
  7336. print the value of the variable passed by its print name: s7v "*features*"
  7337. end
  7338. </pre>
  7339. <p>gdbinit also has s7cell to decode every field of an s7_pointer, and two backtrace
  7340. decoders: s7bt and s7btfull (heh heh). The bt replacements print the gdb backtrace info,
  7341. replacing bare pointer numbers with their s7 value, wherever possible:
  7342. </p>
  7343. <pre class="indented">
  7344. #1 0x000000000042104e in find_symbol_unchecked (sc=0x97edf0, symbol=<b>vars</b>) at s7.c:6677
  7345. x = <b>(inlet 'f import-lambda-definition-2)</b>
  7346. __FUNCTION__ = "find_symbol_unchecked"
  7347. #2 0x00000000006e3424 in eval (sc=0x97edf0, first_op=9) at s7.c:63673
  7348. _x_ = <b>import-lambda-definition-2</b>
  7349. _slot_ = <b>'form import-lambda-definition-2</b>
  7350. _sym_ = <b>env</b>
  7351. _val_ = <b>import-lambda-definition-2</b>
  7352. args = <b>(vars)</b>
  7353. p = <b>(env)</b>
  7354. func = <b>lint-walk</b>
  7355. e = <b>(inlet 'name import-lambda-definition-2 'form import-lambda-definition-2)</b>
  7356. code = <b>(lint-walk name f vars)</b>
  7357. __FUNCTION__ = "eval"
  7358. </pre>
  7359. <br><br>
  7360. <div class="topheader" id="s7examples">s7 examples</div>
  7361. <p>The s7 tarball includes several scheme files including s7test.scm,
  7362. lint.scm, cload.scm, write.scm, mockery.scm, and stuff.scm.
  7363. s7test.scm is a regression test for s7,
  7364. lint.scm is the s7 equivalent of the ancient C program named lint (modern equivalent: cppcheck),
  7365. write.scm has a pretty printer,
  7366. mockery.scm has mock data libraries,
  7367. cload.scm is a wrapper for the FFI stuff described above, and
  7368. stuff.scm is just some arbitrary stuff.
  7369. gdbinit has some gdb commands for s7.
  7370. repl.scm is a repl.
  7371. profile.scm provides access to profiling data, if it's enabled.
  7372. </p>
  7373. <div class="header" id="cload"><h4>cload.scm</h4></div>
  7374. <p>cload.scm defines the macro c-define that reduces the overhead
  7375. involved in (dynamically) linking C entities into s7.
  7376. </p>
  7377. <pre class="indented">
  7378. (<em class=def id="definecfunction">c-define</em> c-info (prefix "") (headers ()) (cflags "") (ldflags "") output-name)
  7379. </pre>
  7380. <p>For example, <code>(c-define '(double j0 (double)) "m" "math.h")</code>
  7381. links the C math library function j0 into s7 under the name m:j0,
  7382. passing it a double argument and getting a double result (a real in s7).
  7383. </p>
  7384. <p><em>prefix</em> is some arbitrary prefix that you want prepended to various names.
  7385. </p>
  7386. <p><em>headers</em> is a list of headers (as strings) that the c-info relies on, (("math.h") for example).
  7387. </p>
  7388. <p><em>cflags</em> are any special C compiler flags that are needed ("-I." in particular), and
  7389. <em>ldflags</em> is the similar case for the loader. <em>output-name</em> is the name of the
  7390. output C file and associated library. It defaults to "temp-s7-output" followed by a number.
  7391. In libm.scm, it is set to "libm_s7" to protect it across cload calls. If cload finds an
  7392. up-to-date output C file and shared library, it simply loads the library, rather than
  7393. going through all the trouble of writing and compling it.
  7394. </p>
  7395. <p><em>c-info</em> is a list that describes the C entities that you want to load into s7.
  7396. It can be either one list describing one entity, or a list of such lists.
  7397. Each description has the form:
  7398. </p>
  7399. <pre class="indented">
  7400. (return-type entity-name-in-C (argument-type...))
  7401. </pre>
  7402. <p>where each entry is a symbol, and C names are used throughout. So, in the j0
  7403. example above, <code>(double j0 (double))</code> says we want access to j0, it returns
  7404. a C double, and it takes one argument, also a C double. s7 tries to figure out
  7405. what the corresponding s7 type is, but in tricky cases, you should tell it
  7406. by replacing the bare type name with a list: <code>(C-type underlying-C-type)</code>. For example,
  7407. the Snd function set_graph_style takes an (enum) argument of type graph_style_t.
  7408. This is actually an int, so we use <code>(graph_style_t int)</code> as the type:
  7409. </p>
  7410. <pre class="indented">
  7411. (void set_graph_style ((graph_style_t int)))
  7412. </pre>
  7413. <p>If the C entity is a constant, then the descriptor list has just two entries,
  7414. the C-type and the entity name: <code>(int F_OK)</code> for example. The entity name can also be a list:
  7415. </p>
  7416. <pre class="indented">
  7417. ((graph_style_t int) (GRAPH_LINES GRAPH_DOTS GRAPH_FILLED GRAPH_DOTS_AND_LINES GRAPH_LOLLIPOPS))
  7418. </pre>
  7419. <p>This defines all the names in the list as integers.
  7420. If the C type has a space ("struct tm*"), use <code>(symbol "struct tm*")</code>
  7421. to construct the corresponding symbol.
  7422. </p>
  7423. <p>The entity is placed in the current s7 environment under the name <code>(string-append prefix ":" name)</code>
  7424. where the ":" is omitted if the prefix is null. So in the j0 example, we get in s7 the function m:j0.
  7425. c-define returns #t if it thinks the load worked, and #f otherwise.
  7426. </p>
  7427. <p>There are times when the only straightforward approach is to write the desired
  7428. C code directly. To insert C code on the fly, use (in-C "code..."). Two more such
  7429. cases that come up all the time: C-function for linkage to functions written
  7430. directly in s7 style using in-C, and C-macro for macros in the C header file that
  7431. need to be wrapped in #ifdefs.
  7432. Here are some examples:
  7433. </p>
  7434. <pre class="indented">
  7435. ;;; various math library functions
  7436. (c-define '((double j0 (double))
  7437. (double j1 (double))
  7438. (double erf (double))
  7439. (double erfc (double))
  7440. (double lgamma (double)))
  7441. "m" "math.h")
  7442. ;;; getenv and setenv
  7443. (c-define '(char* getenv (char*)))
  7444. (c-define '(int setenv (char* char* int)))
  7445. ;;; file-exists? and delete-file
  7446. (define file-exists? (let () ; define F_OK and access only within this let
  7447. (c-define '((int F_OK) (int access (char* int))) "" "unistd.h")
  7448. (lambda (arg) (= (access arg F_OK) 0))))
  7449. (define delete-file (let ()
  7450. (c-define '(int unlink (char*)) "" "unistd.h")
  7451. (lambda (file) (= (unlink file) 0)))) ; 0=success
  7452. ;;; examples from Snd:
  7453. (c-define '(char* version_info ()) "" "snd.h" "-I.")
  7454. (c-define '(mus_float_t mus_degrees_to_radians (mus_float_t)) "" "snd.h" "-I.")
  7455. (c-define '(snd_info* any_selected_sound ()) "" "snd.h" "-I.")
  7456. (c-define '(void select_channel (snd_info* int)) "" "snd.h" "-I.")
  7457. (c-define '(((graph_style_t int) (GRAPH_LINES GRAPH_DOTS GRAPH_FILLED GRAPH_DOTS_AND_LINES GRAPH_LOLLIPOPS))
  7458. (void set_graph_style ((graph_style_t int))))
  7459. "" "snd.h" "-I.")
  7460. ;;; getcwd, strftime
  7461. (c-define '(char* getcwd (char* size_t)) "" "unistd.h")
  7462. (c-define (list '(void* calloc (size_t size_t))
  7463. '(void free (void*))
  7464. '(void time (time_t*)) ; ignore returned value
  7465. (list (symbol "struct tm*") 'localtime '(time_t*))
  7466. (list 'size_t 'strftime (list 'char* 'size_t 'char* (symbol "struct tm*"))))
  7467. "" "time.h")
  7468. &gt; (let ((p (calloc 1 8))
  7469. (str (make-string 32)))
  7470. (time p)
  7471. (strftime str 32 "%a %d-%b-%Y %H:%M %Z" (localtime p))
  7472. (free p)
  7473. str)
  7474. <em class="gray">"Sat 11-Aug-2012 08:55 PDT\x00 "</em>
  7475. ;;; opendir, read_dir, closedir
  7476. (c-define '((int closedir (DIR*))
  7477. (DIR* opendir (char*))
  7478. (in-C "static char *read_dir(DIR *p) \
  7479. { \
  7480. struct dirent *dirp; \
  7481. dirp = readdir(p); \
  7482. if (!dirp) return(NULL); \
  7483. return(dirp-&gt;d_name); \
  7484. }")
  7485. (char* read_dir (DIR*)))
  7486. "" '("sys/types.h" "dirent.h"))
  7487. (let ((dir (opendir "/home/bil/gtk-snd")))
  7488. (do ((p (read_dir dir) (read_dir dir)))
  7489. ((= (length p) 0))
  7490. (format *stderr* "~A " p))
  7491. (closedir dir))
  7492. </pre>
  7493. <p>For the simple cases above, include "-ldl -Wl,-export-dynamic" in the gcc command. So the first
  7494. FFI example is built (this is in Linux):
  7495. </p>
  7496. <pre class="indented">
  7497. gcc -c s7.c -I.
  7498. gcc -o ex1 ex1.c s7.o -lm -I. -ldl -Wl,-export-dynamic
  7499. ex1
  7500. &gt; (load "cload.scm")
  7501. <em class="gray">c-define-1</em>
  7502. &gt; (c-define '(double j0 (double)) "m" "math.h")
  7503. <em class="gray">#t</em>
  7504. &gt; (m:j0 0.5)
  7505. <em class="gray">0.93846980724081</em>
  7506. </pre>
  7507. <p>See also r7rs.scm, libc.scm, libgsl.scm, libm.scm, libdl.scm, and libgdbm.scm.
  7508. libutf8proc.scm exists, but I have not tested it at all.
  7509. </p>
  7510. <div class="indented" id="libc">
  7511. <pre>
  7512. (require libc.scm)
  7513. (define (copy-file in-file out-file)
  7514. (with-let (sublet *libc* :in-file in-file :out-file out-file)
  7515. ;; the rest of the function body exists in the *libc* environment, with the
  7516. ;; function parameters in-file and out-file imported, so, for example,
  7517. ;; (open ...) below calls the libc function open.
  7518. (let ((infd (open in-file O_RDONLY 0)))
  7519. (if (= infd -1)
  7520. (error 'io-error "can't find ~S~%" in-file)
  7521. (let ((outfd (creat out-file #o666)))
  7522. (if (= outfd -1)
  7523. (begin
  7524. (close infd)
  7525. (error 'io-error "can't open ~S~%" out-file))
  7526. (let* ((BUF_SIZE 1024)
  7527. (buf (malloc BUF_SIZE)))
  7528. (do ((num (read infd buf BUF_SIZE) (read infd buf BUF_SIZE)))
  7529. ((or (&lt;= num 0)
  7530. (not (= (write outfd buf num) num)))))
  7531. (close outfd)
  7532. (close infd)
  7533. (free buf)
  7534. out-file)))))))
  7535. (define (glob-&gt;list pattern)
  7536. (with-let (sublet *libc* :pattern pattern)
  7537. (let ((g (glob.make)))
  7538. (glob pattern 0 g)
  7539. (let ((res (glob.gl_pathv g)))
  7540. (globfree g)
  7541. res))))
  7542. ;; now (load "*.scm") is (for-each load (glob-&gt;list "*.scm"))
  7543. </pre>
  7544. </div>
  7545. <div class="indented" id="libgsl">
  7546. <pre>
  7547. (require libgsl.scm)
  7548. (define (eigenvalues M)
  7549. (with-let (sublet *libgsl* :M M)
  7550. (let* ((len (sqrt (length M)))
  7551. (gm (gsl_matrix_alloc len len))
  7552. (m (float-vector-&gt;gsl_matrix M gm))
  7553. (evl (gsl_vector_complex_alloc len))
  7554. (evc (gsl_matrix_complex_alloc len len))
  7555. (w (gsl_eigen_nonsymmv_alloc len)))
  7556. (gsl_eigen_nonsymmv m evl evc w)
  7557. (gsl_eigen_nonsymmv_free w)
  7558. (gsl_eigen_nonsymmv_sort evl evc GSL_EIGEN_SORT_ABS_DESC)
  7559. (let ((vals (make-vector len)))
  7560. (do ((i 0 (+ i 1)))
  7561. ((= i len))
  7562. (set! (vals i) (gsl_vector_complex_get evl i)))
  7563. (gsl_matrix_free gm)
  7564. (gsl_vector_complex_free evl)
  7565. (gsl_matrix_complex_free evc)
  7566. vals))))
  7567. </pre>
  7568. </div>
  7569. <p>We can use gdbm (or better yet, mdb), the :readable argument to object-&gt;string, and
  7570. the fallback methods in the environments to create name-spaces (lets) with billions of
  7571. thread-safe local variables, which can be saved and communicated between s7 runs:
  7572. </p>
  7573. <div class="indented" id="libgdbm">
  7574. <pre>
  7575. (require libgdbm.scm)
  7576. (with-let *libgdbm*
  7577. (define *db*
  7578. (openlet
  7579. (inlet :file (gdbm_open "test.gdbm" 1024 GDBM_NEWDB #o664
  7580. (lambda (str) (format *stderr* "gdbm error: ~S~%" str)))
  7581. :let-ref-fallback (lambda (obj sym)
  7582. (eval-string (gdbm_fetch (obj 'file) (symbol-&gt;string sym))))
  7583. :let-set!-fallback (lambda (obj sym val)
  7584. (gdbm_store (obj 'file)
  7585. (symbol-&gt;string sym)
  7586. (object-&gt;string val :readable)
  7587. GDBM_REPLACE)
  7588. val)
  7589. :make-iterator (lambda (obj)
  7590. (let ((key #f)
  7591. (length (lambda (obj) (expt 2 20))))
  7592. (#_make-iterator
  7593. (let ((iterator? #t))
  7594. (openlet
  7595. (lambda ()
  7596. (if key
  7597. (set! key (gdbm_nextkey (obj 'file) (cdr key)))
  7598. (set! key (gdbm_firstkey (obj 'file))))
  7599. (if (pair? key)
  7600. (cons (string-&gt;symbol (car key))
  7601. (eval-string (gdbm_fetch (obj 'file) (car key))))
  7602. key))))))))))
  7603. (set! (*db* 'str) "123") ; add a variable named 'str with the value "123"
  7604. (set! (*db* 'int) 432)
  7605. (with-let *db*
  7606. (+ int (length str))) ; -&gt; 435
  7607. (map values *db*) ; -&gt; '((str . "123") (int . 432))
  7608. (gdbm_close (*db* 'file)))
  7609. </pre>
  7610. </div>
  7611. <div class="header" id="schemerepl"><h4>repl.scm</h4></div>
  7612. <p>repl.scm implements a repl using vt100 codes and libc.scm. It includes
  7613. symbol and filename completion, a history buffer, paren matching,
  7614. indentation, multi-line edits, and a debugger window.
  7615. To move around in the history buffer, use M-p, M-n or M-. (C-p and C-n are used to move the cursor in the current expression).
  7616. You can change the keymap or the prompt; all the repl functions are
  7617. accessible through the *repl* environment. One field is 'repl-let which
  7618. gives you access to all the repl's internal variables and functions.
  7619. Another is 'top-level-let, normally (sublet (rootlet)), which is the environment in
  7620. which the repl's evaluation takes place. You can reset the repl back to its
  7621. starting point with: <code>(set! (*repl* 'top-level-let) (sublet (rootlet)))</code>.
  7622. You can save the current repl state via <code>((*repl* 'save-repl))</code>, and
  7623. restore it later via <code>((*repl* 'restore-repl))</code>. The repl's saved state
  7624. is in the file save.repl, or the filename can be passed as an argument to save-repl and restore-repl.
  7625. The special symbol '** holds the last value.
  7626. </p>
  7627. <p>Meta keys are a problem on the Mac. You can use ESC instead, but that requires
  7628. super-human capacities. I stared at replacement control keys, and nothing seemed
  7629. right. If you can think of something, it's easy to define replacements: see repl.scm
  7630. which has a small table of mappings.
  7631. </p>
  7632. <p>To run the repl, either build s7 with the compiler flag -DWITH_MAIN,
  7633. or conjure up a wrapper:
  7634. </p>
  7635. <pre class="indented">
  7636. #include "s7.h"
  7637. int main(int argc, char **argv)
  7638. {
  7639. s7_scheme *sc;
  7640. sc = s7_init();
  7641. s7_load(sc, "repl.scm");
  7642. s7_eval_c_string(sc, "((*repl* 'run))");
  7643. return(0);
  7644. }
  7645. /* gcc -o r r.c s7.o -Wl,-export-dynamic -lm -I. -ldl
  7646. */
  7647. </pre>
  7648. <p>Besides evaluating s7 expressions, like any repl,
  7649. you can also type shell commands just as in a shell:
  7650. </p>
  7651. <pre class="indented">
  7652. &gt; pwd
  7653. <em class="gray">/home/bil/cl</em>
  7654. &gt; cd ..
  7655. <em class="gray">/home/bil</em>
  7656. &gt; date
  7657. <em class="gray">Wed 15-Apr-2015 17:32:24 PDT</em>
  7658. &gt; **
  7659. <em class="gray">"Wed 15-Apr-2015 17:32:24 PDT
  7660. "</em>
  7661. </pre>
  7662. <p>In most cases, these are handled through *unbound-variable-hook*, checked using "command -v", then passed
  7663. to the underlying shell via the system function. If s7's (as opposed to libc's) system command
  7664. is accessible, the '** variable holds whatever the command printed.
  7665. </p>
  7666. <p>The prompt is set by the function (*repl* 'prompt). It gets one argument,
  7667. the current line number, and should set the prompt string and its length.
  7668. </p>
  7669. <pre class="indented">
  7670. (set! (*repl* 'prompt) (lambda (num)
  7671. (with-let (*repl* 'repl-let)
  7672. (set! prompt-string "scheme&gt; ")
  7673. (set! prompt-length (length prompt-string)))))
  7674. </pre>
  7675. <p>or, to use the red lambda example mentioned earlier:
  7676. </p>
  7677. <pre class="indented">
  7678. (set! (*repl* 'prompt)
  7679. (lambda (num)
  7680. (with-let (*repl* 'repl-let)
  7681. (set! prompt-string (bold (red (string #\xce #\xbb #\&gt; #\space))))
  7682. (set! prompt-length 3)))) ; until we get unicode length calc
  7683. </pre>
  7684. <p>The line number provides a quick way to move around in the history buffer.
  7685. To get a previous line without laboriously typing M-p over and over,
  7686. simply type the line number (without control or meta bits), then M-.
  7687. </p>
  7688. <p>Here is an example of adding to the keymap:
  7689. </p>
  7690. <pre class="indented">
  7691. (set! ((*repl* 'keymap) (integer-&gt;char 17)) ; C-q to quit and return to caller
  7692. (lambda (c)
  7693. (set! ((*repl* 'repl-let) 'all-done) #t)))
  7694. </pre>
  7695. <p>To access the meta keys (in the keymap), use a string:
  7696. <code>((*repl* 'keymap) (string #\escape #\p))</code>; this is Meta-p which normally accesses
  7697. the history buffer.
  7698. </p>
  7699. <p>You can call the repl from other code, poke around in the current environment (or whatever),
  7700. then return to the caller:
  7701. </p>
  7702. <pre class="indented">
  7703. (load "repl.scm")
  7704. (define (drop-into-repl e)
  7705. (let ((C-q (integer-&gt;char 17))) ; we'll use the C-q example above to get out
  7706. (let ((old-C-q ((*repl* 'keymap) C-q))
  7707. (old-top-level (*repl* 'top-level-let)))
  7708. (dynamic-wind
  7709. (lambda ()
  7710. (set! (*repl* 'top-level-let) e)
  7711. (set! ((*repl* 'keymap) C-q)
  7712. (lambda (c)
  7713. (set! ((*repl* 'repl-let) 'all-done) #t))))
  7714. (lambda ()
  7715. ((<em class=red>*repl* 'run</em>))) ; run the repl
  7716. (lambda ()
  7717. (set! (*repl* 'top-level-let) old-top-level)
  7718. (set! ((*repl* 'keymap) C-q) old-C-q))))))
  7719. (let ((x 32))
  7720. (format *stderr* "x: ~A~%" x)
  7721. (<em class=red>drop-into-repl</em> (curlet))
  7722. (format *stderr* "now x: ~A~%" x))
  7723. </pre>
  7724. <p>Now load that code and:
  7725. </p>
  7726. <pre class="indented">
  7727. x: 32
  7728. &gt; x
  7729. <em class="gray">32</em>
  7730. &gt; (set! x 91)
  7731. <em class="gray">91</em>
  7732. &gt; x
  7733. <em class="gray">91</em>
  7734. &gt; now x: 91 ; here I typed C-q at the prompt
  7735. </pre>
  7736. <p>Another possibility:
  7737. </p>
  7738. <pre class="indented">
  7739. (set! (hook-functions *error-hook*)
  7740. (list (lambda (hook)
  7741. (apply format *stderr* (hook 'data))
  7742. (newline *stderr*)
  7743. (drop-into-repl (owlet)))))
  7744. </pre>
  7745. <p>See the end of repl.scm for more examples.
  7746. </p>
  7747. <!--
  7748. (load "/home/bil/test/sndlib/libsndlib.so" (inlet 'init_func 's7_init_sndlib))
  7749. not tested:
  7750. (load "/home/bil/test/libxm/libxm.so" (inlet 'init_func 'Init_libxm))
  7751. -->
  7752. <div class="header" id="lint"><h4>lint.scm</h4></div>
  7753. <p>lint tries to find errors or infelicities in your scheme code.
  7754. To try it:
  7755. </p>
  7756. <pre class="indented">
  7757. (load "lint.scm")
  7758. (lint "some-code.scm")
  7759. </pre>
  7760. <p>
  7761. There are several
  7762. variables at the start of lint.scm to control additional output:
  7763. </p>
  7764. <pre class="indented">
  7765. *report-unused-parameters*
  7766. *report-unused-top-level-functions*
  7767. *report-shadowed-variables*
  7768. *report-undefined-identifiers*
  7769. *report-multiply-defined-top-level-functions*
  7770. *report-nested-if*
  7771. *report-short-branch*
  7772. *report-one-armed-if*
  7773. *report-loaded-files*
  7774. *report-any-!-as-setter*
  7775. *report-doc-strings*
  7776. *report-func-as-arg-arity-mismatch*
  7777. *report-constant-expressions-in-do*
  7778. *report-bad-variable-names*
  7779. *report-built-in-functions-used-as-variables*
  7780. *report-forward-functions*
  7781. *report-sloppy-assoc*
  7782. *report-bloated-arg*
  7783. </pre>
  7784. <p>See lint.scm for more about these switches. You can also extend lint by adding your own code,
  7785. or adding your functions to lint's tables, or most simply by defining signatures for your functions.
  7786. snd-lint.scm performs these tasks for Snd. (lint exports its innards via *lint*).
  7787. lint is not smart about functions defined outside the current file, so *report-undefined-variables*
  7788. sometimes gets confused. You'll sometimes get a recommendation from lint that is less than helpful; nobody's perfect.
  7789. If it's actually wrong, and not just wrong-headed, please let me know.
  7790. Also in lint.scm are html-lint and C-lint. html-lint reads an HTML file looking for
  7791. Scheme code. If any is found, it runs s7 and then lint over it, reporting troubles.
  7792. Similarly C-lint reads a C file looking for s7_eval_c_string and running lint over its string.
  7793. </p>
  7794. <blockquote>
  7795. <div class="indented">
  7796. <p>After months of intense typing,
  7797. Insanely declares his labors complete. "Ship it!" says Mr Big, and hands
  7798. him a million stock options. Meanwhile, in the basement behind an old door
  7799. with the eldritch sign "eep Ou", in a labyrinth of pounding pipes and fluorescent lights,
  7800. a forgotten shadow types <code>(lint "insanely-great.scm")</code>...
  7801. </p>
  7802. </div>
  7803. </blockquote>
  7804. <!-- ================================================================================ -->
  7805. <script language=JavaScript>
  7806. /** from Remy Sharp at GitHub
  7807. * Note that this script is intended to be included at the *end* of the document, before </body>
  7808. */
  7809. (function (window, document) {
  7810. if ('open' in document.createElement('details')) return;
  7811. // made global by myself to be reused elsewhere
  7812. var addEvent = (function () {
  7813. if (document.addEventListener) {
  7814. return function (el, type, fn) {
  7815. if (el && el.nodeName || el === window) {
  7816. el.addEventListener(type, fn, false);
  7817. } else if (el && el.length) {
  7818. for (var i = 0; i < el.length; i++) {
  7819. addEvent(el[i], type, fn);
  7820. }
  7821. }
  7822. };
  7823. } else {
  7824. return function (el, type, fn) {
  7825. if (el && el.nodeName || el === window) {
  7826. el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
  7827. } else if (el && el.length) {
  7828. for (var i = 0; i < el.length; i++) {
  7829. addEvent(el[i], type, fn);
  7830. }
  7831. }
  7832. };
  7833. }
  7834. })();
  7835. /** details support - typically in it's own script */
  7836. // find the first /real/ node
  7837. function firstNode(source) {
  7838. var node = null;
  7839. if (source.firstChild.nodeName != "#text") {
  7840. return source.firstChild;
  7841. } else {
  7842. source = source.firstChild;
  7843. do {
  7844. source = source.nextSibling;
  7845. } while (source && source.nodeName == '#text');
  7846. return source || null;
  7847. }
  7848. }
  7849. function isSummary(el) {
  7850. var nn = el.nodeName.toUpperCase();
  7851. if (nn == 'DETAILS') {
  7852. return false;
  7853. } else if (nn == 'SUMMARY') {
  7854. return true;
  7855. } else {
  7856. return isSummary(el.parentNode);
  7857. }
  7858. }
  7859. function toggleDetails(event) {
  7860. // more sigh - need to check the clicked object
  7861. var keypress = event.type == 'keypress',
  7862. target = event.target || event.srcElement;
  7863. if (keypress || isSummary(target)) {
  7864. if (keypress) {
  7865. // if it's a keypress, make sure it was enter or space
  7866. keypress = event.which || event.keyCode;
  7867. if (keypress == 32 || keypress == 13) {
  7868. // all's good, go ahead and toggle
  7869. } else {
  7870. return;
  7871. }
  7872. }
  7873. var open = this.getAttribute('open');
  7874. if (open === null) {
  7875. this.setAttribute('open', 'open');
  7876. } else {
  7877. this.removeAttribute('open');
  7878. }
  7879. // this.className = open ? 'open' : ''; // Lame
  7880. // trigger reflow (required in IE - sometimes in Safari too)
  7881. setTimeout(function () {
  7882. document.body.className = document.body.className;
  7883. }, 13);
  7884. if (keypress) {
  7885. event.preventDefault && event.preventDefault();
  7886. return false;
  7887. }
  7888. }
  7889. }
  7890. function addStyle() {
  7891. var style = document.createElement('style'),
  7892. head = document.getElementsByTagName('head')[0],
  7893. key = style.innerText === undefined ? 'textContent' : 'innerText';
  7894. var rules = ['details{display: block;}','details > *{display: none;}','details.open > *{display: block;}','details[open] > *{display: block;}','details > summary:first-child{display: block;cursor: pointer;}','details[open]{display: block;}'];
  7895. i = rules.length;
  7896. style[key] = rules.join("\n");
  7897. head.insertBefore(style, head.firstChild);
  7898. }
  7899. var details = document.getElementsByTagName('details'),
  7900. wrapper,
  7901. i = details.length,
  7902. j,
  7903. first = null,
  7904. label = document.createElement('summary');
  7905. label.appendChild(document.createTextNode('Details'));
  7906. while (i--) {
  7907. first = firstNode(details[i]);
  7908. if (first != null && first.nodeName.toUpperCase() == 'SUMMARY') {
  7909. // we've found that there's a details label already
  7910. } else {
  7911. // first = label.cloneNode(true); // cloned nodes weren't picking up styles in IE - random
  7912. first = document.createElement('summary');
  7913. first.appendChild(document.createTextNode('Details'));
  7914. if (details[i].firstChild) {
  7915. details[i].insertBefore(first, details[i].firstChild);
  7916. } else {
  7917. details[i].appendChild(first);
  7918. }
  7919. }
  7920. // this feels *really* nasty, but we can't target details :text in css :(
  7921. j = details[i].childNodes.length;
  7922. while (j--) {
  7923. if (details[i].childNodes[j].nodeName === '#text' && (details[i].childNodes[j].nodeValue||'').replace(/\s/g, '').length) {
  7924. wrapper = document.createElement('text');
  7925. wrapper.appendChild(details[i].childNodes[j]);
  7926. details[i].insertBefore(wrapper, details[i].childNodes[j]);
  7927. }
  7928. }
  7929. first.legend = true;
  7930. first.tabIndex = 0;
  7931. }
  7932. // trigger details in case this being used on it's own
  7933. document.createElement('details');
  7934. addEvent(details, 'click', toggleDetails);
  7935. addEvent(details, 'keypress', toggleDetails);
  7936. addStyle();
  7937. })(window, document);
  7938. </script>
  7939. </body>
  7940. </html>
  7941. <!--
  7942. circular env without set!:
  7943. (let ()
  7944. (let ((b (curlet)))
  7945. (curlet)))
  7946. circular func (implicit set!):
  7947. (letrec* ((b (lambda () (a)))
  7948. (a (lambda () (b))))
  7949. (a))
  7950. (letrec ((b (lambda () (a)))
  7951. (a (lambda () (b))))
  7952. (a))
  7953. -->