api-compound.texi 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
  4. @c 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Compound Data Types
  7. @section Compound Data Types
  8. This chapter describes Guile's compound data types. By @dfn{compound}
  9. we mean that the primary purpose of these data types is to act as
  10. containers for other kinds of data (including other compound objects).
  11. For instance, a (non-uniform) vector with length 5 is a container that
  12. can hold five arbitrary Scheme objects.
  13. The various kinds of container object differ from each other in how
  14. their memory is allocated, how they are indexed, and how particular
  15. values can be looked up within them.
  16. @menu
  17. * Pairs:: Scheme's basic building block.
  18. * Lists:: Special list functions supported by Guile.
  19. * Vectors:: One-dimensional arrays of Scheme objects.
  20. * Bit Vectors:: Vectors of bits.
  21. * Arrays:: Matrices, etc.
  22. * VLists:: Vector-like lists.
  23. * Record Overview:: Walking through the maze of record APIs.
  24. * SRFI-9 Records:: The standard, recommended record API.
  25. * Records:: Guile's historical record API.
  26. * Structures:: Low-level record representation.
  27. * Dictionary Types:: About dictionary types in general.
  28. * Association Lists:: List-based dictionaries.
  29. * VHashes:: VList-based dictionaries.
  30. * Hash Tables:: Table-based dictionaries.
  31. @end menu
  32. @node Pairs
  33. @subsection Pairs
  34. @tpindex Pairs
  35. Pairs are used to combine two Scheme objects into one compound object.
  36. Hence the name: A pair stores a pair of objects.
  37. The data type @dfn{pair} is extremely important in Scheme, just like in
  38. any other Lisp dialect. The reason is that pairs are not only used to
  39. make two values available as one object, but that pairs are used for
  40. constructing lists of values. Because lists are so important in Scheme,
  41. they are described in a section of their own (@pxref{Lists}).
  42. Pairs can literally get entered in source code or at the REPL, in the
  43. so-called @dfn{dotted list} syntax. This syntax consists of an opening
  44. parentheses, the first element of the pair, a dot, the second element
  45. and a closing parentheses. The following example shows how a pair
  46. consisting of the two numbers 1 and 2, and a pair containing the symbols
  47. @code{foo} and @code{bar} can be entered. It is very important to write
  48. the whitespace before and after the dot, because otherwise the Scheme
  49. parser would not be able to figure out where to split the tokens.
  50. @lisp
  51. (1 . 2)
  52. (foo . bar)
  53. @end lisp
  54. But beware, if you want to try out these examples, you have to
  55. @dfn{quote} the expressions. More information about quotation is
  56. available in the section @ref{Expression Syntax}. The correct way
  57. to try these examples is as follows.
  58. @lisp
  59. '(1 . 2)
  60. @result{}
  61. (1 . 2)
  62. '(foo . bar)
  63. @result{}
  64. (foo . bar)
  65. @end lisp
  66. A new pair is made by calling the procedure @code{cons} with two
  67. arguments. Then the argument values are stored into a newly allocated
  68. pair, and the pair is returned. The name @code{cons} stands for
  69. "construct". Use the procedure @code{pair?} to test whether a
  70. given Scheme object is a pair or not.
  71. @rnindex cons
  72. @deffn {Scheme Procedure} cons x y
  73. @deffnx {C Function} scm_cons (x, y)
  74. Return a newly allocated pair whose car is @var{x} and whose
  75. cdr is @var{y}. The pair is guaranteed to be different (in the
  76. sense of @code{eq?}) from every previously existing object.
  77. @end deffn
  78. @rnindex pair?
  79. @deffn {Scheme Procedure} pair? x
  80. @deffnx {C Function} scm_pair_p (x)
  81. Return @code{#t} if @var{x} is a pair; otherwise return
  82. @code{#f}.
  83. @end deffn
  84. @deftypefn {C Function} int scm_is_pair (SCM x)
  85. Return 1 when @var{x} is a pair; otherwise return 0.
  86. @end deftypefn
  87. The two parts of a pair are traditionally called @dfn{car} and
  88. @dfn{cdr}. They can be retrieved with procedures of the same name
  89. (@code{car} and @code{cdr}), and can be modified with the procedures
  90. @code{set-car!} and @code{set-cdr!}.
  91. Since a very common operation in Scheme programs is to access the car of
  92. a car of a pair, or the car of the cdr of a pair, etc., the procedures
  93. called @code{caar}, @code{cadr} and so on are also predefined. However,
  94. using these procedures is often detrimental to readability, and
  95. error-prone. Thus, accessing the contents of a list is usually better
  96. achieved using pattern matching techniques (@pxref{Pattern Matching}).
  97. @rnindex car
  98. @rnindex cdr
  99. @deffn {Scheme Procedure} car pair
  100. @deffnx {Scheme Procedure} cdr pair
  101. @deffnx {C Function} scm_car (pair)
  102. @deffnx {C Function} scm_cdr (pair)
  103. Return the car or the cdr of @var{pair}, respectively.
  104. @end deffn
  105. @deftypefn {C Macro} SCM SCM_CAR (SCM pair)
  106. @deftypefnx {C Macro} SCM SCM_CDR (SCM pair)
  107. These two macros are the fastest way to access the car or cdr of a
  108. pair; they can be thought of as compiling into a single memory
  109. reference.
  110. These macros do no checking at all. The argument @var{pair} must be a
  111. valid pair.
  112. @end deftypefn
  113. @deffn {Scheme Procedure} cddr pair
  114. @deffnx {Scheme Procedure} cdar pair
  115. @deffnx {Scheme Procedure} cadr pair
  116. @deffnx {Scheme Procedure} caar pair
  117. @deffnx {Scheme Procedure} cdddr pair
  118. @deffnx {Scheme Procedure} cddar pair
  119. @deffnx {Scheme Procedure} cdadr pair
  120. @deffnx {Scheme Procedure} cdaar pair
  121. @deffnx {Scheme Procedure} caddr pair
  122. @deffnx {Scheme Procedure} cadar pair
  123. @deffnx {Scheme Procedure} caadr pair
  124. @deffnx {Scheme Procedure} caaar pair
  125. @deffnx {Scheme Procedure} cddddr pair
  126. @deffnx {Scheme Procedure} cdddar pair
  127. @deffnx {Scheme Procedure} cddadr pair
  128. @deffnx {Scheme Procedure} cddaar pair
  129. @deffnx {Scheme Procedure} cdaddr pair
  130. @deffnx {Scheme Procedure} cdadar pair
  131. @deffnx {Scheme Procedure} cdaadr pair
  132. @deffnx {Scheme Procedure} cdaaar pair
  133. @deffnx {Scheme Procedure} cadddr pair
  134. @deffnx {Scheme Procedure} caddar pair
  135. @deffnx {Scheme Procedure} cadadr pair
  136. @deffnx {Scheme Procedure} cadaar pair
  137. @deffnx {Scheme Procedure} caaddr pair
  138. @deffnx {Scheme Procedure} caadar pair
  139. @deffnx {Scheme Procedure} caaadr pair
  140. @deffnx {Scheme Procedure} caaaar pair
  141. @deffnx {C Function} scm_cddr (pair)
  142. @deffnx {C Function} scm_cdar (pair)
  143. @deffnx {C Function} scm_cadr (pair)
  144. @deffnx {C Function} scm_caar (pair)
  145. @deffnx {C Function} scm_cdddr (pair)
  146. @deffnx {C Function} scm_cddar (pair)
  147. @deffnx {C Function} scm_cdadr (pair)
  148. @deffnx {C Function} scm_cdaar (pair)
  149. @deffnx {C Function} scm_caddr (pair)
  150. @deffnx {C Function} scm_cadar (pair)
  151. @deffnx {C Function} scm_caadr (pair)
  152. @deffnx {C Function} scm_caaar (pair)
  153. @deffnx {C Function} scm_cddddr (pair)
  154. @deffnx {C Function} scm_cdddar (pair)
  155. @deffnx {C Function} scm_cddadr (pair)
  156. @deffnx {C Function} scm_cddaar (pair)
  157. @deffnx {C Function} scm_cdaddr (pair)
  158. @deffnx {C Function} scm_cdadar (pair)
  159. @deffnx {C Function} scm_cdaadr (pair)
  160. @deffnx {C Function} scm_cdaaar (pair)
  161. @deffnx {C Function} scm_cadddr (pair)
  162. @deffnx {C Function} scm_caddar (pair)
  163. @deffnx {C Function} scm_cadadr (pair)
  164. @deffnx {C Function} scm_cadaar (pair)
  165. @deffnx {C Function} scm_caaddr (pair)
  166. @deffnx {C Function} scm_caadar (pair)
  167. @deffnx {C Function} scm_caaadr (pair)
  168. @deffnx {C Function} scm_caaaar (pair)
  169. These procedures are compositions of @code{car} and @code{cdr}, where
  170. for example @code{caddr} could be defined by
  171. @lisp
  172. (define caddr (lambda (x) (car (cdr (cdr x)))))
  173. @end lisp
  174. @code{cadr}, @code{caddr} and @code{cadddr} pick out the second, third
  175. or fourth elements of a list, respectively. SRFI-1 provides the same
  176. under the names @code{second}, @code{third} and @code{fourth}
  177. (@pxref{SRFI-1 Selectors}).
  178. @end deffn
  179. @rnindex set-car!
  180. @deffn {Scheme Procedure} set-car! pair value
  181. @deffnx {C Function} scm_set_car_x (pair, value)
  182. Stores @var{value} in the car field of @var{pair}. The value returned
  183. by @code{set-car!} is unspecified.
  184. @end deffn
  185. @rnindex set-cdr!
  186. @deffn {Scheme Procedure} set-cdr! pair value
  187. @deffnx {C Function} scm_set_cdr_x (pair, value)
  188. Stores @var{value} in the cdr field of @var{pair}. The value returned
  189. by @code{set-cdr!} is unspecified.
  190. @end deffn
  191. @node Lists
  192. @subsection Lists
  193. @tpindex Lists
  194. A very important data type in Scheme---as well as in all other Lisp
  195. dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
  196. Scheme does not have a real datatype @dfn{list}. Lists are made up of
  197. @dfn{chained pairs}, and only exist by definition---a list is a chain
  198. of pairs which looks like a list.}
  199. This is the short definition of what a list is:
  200. @itemize @bullet
  201. @item
  202. Either the empty list @code{()},
  203. @item
  204. or a pair which has a list in its cdr.
  205. @end itemize
  206. @c FIXME::martin: Describe the pair chaining in more detail.
  207. @c FIXME::martin: What is a proper, what an improper list?
  208. @c What is a circular list?
  209. @c FIXME::martin: Maybe steal some graphics from the Elisp reference
  210. @c manual?
  211. @menu
  212. * List Syntax:: Writing literal lists.
  213. * List Predicates:: Testing lists.
  214. * List Constructors:: Creating new lists.
  215. * List Selection:: Selecting from lists, getting their length.
  216. * Append/Reverse:: Appending and reversing lists.
  217. * List Modification:: Modifying existing lists.
  218. * List Searching:: Searching for list elements
  219. * List Mapping:: Applying procedures to lists.
  220. @end menu
  221. @node List Syntax
  222. @subsubsection List Read Syntax
  223. The syntax for lists is an opening parentheses, then all the elements of
  224. the list (separated by whitespace) and finally a closing
  225. parentheses.@footnote{Note that there is no separation character between
  226. the list elements, like a comma or a semicolon.}.
  227. @lisp
  228. (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
  229. ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
  230. () ; @r{the empty list}
  231. @end lisp
  232. The last example needs a bit more explanation. A list with no elements,
  233. called the @dfn{empty list}, is special in some ways. It is used for
  234. terminating lists by storing it into the cdr of the last pair that makes
  235. up a list. An example will clear that up:
  236. @lisp
  237. (car '(1))
  238. @result{}
  239. 1
  240. (cdr '(1))
  241. @result{}
  242. ()
  243. @end lisp
  244. This example also shows that lists have to be quoted when written
  245. (@pxref{Expression Syntax}), because they would otherwise be
  246. mistakingly taken as procedure applications (@pxref{Simple
  247. Invocation}).
  248. @node List Predicates
  249. @subsubsection List Predicates
  250. Often it is useful to test whether a given Scheme object is a list or
  251. not. List-processing procedures could use this information to test
  252. whether their input is valid, or they could do different things
  253. depending on the datatype of their arguments.
  254. @rnindex list?
  255. @deffn {Scheme Procedure} list? x
  256. @deffnx {C Function} scm_list_p (x)
  257. Return @code{#t} if @var{x} is a proper list, else @code{#f}.
  258. @end deffn
  259. The predicate @code{null?} is often used in list-processing code to
  260. tell whether a given list has run out of elements. That is, a loop
  261. somehow deals with the elements of a list until the list satisfies
  262. @code{null?}. Then, the algorithm terminates.
  263. @rnindex null?
  264. @deffn {Scheme Procedure} null? x
  265. @deffnx {C Function} scm_null_p (x)
  266. Return @code{#t} if @var{x} is the empty list, else @code{#f}.
  267. @end deffn
  268. @deftypefn {C Function} int scm_is_null (SCM x)
  269. Return 1 when @var{x} is the empty list; otherwise return 0.
  270. @end deftypefn
  271. @node List Constructors
  272. @subsubsection List Constructors
  273. This section describes the procedures for constructing new lists.
  274. @code{list} simply returns a list where the elements are the arguments,
  275. @code{cons*} is similar, but the last argument is stored in the cdr of
  276. the last pair of the list.
  277. @c C Function scm_list(rest) used to be documented here, but it's a
  278. @c no-op since it does nothing but return the list the caller must
  279. @c have already created.
  280. @c
  281. @deffn {Scheme Procedure} list elem @dots{}
  282. @deffnx {C Function} scm_list_1 (elem1)
  283. @deffnx {C Function} scm_list_2 (elem1, elem2)
  284. @deffnx {C Function} scm_list_3 (elem1, elem2, elem3)
  285. @deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4)
  286. @deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5)
  287. @deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED})
  288. @rnindex list
  289. Return a new list containing elements @var{elem} @enddots{}.
  290. @code{scm_list_n} takes a variable number of arguments, terminated by
  291. the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is
  292. not included in the list. None of @var{elem} @dots{} can
  293. themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will
  294. terminate at that point.
  295. @end deffn
  296. @c C Function scm_cons_star(arg1,rest) used to be documented here,
  297. @c but it's not really a useful interface, since it expects the
  298. @c caller to have already consed up all but the first argument
  299. @c already.
  300. @c
  301. @deffn {Scheme Procedure} cons* arg1 arg2 @dots{}
  302. Like @code{list}, but the last arg provides the tail of the
  303. constructed list, returning @code{(cons @var{arg1} (cons
  304. @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
  305. argument. If given one argument, that argument is returned as
  306. result. This function is called @code{list*} in some other
  307. Schemes and in Common LISP.
  308. @end deffn
  309. @deffn {Scheme Procedure} list-copy lst
  310. @deffnx {C Function} scm_list_copy (lst)
  311. Return a (newly-created) copy of @var{lst}.
  312. @end deffn
  313. @deffn {Scheme Procedure} make-list n [init]
  314. Create a list containing of @var{n} elements, where each element is
  315. initialized to @var{init}. @var{init} defaults to the empty list
  316. @code{()} if not given.
  317. @end deffn
  318. Note that @code{list-copy} only makes a copy of the pairs which make up
  319. the spine of the lists. The list elements are not copied, which means
  320. that modifying the elements of the new list also modifies the elements
  321. of the old list. On the other hand, applying procedures like
  322. @code{set-cdr!} or @code{delv!} to the new list will not alter the old
  323. list. If you also need to copy the list elements (making a deep copy),
  324. use the procedure @code{copy-tree} (@pxref{Copying}).
  325. @node List Selection
  326. @subsubsection List Selection
  327. These procedures are used to get some information about a list, or to
  328. retrieve one or more elements of a list.
  329. @rnindex length
  330. @deffn {Scheme Procedure} length lst
  331. @deffnx {C Function} scm_length (lst)
  332. Return the number of elements in list @var{lst}.
  333. @end deffn
  334. @deffn {Scheme Procedure} last-pair lst
  335. @deffnx {C Function} scm_last_pair (lst)
  336. Return the last pair in @var{lst}, signalling an error if
  337. @var{lst} is circular.
  338. @end deffn
  339. @rnindex list-ref
  340. @deffn {Scheme Procedure} list-ref list k
  341. @deffnx {C Function} scm_list_ref (list, k)
  342. Return the @var{k}th element from @var{list}.
  343. @end deffn
  344. @rnindex list-tail
  345. @deffn {Scheme Procedure} list-tail lst k
  346. @deffnx {Scheme Procedure} list-cdr-ref lst k
  347. @deffnx {C Function} scm_list_tail (lst, k)
  348. Return the "tail" of @var{lst} beginning with its @var{k}th element.
  349. The first element of the list is considered to be element 0.
  350. @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
  351. think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
  352. or returning the results of cdring @var{k} times down @var{lst}.
  353. @end deffn
  354. @deffn {Scheme Procedure} list-head lst k
  355. @deffnx {C Function} scm_list_head (lst, k)
  356. Copy the first @var{k} elements from @var{lst} into a new list, and
  357. return it.
  358. @end deffn
  359. @node Append/Reverse
  360. @subsubsection Append and Reverse
  361. @code{append} and @code{append!} are used to concatenate two or more
  362. lists in order to form a new list. @code{reverse} and @code{reverse!}
  363. return lists with the same elements as their arguments, but in reverse
  364. order. The procedure variants with an @code{!} directly modify the
  365. pairs which form the list, whereas the other procedures create new
  366. pairs. This is why you should be careful when using the side-effecting
  367. variants.
  368. @rnindex append
  369. @deffn {Scheme Procedure} append lst @dots{} obj
  370. @deffnx {Scheme Procedure} append
  371. @deffnx {Scheme Procedure} append! lst @dots{} obj
  372. @deffnx {Scheme Procedure} append!
  373. @deffnx {C Function} scm_append (lstlst)
  374. @deffnx {C Function} scm_append_x (lstlst)
  375. Return a list comprising all the elements of lists @var{lst} @dots{}
  376. @var{obj}. If called with no arguments, return the empty list.
  377. @lisp
  378. (append '(x) '(y)) @result{} (x y)
  379. (append '(a) '(b c d)) @result{} (a b c d)
  380. (append '(a (b)) '((c))) @result{} (a (b) (c))
  381. @end lisp
  382. The last argument @var{obj} may actually be any object; an improper
  383. list results if the last argument is not a proper list.
  384. @lisp
  385. (append '(a b) '(c . d)) @result{} (a b c . d)
  386. (append '() 'a) @result{} a
  387. @end lisp
  388. @code{append} doesn't modify the given lists, but the return may share
  389. structure with the final @var{obj}. @code{append!} is permitted, but
  390. not required, to modify the given lists to form its return.
  391. For @code{scm_append} and @code{scm_append_x}, @var{lstlst} is a list
  392. of the list operands @var{lst} @dots{} @var{obj}. That @var{lstlst}
  393. itself is not modified or used in the return.
  394. @end deffn
  395. @rnindex reverse
  396. @deffn {Scheme Procedure} reverse lst
  397. @deffnx {Scheme Procedure} reverse! lst [newtail]
  398. @deffnx {C Function} scm_reverse (lst)
  399. @deffnx {C Function} scm_reverse_x (lst, newtail)
  400. Return a list comprising the elements of @var{lst}, in reverse order.
  401. @code{reverse} constructs a new list. @code{reverse!} is permitted, but
  402. not required, to modify @var{lst} in constructing its return.
  403. For @code{reverse!}, the optional @var{newtail} is appended to the
  404. result. @var{newtail} isn't reversed, it simply becomes the list
  405. tail. For @code{scm_reverse_x}, the @var{newtail} parameter is
  406. mandatory, but can be @code{SCM_EOL} if no further tail is required.
  407. @end deffn
  408. @node List Modification
  409. @subsubsection List Modification
  410. The following procedures modify an existing list, either by changing
  411. elements of the list, or by changing the list structure itself.
  412. @deffn {Scheme Procedure} list-set! list k val
  413. @deffnx {C Function} scm_list_set_x (list, k, val)
  414. Set the @var{k}th element of @var{list} to @var{val}.
  415. @end deffn
  416. @deffn {Scheme Procedure} list-cdr-set! list k val
  417. @deffnx {C Function} scm_list_cdr_set_x (list, k, val)
  418. Set the @var{k}th cdr of @var{list} to @var{val}.
  419. @end deffn
  420. @deffn {Scheme Procedure} delq item lst
  421. @deffnx {C Function} scm_delq (item, lst)
  422. Return a newly-created copy of @var{lst} with elements
  423. @code{eq?} to @var{item} removed. This procedure mirrors
  424. @code{memq}: @code{delq} compares elements of @var{lst} against
  425. @var{item} with @code{eq?}.
  426. @end deffn
  427. @deffn {Scheme Procedure} delv item lst
  428. @deffnx {C Function} scm_delv (item, lst)
  429. Return a newly-created copy of @var{lst} with elements
  430. @code{eqv?} to @var{item} removed. This procedure mirrors
  431. @code{memv}: @code{delv} compares elements of @var{lst} against
  432. @var{item} with @code{eqv?}.
  433. @end deffn
  434. @deffn {Scheme Procedure} delete item lst
  435. @deffnx {C Function} scm_delete (item, lst)
  436. Return a newly-created copy of @var{lst} with elements
  437. @code{equal?} to @var{item} removed. This procedure mirrors
  438. @code{member}: @code{delete} compares elements of @var{lst}
  439. against @var{item} with @code{equal?}.
  440. See also SRFI-1 which has an extended @code{delete} (@ref{SRFI-1
  441. Deleting}), and also an @code{lset-difference} which can delete
  442. multiple @var{item}s in one call (@ref{SRFI-1 Set Operations}).
  443. @end deffn
  444. @deffn {Scheme Procedure} delq! item lst
  445. @deffnx {Scheme Procedure} delv! item lst
  446. @deffnx {Scheme Procedure} delete! item lst
  447. @deffnx {C Function} scm_delq_x (item, lst)
  448. @deffnx {C Function} scm_delv_x (item, lst)
  449. @deffnx {C Function} scm_delete_x (item, lst)
  450. These procedures are destructive versions of @code{delq}, @code{delv}
  451. and @code{delete}: they modify the pointers in the existing @var{lst}
  452. rather than creating a new list. Caveat evaluator: Like other
  453. destructive list functions, these functions cannot modify the binding of
  454. @var{lst}, and so cannot be used to delete the first element of
  455. @var{lst} destructively.
  456. @end deffn
  457. @deffn {Scheme Procedure} delq1! item lst
  458. @deffnx {C Function} scm_delq1_x (item, lst)
  459. Like @code{delq!}, but only deletes the first occurrence of
  460. @var{item} from @var{lst}. Tests for equality using
  461. @code{eq?}. See also @code{delv1!} and @code{delete1!}.
  462. @end deffn
  463. @deffn {Scheme Procedure} delv1! item lst
  464. @deffnx {C Function} scm_delv1_x (item, lst)
  465. Like @code{delv!}, but only deletes the first occurrence of
  466. @var{item} from @var{lst}. Tests for equality using
  467. @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
  468. @end deffn
  469. @deffn {Scheme Procedure} delete1! item lst
  470. @deffnx {C Function} scm_delete1_x (item, lst)
  471. Like @code{delete!}, but only deletes the first occurrence of
  472. @var{item} from @var{lst}. Tests for equality using
  473. @code{equal?}. See also @code{delq1!} and @code{delv1!}.
  474. @end deffn
  475. @deffn {Scheme Procedure} filter pred lst
  476. @deffnx {Scheme Procedure} filter! pred lst
  477. Return a list containing all elements from @var{lst} which satisfy the
  478. predicate @var{pred}. The elements in the result list have the same
  479. order as in @var{lst}. The order in which @var{pred} is applied to
  480. the list elements is not specified.
  481. @code{filter} does not change @var{lst}, but the result may share a
  482. tail with it. @code{filter!} may modify @var{lst} to construct its
  483. return.
  484. @end deffn
  485. @node List Searching
  486. @subsubsection List Searching
  487. The following procedures search lists for particular elements. They use
  488. different comparison predicates for comparing list elements with the
  489. object to be searched. When they fail, they return @code{#f}, otherwise
  490. they return the sublist whose car is equal to the search object, where
  491. equality depends on the equality predicate used.
  492. @rnindex memq
  493. @deffn {Scheme Procedure} memq x lst
  494. @deffnx {C Function} scm_memq (x, lst)
  495. Return the first sublist of @var{lst} whose car is @code{eq?}
  496. to @var{x} where the sublists of @var{lst} are the non-empty
  497. lists returned by @code{(list-tail @var{lst} @var{k})} for
  498. @var{k} less than the length of @var{lst}. If @var{x} does not
  499. occur in @var{lst}, then @code{#f} (not the empty list) is
  500. returned.
  501. @end deffn
  502. @rnindex memv
  503. @deffn {Scheme Procedure} memv x lst
  504. @deffnx {C Function} scm_memv (x, lst)
  505. Return the first sublist of @var{lst} whose car is @code{eqv?}
  506. to @var{x} where the sublists of @var{lst} are the non-empty
  507. lists returned by @code{(list-tail @var{lst} @var{k})} for
  508. @var{k} less than the length of @var{lst}. If @var{x} does not
  509. occur in @var{lst}, then @code{#f} (not the empty list) is
  510. returned.
  511. @end deffn
  512. @rnindex member
  513. @deffn {Scheme Procedure} member x lst
  514. @deffnx {C Function} scm_member (x, lst)
  515. Return the first sublist of @var{lst} whose car is
  516. @code{equal?} to @var{x} where the sublists of @var{lst} are
  517. the non-empty lists returned by @code{(list-tail @var{lst}
  518. @var{k})} for @var{k} less than the length of @var{lst}. If
  519. @var{x} does not occur in @var{lst}, then @code{#f} (not the
  520. empty list) is returned.
  521. See also SRFI-1 which has an extended @code{member} function
  522. (@ref{SRFI-1 Searching}).
  523. @end deffn
  524. @node List Mapping
  525. @subsubsection List Mapping
  526. List processing is very convenient in Scheme because the process of
  527. iterating over the elements of a list can be highly abstracted. The
  528. procedures in this section are the most basic iterating procedures for
  529. lists. They take a procedure and one or more lists as arguments, and
  530. apply the procedure to each element of the list. They differ in their
  531. return value.
  532. @rnindex map
  533. @c begin (texi-doc-string "guile" "map")
  534. @deffn {Scheme Procedure} map proc arg1 arg2 @dots{}
  535. @deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{}
  536. @deffnx {C Function} scm_map (proc, arg1, args)
  537. Apply @var{proc} to each element of the list @var{arg1} (if only two
  538. arguments are given), or to the corresponding elements of the argument
  539. lists (if more than two arguments are given). The result(s) of the
  540. procedure applications are saved and returned in a list. For
  541. @code{map}, the order of procedure applications is not specified,
  542. @code{map-in-order} applies the procedure from left to right to the list
  543. elements.
  544. @end deffn
  545. @rnindex for-each
  546. @c begin (texi-doc-string "guile" "for-each")
  547. @deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{}
  548. Like @code{map}, but the procedure is always applied from left to right,
  549. and the result(s) of the procedure applications are thrown away. The
  550. return value is not specified.
  551. @end deffn
  552. See also SRFI-1 which extends these functions to take lists of unequal
  553. lengths (@ref{SRFI-1 Fold and Map}).
  554. @node Vectors
  555. @subsection Vectors
  556. @tpindex Vectors
  557. Vectors are sequences of Scheme objects. Unlike lists, the length of a
  558. vector, once the vector is created, cannot be changed. The advantage of
  559. vectors over lists is that the time required to access one element of a vector
  560. given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number,
  561. is constant, whereas lists have an access time linear to the position of the
  562. accessed element in the list.
  563. Vectors can contain any kind of Scheme object; it is even possible to
  564. have different types of objects in the same vector. For vectors
  565. containing vectors, you may wish to use arrays, instead. Note, too,
  566. that vectors are the special case of one dimensional non-uniform arrays
  567. and that most array procedures operate happily on vectors
  568. (@pxref{Arrays}).
  569. Also see @ref{SRFI-43}, for a comprehensive vector library.
  570. @menu
  571. * Vector Syntax:: Read syntax for vectors.
  572. * Vector Creation:: Dynamic vector creation and validation.
  573. * Vector Accessors:: Accessing and modifying vector contents.
  574. * Vector Accessing from C:: Ways to work with vectors from C.
  575. * Uniform Numeric Vectors:: Vectors of unboxed numeric values.
  576. @end menu
  577. @node Vector Syntax
  578. @subsubsection Read Syntax for Vectors
  579. Vectors can literally be entered in source code, just like strings,
  580. characters or some of the other data types. The read syntax for vectors
  581. is as follows: A sharp sign (@code{#}), followed by an opening
  582. parentheses, all elements of the vector in their respective read syntax,
  583. and finally a closing parentheses. Like strings, vectors do not have to
  584. be quoted.
  585. The following are examples of the read syntax for vectors; where the
  586. first vector only contains numbers and the second three different object
  587. types: a string, a symbol and a number in hexadecimal notation.
  588. @lisp
  589. #(1 2 3)
  590. #("Hello" foo #xdeadbeef)
  591. @end lisp
  592. @node Vector Creation
  593. @subsubsection Dynamic Vector Creation and Validation
  594. Instead of creating a vector implicitly by using the read syntax just
  595. described, you can create a vector dynamically by calling one of the
  596. @code{vector} and @code{list->vector} primitives with the list of Scheme
  597. values that you want to place into a vector. The size of the vector
  598. thus created is determined implicitly by the number of arguments given.
  599. @rnindex vector
  600. @rnindex list->vector
  601. @deffn {Scheme Procedure} vector arg @dots{}
  602. @deffnx {Scheme Procedure} list->vector l
  603. @deffnx {C Function} scm_vector (l)
  604. Return a newly allocated vector composed of the
  605. given arguments. Analogous to @code{list}.
  606. @lisp
  607. (vector 'a 'b 'c) @result{} #(a b c)
  608. @end lisp
  609. @end deffn
  610. The inverse operation is @code{vector->list}:
  611. @rnindex vector->list
  612. @deffn {Scheme Procedure} vector->list v
  613. @deffnx {C Function} scm_vector_to_list (v)
  614. Return a newly allocated list composed of the elements of @var{v}.
  615. @lisp
  616. (vector->list #(dah dah didah)) @result{} (dah dah didah)
  617. (list->vector '(dididit dah)) @result{} #(dididit dah)
  618. @end lisp
  619. @end deffn
  620. To allocate a vector with an explicitly specified size, use
  621. @code{make-vector}. With this primitive you can also specify an initial
  622. value for the vector elements (the same value for all elements, that
  623. is):
  624. @rnindex make-vector
  625. @deffn {Scheme Procedure} make-vector len [fill]
  626. @deffnx {C Function} scm_make_vector (len, fill)
  627. Return a newly allocated vector of @var{len} elements. If a
  628. second argument is given, then each position is initialized to
  629. @var{fill}. Otherwise the initial contents of each position is
  630. unspecified.
  631. @end deffn
  632. @deftypefn {C Function} SCM scm_c_make_vector (size_t k, SCM fill)
  633. Like @code{scm_make_vector}, but the length is given as a @code{size_t}.
  634. @end deftypefn
  635. To check whether an arbitrary Scheme value @emph{is} a vector, use the
  636. @code{vector?} primitive:
  637. @rnindex vector?
  638. @deffn {Scheme Procedure} vector? obj
  639. @deffnx {C Function} scm_vector_p (obj)
  640. Return @code{#t} if @var{obj} is a vector, otherwise return
  641. @code{#f}.
  642. @end deffn
  643. @deftypefn {C Function} int scm_is_vector (SCM obj)
  644. Return non-zero when @var{obj} is a vector, otherwise return
  645. @code{zero}.
  646. @end deftypefn
  647. @node Vector Accessors
  648. @subsubsection Accessing and Modifying Vector Contents
  649. @code{vector-length} and @code{vector-ref} return information about a
  650. given vector, respectively its size and the elements that are contained
  651. in the vector.
  652. @rnindex vector-length
  653. @deffn {Scheme Procedure} vector-length vector
  654. @deffnx {C Function} scm_vector_length (vector)
  655. Return the number of elements in @var{vector} as an exact integer.
  656. @end deffn
  657. @deftypefn {C Function} size_t scm_c_vector_length (SCM vec)
  658. Return the number of elements in @var{vec} as a @code{size_t}.
  659. @end deftypefn
  660. @rnindex vector-ref
  661. @deffn {Scheme Procedure} vector-ref vec k
  662. @deffnx {C Function} scm_vector_ref (vec, k)
  663. Return the contents of position @var{k} of @var{vec}.
  664. @var{k} must be a valid index of @var{vec}.
  665. @lisp
  666. (vector-ref #(1 1 2 3 5 8 13 21) 5) @result{} 8
  667. (vector-ref #(1 1 2 3 5 8 13 21)
  668. (let ((i (round (* 2 (acos -1)))))
  669. (if (inexact? i)
  670. (inexact->exact i)
  671. i))) @result{} 13
  672. @end lisp
  673. @end deffn
  674. @deftypefn {C Function} SCM scm_c_vector_ref (SCM vec, size_t k)
  675. Return the contents of position @var{k} (a @code{size_t}) of
  676. @var{vec}.
  677. @end deftypefn
  678. A vector created by one of the dynamic vector constructor procedures
  679. (@pxref{Vector Creation}) can be modified using the following
  680. procedures.
  681. @emph{NOTE:} According to R5RS, it is an error to use any of these
  682. procedures on a literally read vector, because such vectors should be
  683. considered as constants. Currently, however, Guile does not detect this
  684. error.
  685. @rnindex vector-set!
  686. @deffn {Scheme Procedure} vector-set! vec k obj
  687. @deffnx {C Function} scm_vector_set_x (vec, k, obj)
  688. Store @var{obj} in position @var{k} of @var{vec}.
  689. @var{k} must be a valid index of @var{vec}.
  690. The value returned by @samp{vector-set!} is unspecified.
  691. @lisp
  692. (let ((vec (vector 0 '(2 2 2 2) "Anna")))
  693. (vector-set! vec 1 '("Sue" "Sue"))
  694. vec) @result{} #(0 ("Sue" "Sue") "Anna")
  695. @end lisp
  696. @end deffn
  697. @deftypefn {C Function} void scm_c_vector_set_x (SCM vec, size_t k, SCM obj)
  698. Store @var{obj} in position @var{k} (a @code{size_t}) of @var{vec}.
  699. @end deftypefn
  700. @rnindex vector-fill!
  701. @deffn {Scheme Procedure} vector-fill! vec fill
  702. @deffnx {C Function} scm_vector_fill_x (vec, fill)
  703. Store @var{fill} in every position of @var{vec}. The value
  704. returned by @code{vector-fill!} is unspecified.
  705. @end deffn
  706. @deffn {Scheme Procedure} vector-copy vec
  707. @deffnx {C Function} scm_vector_copy (vec)
  708. Return a copy of @var{vec}.
  709. @end deffn
  710. @deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2
  711. @deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
  712. Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
  713. to @var{vec2} starting at position @var{start2}. @var{start1} and
  714. @var{start2} are inclusive indices; @var{end1} is exclusive.
  715. @code{vector-move-left!} copies elements in leftmost order.
  716. Therefore, in the case where @var{vec1} and @var{vec2} refer to the
  717. same vector, @code{vector-move-left!} is usually appropriate when
  718. @var{start1} is greater than @var{start2}.
  719. @end deffn
  720. @deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2
  721. @deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2)
  722. Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
  723. to @var{vec2} starting at position @var{start2}. @var{start1} and
  724. @var{start2} are inclusive indices; @var{end1} is exclusive.
  725. @code{vector-move-right!} copies elements in rightmost order.
  726. Therefore, in the case where @var{vec1} and @var{vec2} refer to the
  727. same vector, @code{vector-move-right!} is usually appropriate when
  728. @var{start1} is less than @var{start2}.
  729. @end deffn
  730. @node Vector Accessing from C
  731. @subsubsection Vector Accessing from C
  732. A vector can be read and modified from C with the functions
  733. @code{scm_c_vector_ref} and @code{scm_c_vector_set_x}, for example. In
  734. addition to these functions, there are two more ways to access vectors
  735. from C that might be more efficient in certain situations: you can
  736. restrict yourself to @dfn{simple vectors} and then use the very fast
  737. @emph{simple vector macros}; or you can use the very general framework
  738. for accessing all kinds of arrays (@pxref{Accessing Arrays from C}),
  739. which is more verbose, but can deal efficiently with all kinds of
  740. vectors (and arrays). For vectors, you can use the
  741. @code{scm_vector_elements} and @code{scm_vector_writable_elements}
  742. functions as shortcuts.
  743. @deftypefn {C Function} int scm_is_simple_vector (SCM obj)
  744. Return non-zero if @var{obj} is a simple vector, else return zero. A
  745. simple vector is a vector that can be used with the @code{SCM_SIMPLE_*}
  746. macros below.
  747. The following functions are guaranteed to return simple vectors:
  748. @code{scm_make_vector}, @code{scm_c_make_vector}, @code{scm_vector},
  749. @code{scm_list_to_vector}.
  750. @end deftypefn
  751. @deftypefn {C Macro} size_t SCM_SIMPLE_VECTOR_LENGTH (SCM vec)
  752. Evaluates to the length of the simple vector @var{vec}. No type
  753. checking is done.
  754. @end deftypefn
  755. @deftypefn {C Macro} SCM SCM_SIMPLE_VECTOR_REF (SCM vec, size_t idx)
  756. Evaluates to the element at position @var{idx} in the simple vector
  757. @var{vec}. No type or range checking is done.
  758. @end deftypefn
  759. @deftypefn {C Macro} void SCM_SIMPLE_VECTOR_SET (SCM vec, size_t idx, SCM val)
  760. Sets the element at position @var{idx} in the simple vector
  761. @var{vec} to @var{val}. No type or range checking is done.
  762. @end deftypefn
  763. @deftypefn {C Function} {const SCM *} scm_vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  764. Acquire a handle for the vector @var{vec} and return a pointer to the
  765. elements of it. This pointer can only be used to read the elements of
  766. @var{vec}. When @var{vec} is not a vector, an error is signaled. The
  767. handle must eventually be released with
  768. @code{scm_array_handle_release}.
  769. The variables pointed to by @var{lenp} and @var{incp} are filled with
  770. the number of elements of the vector and the increment (number of
  771. elements) between successive elements, respectively. Successive
  772. elements of @var{vec} need not be contiguous in their underlying
  773. ``root vector'' returned here; hence the increment is not necessarily
  774. equal to 1 and may well be negative too (@pxref{Shared Arrays}).
  775. The following example shows the typical way to use this function. It
  776. creates a list of all elements of @var{vec} (in reverse order).
  777. @example
  778. scm_t_array_handle handle;
  779. size_t i, len;
  780. ssize_t inc;
  781. const SCM *elt;
  782. SCM list;
  783. elt = scm_vector_elements (vec, &handle, &len, &inc);
  784. list = SCM_EOL;
  785. for (i = 0; i < len; i++, elt += inc)
  786. list = scm_cons (*elt, list);
  787. scm_array_handle_release (&handle);
  788. @end example
  789. @end deftypefn
  790. @deftypefn {C Function} {SCM *} scm_vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
  791. Like @code{scm_vector_elements} but the pointer can be used to modify
  792. the vector.
  793. The following example shows the typical way to use this function. It
  794. fills a vector with @code{#t}.
  795. @example
  796. scm_t_array_handle handle;
  797. size_t i, len;
  798. ssize_t inc;
  799. SCM *elt;
  800. elt = scm_vector_writable_elements (vec, &handle, &len, &inc);
  801. for (i = 0; i < len; i++, elt += inc)
  802. *elt = SCM_BOOL_T;
  803. scm_array_handle_release (&handle);
  804. @end example
  805. @end deftypefn
  806. @node Uniform Numeric Vectors
  807. @subsubsection Uniform Numeric Vectors
  808. A uniform numeric vector is a vector whose elements are all of a single
  809. numeric type. Guile offers uniform numeric vectors for signed and
  810. unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
  811. floating point values, and complex floating-point numbers of these two
  812. sizes. @xref{SRFI-4}, for more information.
  813. For many purposes, bytevectors work just as well as uniform vectors, and have
  814. the advantage that they integrate well with binary input and output.
  815. @xref{Bytevectors}, for more information on bytevectors.
  816. @node Bit Vectors
  817. @subsection Bit Vectors
  818. @noindent
  819. Bit vectors are zero-origin, one-dimensional arrays of booleans. They
  820. are displayed as a sequence of @code{0}s and @code{1}s prefixed by
  821. @code{#*}, e.g.,
  822. @example
  823. (make-bitvector 8 #f) @result{}
  824. #*00000000
  825. @end example
  826. Bit vectors are the special case of one dimensional bit arrays, and can
  827. thus be used with the array procedures, @xref{Arrays}.
  828. @deffn {Scheme Procedure} bitvector? obj
  829. @deffnx {C Function} scm_bitvector_p (obj)
  830. Return @code{#t} when @var{obj} is a bitvector, else
  831. return @code{#f}.
  832. @end deffn
  833. @deftypefn {C Function} int scm_is_bitvector (SCM obj)
  834. Return @code{1} when @var{obj} is a bitvector, else return @code{0}.
  835. @end deftypefn
  836. @deffn {Scheme Procedure} make-bitvector len [fill]
  837. @deffnx {C Function} scm_make_bitvector (len, fill)
  838. Create a new bitvector of length @var{len} and
  839. optionally initialize all elements to @var{fill}.
  840. @end deffn
  841. @deftypefn {C Function} SCM scm_c_make_bitvector (size_t len, SCM fill)
  842. Like @code{scm_make_bitvector}, but the length is given as a
  843. @code{size_t}.
  844. @end deftypefn
  845. @deffn {Scheme Procedure} bitvector bit @dots{}
  846. @deffnx {C Function} scm_bitvector (bits)
  847. Create a new bitvector with the arguments as elements.
  848. @end deffn
  849. @deffn {Scheme Procedure} bitvector-length vec
  850. @deffnx {C Function} scm_bitvector_length (vec)
  851. Return the length of the bitvector @var{vec}.
  852. @end deffn
  853. @deftypefn {C Function} size_t scm_c_bitvector_length (SCM vec)
  854. Like @code{scm_bitvector_length}, but the length is returned as a
  855. @code{size_t}.
  856. @end deftypefn
  857. @deffn {Scheme Procedure} bitvector-ref vec idx
  858. @deffnx {C Function} scm_bitvector_ref (vec, idx)
  859. Return the element at index @var{idx} of the bitvector
  860. @var{vec}.
  861. @end deffn
  862. @deftypefn {C Function} SCM scm_c_bitvector_ref (SCM vec, size_t idx)
  863. Return the element at index @var{idx} of the bitvector
  864. @var{vec}.
  865. @end deftypefn
  866. @deffn {Scheme Procedure} bitvector-set! vec idx val
  867. @deffnx {C Function} scm_bitvector_set_x (vec, idx, val)
  868. Set the element at index @var{idx} of the bitvector
  869. @var{vec} when @var{val} is true, else clear it.
  870. @end deffn
  871. @deftypefn {C Function} SCM scm_c_bitvector_set_x (SCM vec, size_t idx, SCM val)
  872. Set the element at index @var{idx} of the bitvector
  873. @var{vec} when @var{val} is true, else clear it.
  874. @end deftypefn
  875. @deffn {Scheme Procedure} bitvector-fill! vec val
  876. @deffnx {C Function} scm_bitvector_fill_x (vec, val)
  877. Set all elements of the bitvector
  878. @var{vec} when @var{val} is true, else clear them.
  879. @end deffn
  880. @deffn {Scheme Procedure} list->bitvector list
  881. @deffnx {C Function} scm_list_to_bitvector (list)
  882. Return a new bitvector initialized with the elements
  883. of @var{list}.
  884. @end deffn
  885. @deffn {Scheme Procedure} bitvector->list vec
  886. @deffnx {C Function} scm_bitvector_to_list (vec)
  887. Return a new list initialized with the elements
  888. of the bitvector @var{vec}.
  889. @end deffn
  890. @deffn {Scheme Procedure} bit-count bool bitvector
  891. @deffnx {C Function} scm_bit_count (bool, bitvector)
  892. Return a count of how many entries in @var{bitvector} are equal to
  893. @var{bool}. For example,
  894. @example
  895. (bit-count #f #*000111000) @result{} 6
  896. @end example
  897. @end deffn
  898. @deffn {Scheme Procedure} bit-position bool bitvector start
  899. @deffnx {C Function} scm_bit_position (bool, bitvector, start)
  900. Return the index of the first occurrence of @var{bool} in
  901. @var{bitvector}, starting from @var{start}. If there is no @var{bool}
  902. entry between @var{start} and the end of @var{bitvector}, then return
  903. @code{#f}. For example,
  904. @example
  905. (bit-position #t #*000101 0) @result{} 3
  906. (bit-position #f #*0001111 3) @result{} #f
  907. @end example
  908. @end deffn
  909. @deffn {Scheme Procedure} bit-invert! bitvector
  910. @deffnx {C Function} scm_bit_invert_x (bitvector)
  911. Modify @var{bitvector} by replacing each element with its negation.
  912. @end deffn
  913. @deffn {Scheme Procedure} bit-set*! bitvector uvec bool
  914. @deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool)
  915. Set entries of @var{bitvector} to @var{bool}, with @var{uvec}
  916. selecting the entries to change. The return value is unspecified.
  917. If @var{uvec} is a bit vector, then those entries where it has
  918. @code{#t} are the ones in @var{bitvector} which are set to @var{bool}.
  919. @var{uvec} and @var{bitvector} must be the same length. When
  920. @var{bool} is @code{#t} it's like @var{uvec} is OR'ed into
  921. @var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an
  922. ANDNOT.
  923. @example
  924. (define bv #*01000010)
  925. (bit-set*! bv #*10010001 #t)
  926. bv
  927. @result{} #*11010011
  928. @end example
  929. If @var{uvec} is a uniform vector of unsigned long integers, then
  930. they're indexes into @var{bitvector} which are set to @var{bool}.
  931. @example
  932. (define bv #*01000010)
  933. (bit-set*! bv #u(5 2 7) #t)
  934. bv
  935. @result{} #*01100111
  936. @end example
  937. @end deffn
  938. @deffn {Scheme Procedure} bit-count* bitvector uvec bool
  939. @deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool)
  940. Return a count of how many entries in @var{bitvector} are equal to
  941. @var{bool}, with @var{uvec} selecting the entries to consider.
  942. @var{uvec} is interpreted in the same way as for @code{bit-set*!}
  943. above. Namely, if @var{uvec} is a bit vector then entries which have
  944. @code{#t} there are considered in @var{bitvector}. Or if @var{uvec}
  945. is a uniform vector of unsigned long integers then it's the indexes in
  946. @var{bitvector} to consider.
  947. For example,
  948. @example
  949. (bit-count* #*01110111 #*11001101 #t) @result{} 3
  950. (bit-count* #*01110111 #u32(7 0 4) #f) @result{} 2
  951. @end example
  952. @end deffn
  953. @deftypefn {C Function} {const scm_t_uint32 *} scm_bitvector_elements (SCM vec, scm_t_array_handle *handle, size_t *offp, size_t *lenp, ssize_t *incp)
  954. Like @code{scm_vector_elements} (@pxref{Vector Accessing from C}), but
  955. for bitvectors. The variable pointed to by @var{offp} is set to the
  956. value returned by @code{scm_array_handle_bit_elements_offset}. See
  957. @code{scm_array_handle_bit_elements} for how to use the returned
  958. pointer and the offset.
  959. @end deftypefn
  960. @deftypefn {C Function} {scm_t_uint32 *} scm_bitvector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *offp, size_t *lenp, ssize_t *incp)
  961. Like @code{scm_bitvector_elements}, but the pointer is good for reading
  962. and writing.
  963. @end deftypefn
  964. @node Arrays
  965. @subsection Arrays
  966. @tpindex Arrays
  967. @dfn{Arrays} are a collection of cells organized into an arbitrary
  968. number of dimensions. Each cell can be accessed in constant time by
  969. supplying an index for each dimension.
  970. In the current implementation, an array uses a vector of some kind for
  971. the actual storage of its elements. Any kind of vector will do, so you
  972. can have arrays of uniform numeric values, arrays of characters, arrays
  973. of bits, and of course, arrays of arbitrary Scheme values. For example,
  974. arrays with an underlying @code{c64vector} might be nice for digital
  975. signal processing, while arrays made from a @code{u8vector} might be
  976. used to hold gray-scale images.
  977. The number of dimensions of an array is called its @dfn{rank}. Thus,
  978. a matrix is an array of rank 2, while a vector has rank 1. When
  979. accessing an array element, you have to specify one exact integer for
  980. each dimension. These integers are called the @dfn{indices} of the
  981. element. An array specifies the allowed range of indices for each
  982. dimension via an inclusive lower and upper bound. These bounds can
  983. well be negative, but the upper bound must be greater than or equal to
  984. the lower bound minus one. When all lower bounds of an array are
  985. zero, it is called a @dfn{zero-origin} array.
  986. Arrays can be of rank 0, which could be interpreted as a scalar.
  987. Thus, a zero-rank array can store exactly one object and the list of
  988. indices of this element is the empty list.
  989. Arrays contain zero elements when one of their dimensions has a zero
  990. length. These empty arrays maintain information about their shape: a
  991. matrix with zero columns and 3 rows is different from a matrix with 3
  992. columns and zero rows, which again is different from a vector of
  993. length zero.
  994. The array procedures are all polymorphic, treating strings, uniform
  995. numeric vectors, bytevectors, bit vectors and ordinary vectors as one
  996. dimensional arrays.
  997. @menu
  998. * Array Syntax::
  999. * Array Procedures::
  1000. * Shared Arrays::
  1001. * Accessing Arrays from C::
  1002. @end menu
  1003. @node Array Syntax
  1004. @subsubsection Array Syntax
  1005. An array is displayed as @code{#} followed by its rank, followed by a
  1006. tag that describes the underlying vector, optionally followed by
  1007. information about its shape, and finally followed by the cells,
  1008. organized into dimensions using parentheses.
  1009. In more words, the array tag is of the form
  1010. @example
  1011. #<rank><vectag><@@lower><:len><@@lower><:len>...
  1012. @end example
  1013. where @code{<rank>} is a positive integer in decimal giving the rank of
  1014. the array. It is omitted when the rank is 1 and the array is non-shared
  1015. and has zero-origin (see below). For shared arrays and for a non-zero
  1016. origin, the rank is always printed even when it is 1 to distinguish
  1017. them from ordinary vectors.
  1018. The @code{<vectag>} part is the tag for a uniform numeric vector, like
  1019. @code{u8}, @code{s16}, etc, @code{b} for bitvectors, or @code{a} for
  1020. strings. It is empty for ordinary vectors.
  1021. The @code{<@@lower>} part is a @samp{@@} character followed by a signed
  1022. integer in decimal giving the lower bound of a dimension. There is one
  1023. @code{<@@lower>} for each dimension. When all lower bounds are zero,
  1024. all @code{<@@lower>} parts are omitted.
  1025. The @code{<:len>} part is a @samp{:} character followed by an unsigned
  1026. integer in decimal giving the length of a dimension. Like for the lower
  1027. bounds, there is one @code{<:len>} for each dimension, and the
  1028. @code{<:len>} part always follows the @code{<@@lower>} part for a
  1029. dimension. Lengths are only then printed when they can't be deduced
  1030. from the nested lists of elements of the array literal, which can happen
  1031. when at least one length is zero.
  1032. As a special case, an array of rank 0 is printed as
  1033. @code{#0<vectag>(<scalar>)}, where @code{<scalar>} is the result of
  1034. printing the single element of the array.
  1035. Thus,
  1036. @table @code
  1037. @item #(1 2 3)
  1038. is an ordinary array of rank 1 with lower bound 0 in dimension 0.
  1039. (I.e., a regular vector.)
  1040. @item #@@2(1 2 3)
  1041. is an ordinary array of rank 1 with lower bound 2 in dimension 0.
  1042. @item #2((1 2 3) (4 5 6))
  1043. is a non-uniform array of rank 2; a 3@cross{}3 matrix with index ranges 0..2
  1044. and 0..2.
  1045. @item #u32(0 1 2)
  1046. is a uniform u8 array of rank 1.
  1047. @item #2u32@@2@@3((1 2) (2 3))
  1048. is a uniform u8 array of rank 2 with index ranges 2..3 and 3..4.
  1049. @item #2()
  1050. is a two-dimensional array with index ranges 0..-1 and 0..-1, i.e.@:
  1051. both dimensions have length zero.
  1052. @item #2:0:2()
  1053. is a two-dimensional array with index ranges 0..-1 and 0..1, i.e.@: the
  1054. first dimension has length zero, but the second has length 2.
  1055. @item #0(12)
  1056. is a rank-zero array with contents 12.
  1057. @end table
  1058. In addition, bytevectors are also arrays, but use a different syntax
  1059. (@pxref{Bytevectors}):
  1060. @table @code
  1061. @item #vu8(1 2 3)
  1062. is a 3-byte long bytevector, with contents 1, 2, 3.
  1063. @end table
  1064. @node Array Procedures
  1065. @subsubsection Array Procedures
  1066. When an array is created, the range of each dimension must be
  1067. specified, e.g., to create a 2@cross{}3 array with a zero-based index:
  1068. @example
  1069. (make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho))
  1070. @end example
  1071. The range of each dimension can also be given explicitly, e.g., another
  1072. way to create the same array:
  1073. @example
  1074. (make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho))
  1075. @end example
  1076. The following procedures can be used with arrays (or vectors). An
  1077. argument shown as @var{idx}@dots{} means one parameter for each
  1078. dimension in the array. A @var{idxlist} argument means a list of such
  1079. values, one for each dimension.
  1080. @deffn {Scheme Procedure} array? obj
  1081. @deffnx {C Function} scm_array_p (obj, unused)
  1082. Return @code{#t} if the @var{obj} is an array, and @code{#f} if
  1083. not.
  1084. The second argument to scm_array_p is there for historical reasons,
  1085. but it is not used. You should always pass @code{SCM_UNDEFINED} as
  1086. its value.
  1087. @end deffn
  1088. @deffn {Scheme Procedure} typed-array? obj type
  1089. @deffnx {C Function} scm_typed_array_p (obj, type)
  1090. Return @code{#t} if the @var{obj} is an array of type @var{type}, and
  1091. @code{#f} if not.
  1092. @end deffn
  1093. @deftypefn {C Function} int scm_is_array (SCM obj)
  1094. Return @code{1} if the @var{obj} is an array and @code{0} if not.
  1095. @end deftypefn
  1096. @deftypefn {C Function} int scm_is_typed_array (SCM obj, SCM type)
  1097. Return @code{0} if the @var{obj} is an array of type @var{type}, and
  1098. @code{1} if not.
  1099. @end deftypefn
  1100. @deffn {Scheme Procedure} make-array fill bound @dots{}
  1101. @deffnx {C Function} scm_make_array (fill, bounds)
  1102. Equivalent to @code{(make-typed-array #t @var{fill} @var{bound} ...)}.
  1103. @end deffn
  1104. @deffn {Scheme Procedure} make-typed-array type fill bound @dots{}
  1105. @deffnx {C Function} scm_make_typed_array (type, fill, bounds)
  1106. Create and return an array that has as many dimensions as there are
  1107. @var{bound}s and (maybe) fill it with @var{fill}.
  1108. The underlying storage vector is created according to @var{type},
  1109. which must be a symbol whose name is the `vectag' of the array as
  1110. explained above, or @code{#t} for ordinary, non-specialized arrays.
  1111. For example, using the symbol @code{f64} for @var{type} will create an
  1112. array that uses a @code{f64vector} for storing its elements, and
  1113. @code{a} will use a string.
  1114. When @var{fill} is not the special @emph{unspecified} value, the new
  1115. array is filled with @var{fill}. Otherwise, the initial contents of
  1116. the array is unspecified. The special @emph{unspecified} value is
  1117. stored in the variable @code{*unspecified*} so that for example
  1118. @code{(make-typed-array 'u32 *unspecified* 4)} creates a uninitialized
  1119. @code{u32} vector of length 4.
  1120. Each @var{bound} may be a positive non-zero integer @var{n}, in which
  1121. case the index for that dimension can range from 0 through @var{n}-1; or
  1122. an explicit index range specifier in the form @code{(LOWER UPPER)},
  1123. where both @var{lower} and @var{upper} are integers, possibly less than
  1124. zero, and possibly the same number (however, @var{lower} cannot be
  1125. greater than @var{upper}).
  1126. @end deffn
  1127. @deffn {Scheme Procedure} list->array dimspec list
  1128. Equivalent to @code{(list->typed-array #t @var{dimspec}
  1129. @var{list})}.
  1130. @end deffn
  1131. @deffn {Scheme Procedure} list->typed-array type dimspec list
  1132. @deffnx {C Function} scm_list_to_typed_array (type, dimspec, list)
  1133. Return an array of the type indicated by @var{type} with elements the
  1134. same as those of @var{list}.
  1135. The argument @var{dimspec} determines the number of dimensions of the
  1136. array and their lower bounds. When @var{dimspec} is an exact integer,
  1137. it gives the number of dimensions directly and all lower bounds are
  1138. zero. When it is a list of exact integers, then each element is the
  1139. lower index bound of a dimension, and there will be as many dimensions
  1140. as elements in the list.
  1141. @end deffn
  1142. @deffn {Scheme Procedure} array-type array
  1143. @deffnx {C Function} scm_array_type (array)
  1144. Return the type of @var{array}. This is the `vectag' used for
  1145. printing @var{array} (or @code{#t} for ordinary arrays) and can be
  1146. used with @code{make-typed-array} to create an array of the same kind
  1147. as @var{array}.
  1148. @end deffn
  1149. @deffn {Scheme Procedure} array-ref array idx @dots{}
  1150. @deffnx {C Function} scm_array_ref (array, idxlist)
  1151. Return the element at @code{(idx @dots{})} in @var{array}.
  1152. @example
  1153. (define a (make-array 999 '(1 2) '(3 4)))
  1154. (array-ref a 2 4) @result{} 999
  1155. @end example
  1156. @end deffn
  1157. @deffn {Scheme Procedure} array-in-bounds? array idx @dots{}
  1158. @deffnx {C Function} scm_array_in_bounds_p (array, idxlist)
  1159. Return @code{#t} if the given indices would be acceptable to
  1160. @code{array-ref}.
  1161. @example
  1162. (define a (make-array #f '(1 2) '(3 4)))
  1163. (array-in-bounds? a 2 3) @result{} #t
  1164. (array-in-bounds? a 0 0) @result{} #f
  1165. @end example
  1166. @end deffn
  1167. @deffn {Scheme Procedure} array-set! array obj idx @dots{}
  1168. @deffnx {C Function} scm_array_set_x (array, obj, idxlist)
  1169. Set the element at @code{(idx @dots{})} in @var{array} to @var{obj}.
  1170. The return value is unspecified.
  1171. @example
  1172. (define a (make-array #f '(0 1) '(0 1)))
  1173. (array-set! a #t 1 1)
  1174. a @result{} #2((#f #f) (#f #t))
  1175. @end example
  1176. @end deffn
  1177. @deffn {Scheme Procedure} array-shape array
  1178. @deffnx {Scheme Procedure} array-dimensions array
  1179. @deffnx {C Function} scm_array_dimensions (array)
  1180. Return a list of the bounds for each dimension of @var{array}.
  1181. @code{array-shape} gives @code{(@var{lower} @var{upper})} for each
  1182. dimension. @code{array-dimensions} instead returns just
  1183. @math{@var{upper}+1} for dimensions with a 0 lower bound. Both are
  1184. suitable as input to @code{make-array}.
  1185. For example,
  1186. @example
  1187. (define a (make-array 'foo '(-1 3) 5))
  1188. (array-shape a) @result{} ((-1 3) (0 4))
  1189. (array-dimensions a) @result{} ((-1 3) 5)
  1190. @end example
  1191. @end deffn
  1192. @deffn {Scheme Procedure} array-length array
  1193. @deffnx {C Function} scm_array_length (array)
  1194. @deffnx {C Function} size_t scm_c_array_length (array)
  1195. Return the length of an array: its first dimension. It is an error to
  1196. ask for the length of an array of rank 0.
  1197. @end deffn
  1198. @deffn {Scheme Procedure} array-rank array
  1199. @deffnx {C Function} scm_array_rank (array)
  1200. Return the rank of @var{array}.
  1201. @end deffn
  1202. @deftypefn {C Function} size_t scm_c_array_rank (SCM array)
  1203. Return the rank of @var{array} as a @code{size_t}.
  1204. @end deftypefn
  1205. @deffn {Scheme Procedure} array->list array
  1206. @deffnx {C Function} scm_array_to_list (array)
  1207. Return a list consisting of all the elements, in order, of
  1208. @var{array}.
  1209. @end deffn
  1210. @c FIXME: Describe how the order affects the copying (it matters for
  1211. @c shared arrays with the same underlying root vector, presumably).
  1212. @c
  1213. @deffn {Scheme Procedure} array-copy! src dst
  1214. @deffnx {Scheme Procedure} array-copy-in-order! src dst
  1215. @deffnx {C Function} scm_array_copy_x (src, dst)
  1216. Copy every element from vector or array @var{src} to the corresponding
  1217. element of @var{dst}. @var{dst} must have the same rank as @var{src},
  1218. and be at least as large in each dimension. The return value is
  1219. unspecified.
  1220. @end deffn
  1221. @deffn {Scheme Procedure} array-fill! array fill
  1222. @deffnx {C Function} scm_array_fill_x (array, fill)
  1223. Store @var{fill} in every element of @var{array}. The value returned
  1224. is unspecified.
  1225. @end deffn
  1226. @c begin (texi-doc-string "guile" "array-equal?")
  1227. @deffn {Scheme Procedure} array-equal? array @dots{}
  1228. Return @code{#t} if all arguments are arrays with the same shape, the
  1229. same type, and have corresponding elements which are either
  1230. @code{equal?} or @code{array-equal?}. This function differs from
  1231. @code{equal?} (@pxref{Equality}) in that all arguments must be arrays.
  1232. @end deffn
  1233. @c FIXME: array-map! accepts no source arrays at all, and in that
  1234. @c case makes calls "(proc)". Is that meant to be a documented
  1235. @c feature?
  1236. @c
  1237. @c FIXME: array-for-each doesn't say what happens if the sources have
  1238. @c different index ranges. The code currently iterates over the
  1239. @c indices of the first and expects the others to cover those. That
  1240. @c at least vaguely matches array-map!, but is it meant to be a
  1241. @c documented feature?
  1242. @deffn {Scheme Procedure} array-map! dst proc src @dots{}
  1243. @deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
  1244. @deffnx {C Function} scm_array_map_x (dst, proc, srclist)
  1245. Set each element of the @var{dst} array to values obtained from calls
  1246. to @var{proc}. The value returned is unspecified.
  1247. Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
  1248. where each @var{elem} is from the corresponding @var{src} array, at
  1249. the @var{dst} index. @code{array-map-in-order!} makes the calls in
  1250. row-major order, @code{array-map!} makes them in an unspecified order.
  1251. The @var{src} arrays must have the same number of dimensions as
  1252. @var{dst}, and must have a range for each dimension which covers the
  1253. range in @var{dst}. This ensures all @var{dst} indices are valid in
  1254. each @var{src}.
  1255. @end deffn
  1256. @deffn {Scheme Procedure} array-for-each proc src1 src2 @dots{}
  1257. @deffnx {C Function} scm_array_for_each (proc, src1, srclist)
  1258. Apply @var{proc} to each tuple of elements of @var{src1} @var{src2}
  1259. @dots{}, in row-major order. The value returned is unspecified.
  1260. @end deffn
  1261. @deffn {Scheme Procedure} array-index-map! dst proc
  1262. @deffnx {C Function} scm_array_index_map_x (dst, proc)
  1263. Set each element of the @var{dst} array to values returned by calls to
  1264. @var{proc}. The value returned is unspecified.
  1265. Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
  1266. @var{i1}@dots{}@var{iN} is the destination index, one parameter for
  1267. each dimension. The order in which the calls are made is unspecified.
  1268. For example, to create a @m{4\times4, 4x4} matrix representing a
  1269. cyclic group,
  1270. @tex
  1271. \advance\leftskip by 2\lispnarrowing {
  1272. $\left(\matrix{%
  1273. 0 & 1 & 2 & 3 \cr
  1274. 1 & 2 & 3 & 0 \cr
  1275. 2 & 3 & 0 & 1 \cr
  1276. 3 & 0 & 1 & 2 \cr
  1277. }\right)$} \par
  1278. @end tex
  1279. @ifnottex
  1280. @example
  1281. / 0 1 2 3 \
  1282. | 1 2 3 0 |
  1283. | 2 3 0 1 |
  1284. \ 3 0 1 2 /
  1285. @end example
  1286. @end ifnottex
  1287. @example
  1288. (define a (make-array #f 4 4))
  1289. (array-index-map! a (lambda (i j)
  1290. (modulo (+ i j) 4)))
  1291. @end example
  1292. @end deffn
  1293. @deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
  1294. @deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
  1295. Attempt to read all elements of array @var{ra}, in lexicographic order, as
  1296. binary objects from @var{port_or_fd}.
  1297. If an end of file is encountered,
  1298. the objects up to that point are put into @var{ra}
  1299. (starting at the beginning) and the remainder of the array is
  1300. unchanged.
  1301. The optional arguments @var{start} and @var{end} allow
  1302. a specified region of a vector (or linearized array) to be read,
  1303. leaving the remainder of the vector unchanged.
  1304. @code{uniform-array-read!} returns the number of objects read.
  1305. @var{port_or_fd} may be omitted, in which case it defaults to the value
  1306. returned by @code{(current-input-port)}.
  1307. @end deffn
  1308. @deffn {Scheme Procedure} uniform-array-write ra [port_or_fd [start [end]]]
  1309. @deffnx {C Function} scm_uniform_array_write (ra, port_or_fd, start, end)
  1310. Writes all elements of @var{ra} as binary objects to
  1311. @var{port_or_fd}.
  1312. The optional arguments @var{start}
  1313. and @var{end} allow
  1314. a specified region of a vector (or linearized array) to be written.
  1315. The number of objects actually written is returned.
  1316. @var{port_or_fd} may be
  1317. omitted, in which case it defaults to the value returned by
  1318. @code{(current-output-port)}.
  1319. @end deffn
  1320. @node Shared Arrays
  1321. @subsubsection Shared Arrays
  1322. @deffn {Scheme Procedure} make-shared-array oldarray mapfunc bound @dots{}
  1323. @deffnx {C Function} scm_make_shared_array (oldarray, mapfunc, boundlist)
  1324. Return a new array which shares the storage of @var{oldarray}.
  1325. Changes made through either affect the same underlying storage. The
  1326. @var{bound} @dots{} arguments are the shape of the new array, the same
  1327. as @code{make-array} (@pxref{Array Procedures}).
  1328. @var{mapfunc} translates coordinates from the new array to the
  1329. @var{oldarray}. It's called as @code{(@var{mapfunc} newidx1 @dots{})}
  1330. with one parameter for each dimension of the new array, and should
  1331. return a list of indices for @var{oldarray}, one for each dimension of
  1332. @var{oldarray}.
  1333. @var{mapfunc} must be affine linear, meaning that each @var{oldarray}
  1334. index must be formed by adding integer multiples (possibly negative)
  1335. of some or all of @var{newidx1} etc, plus a possible integer offset.
  1336. The multiples and offset must be the same in each call.
  1337. @sp 1
  1338. One good use for a shared array is to restrict the range of some
  1339. dimensions, so as to apply say @code{array-for-each} or
  1340. @code{array-fill!} to only part of an array. The plain @code{list}
  1341. function can be used for @var{mapfunc} in this case, making no changes
  1342. to the index values. For example,
  1343. @example
  1344. (make-shared-array #2((a b c) (d e f) (g h i)) list 3 2)
  1345. @result{} #2((a b) (d e) (g h))
  1346. @end example
  1347. The new array can have fewer dimensions than @var{oldarray}, for
  1348. example to take a column from an array.
  1349. @example
  1350. (make-shared-array #2((a b c) (d e f) (g h i))
  1351. (lambda (i) (list i 2))
  1352. '(0 2))
  1353. @result{} #1(c f i)
  1354. @end example
  1355. A diagonal can be taken by using the single new array index for both
  1356. row and column in the old array. For example,
  1357. @example
  1358. (make-shared-array #2((a b c) (d e f) (g h i))
  1359. (lambda (i) (list i i))
  1360. '(0 2))
  1361. @result{} #1(a e i)
  1362. @end example
  1363. Dimensions can be increased by for instance considering portions of a
  1364. one dimensional array as rows in a two dimensional array.
  1365. (@code{array-contents} below can do the opposite, flattening an
  1366. array.)
  1367. @example
  1368. (make-shared-array #1(a b c d e f g h i j k l)
  1369. (lambda (i j) (list (+ (* i 3) j)))
  1370. 4 3)
  1371. @result{} #2((a b c) (d e f) (g h i) (j k l))
  1372. @end example
  1373. By negating an index the order that elements appear can be reversed.
  1374. The following just reverses the column order,
  1375. @example
  1376. (make-shared-array #2((a b c) (d e f) (g h i))
  1377. (lambda (i j) (list i (- 2 j)))
  1378. 3 3)
  1379. @result{} #2((c b a) (f e d) (i h g))
  1380. @end example
  1381. A fixed offset on indexes allows for instance a change from a 0 based
  1382. to a 1 based array,
  1383. @example
  1384. (define x #2((a b c) (d e f) (g h i)))
  1385. (define y (make-shared-array x
  1386. (lambda (i j) (list (1- i) (1- j)))
  1387. '(1 3) '(1 3)))
  1388. (array-ref x 0 0) @result{} a
  1389. (array-ref y 1 1) @result{} a
  1390. @end example
  1391. A multiple on an index allows every Nth element of an array to be
  1392. taken. The following is every third element,
  1393. @example
  1394. (make-shared-array #1(a b c d e f g h i j k l)
  1395. (lambda (i) (list (* i 3)))
  1396. 4)
  1397. @result{} #1(a d g j)
  1398. @end example
  1399. The above examples can be combined to make weird and wonderful
  1400. selections from an array, but it's important to note that because
  1401. @var{mapfunc} must be affine linear, arbitrary permutations are not
  1402. possible.
  1403. In the current implementation, @var{mapfunc} is not called for every
  1404. access to the new array but only on some sample points to establish a
  1405. base and stride for new array indices in @var{oldarray} data. A few
  1406. sample points are enough because @var{mapfunc} is linear.
  1407. @end deffn
  1408. @deffn {Scheme Procedure} shared-array-increments array
  1409. @deffnx {C Function} scm_shared_array_increments (array)
  1410. For each dimension, return the distance between elements in the root vector.
  1411. @end deffn
  1412. @deffn {Scheme Procedure} shared-array-offset array
  1413. @deffnx {C Function} scm_shared_array_offset (array)
  1414. Return the root vector index of the first element in the array.
  1415. @end deffn
  1416. @deffn {Scheme Procedure} shared-array-root array
  1417. @deffnx {C Function} scm_shared_array_root (array)
  1418. Return the root vector of a shared array.
  1419. @end deffn
  1420. @deffn {Scheme Procedure} array-contents array [strict]
  1421. @deffnx {C Function} scm_array_contents (array, strict)
  1422. If @var{array} may be @dfn{unrolled} into a one dimensional shared array
  1423. without changing their order (last subscript changing fastest), then
  1424. @code{array-contents} returns that shared array, otherwise it returns
  1425. @code{#f}. All arrays made by @code{make-array} and
  1426. @code{make-typed-array} may be unrolled, some arrays made by
  1427. @code{make-shared-array} may not be.
  1428. If the optional argument @var{strict} is provided, a shared array will
  1429. be returned only if its elements are stored internally contiguous in
  1430. memory.
  1431. @end deffn
  1432. @deffn {Scheme Procedure} transpose-array array dim1 dim2 @dots{}
  1433. @deffnx {C Function} scm_transpose_array (array, dimlist)
  1434. Return an array sharing contents with @var{array}, but with
  1435. dimensions arranged in a different order. There must be one
  1436. @var{dim} argument for each dimension of @var{array}.
  1437. @var{dim1}, @var{dim2}, @dots{} should be integers between 0
  1438. and the rank of the array to be returned. Each integer in that
  1439. range must appear at least once in the argument list.
  1440. The values of @var{dim1}, @var{dim2}, @dots{} correspond to
  1441. dimensions in the array to be returned, and their positions in the
  1442. argument list to dimensions of @var{array}. Several @var{dim}s
  1443. may have the same value, in which case the returned array will
  1444. have smaller rank than @var{array}.
  1445. @lisp
  1446. (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
  1447. (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
  1448. (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
  1449. #2((a 4) (b 5) (c 6))
  1450. @end lisp
  1451. @end deffn
  1452. @node Accessing Arrays from C
  1453. @subsubsection Accessing Arrays from C
  1454. For interworking with external C code, Guile provides an API to allow C
  1455. code to access the elements of a Scheme array. In particular, for
  1456. uniform numeric arrays, the API exposes the underlying uniform data as a
  1457. C array of numbers of the relevant type.
  1458. While pointers to the elements of an array are in use, the array itself
  1459. must be protected so that the pointer remains valid. Such a protected
  1460. array is said to be @dfn{reserved}. A reserved array can be read but
  1461. modifications to it that would cause the pointer to its elements to
  1462. become invalid are prevented. When you attempt such a modification, an
  1463. error is signalled.
  1464. (This is similar to locking the array while it is in use, but without
  1465. the danger of a deadlock. In a multi-threaded program, you will need
  1466. additional synchronization to avoid modifying reserved arrays.)
  1467. You must take care to always unreserve an array after reserving it,
  1468. even in the presence of non-local exits. If a non-local exit can
  1469. happen between these two calls, you should install a dynwind context
  1470. that releases the array when it is left (@pxref{Dynamic Wind}).
  1471. In addition, array reserving and unreserving must be properly
  1472. paired. For instance, when reserving two or more arrays in a certain
  1473. order, you need to unreserve them in the opposite order.
  1474. Once you have reserved an array and have retrieved the pointer to its
  1475. elements, you must figure out the layout of the elements in memory.
  1476. Guile allows slices to be taken out of arrays without actually making a
  1477. copy, such as making an alias for the diagonal of a matrix that can be
  1478. treated as a vector. Arrays that result from such an operation are not
  1479. stored contiguously in memory and when working with their elements
  1480. directly, you need to take this into account.
  1481. The layout of array elements in memory can be defined via a
  1482. @emph{mapping function} that computes a scalar position from a vector of
  1483. indices. The scalar position then is the offset of the element with the
  1484. given indices from the start of the storage block of the array.
  1485. In Guile, this mapping function is restricted to be @dfn{affine}: all
  1486. mapping functions of Guile arrays can be written as @code{p = b +
  1487. c[0]*i[0] + c[1]*i[1] + ... + c[n-1]*i[n-1]} where @code{i[k]} is the
  1488. @nicode{k}th index and @code{n} is the rank of the array. For
  1489. example, a matrix of size 3x3 would have @code{b == 0}, @code{c[0] ==
  1490. 3} and @code{c[1] == 1}. When you transpose this matrix (with
  1491. @code{transpose-array}, say), you will get an array whose mapping
  1492. function has @code{b == 0}, @code{c[0] == 1} and @code{c[1] == 3}.
  1493. The function @code{scm_array_handle_dims} gives you (indirect) access to
  1494. the coefficients @code{c[k]}.
  1495. @c XXX
  1496. Note that there are no functions for accessing the elements of a
  1497. character array yet. Once the string implementation of Guile has been
  1498. changed to use Unicode, we will provide them.
  1499. @deftp {C Type} scm_t_array_handle
  1500. This is a structure type that holds all information necessary to manage
  1501. the reservation of arrays as explained above. Structures of this type
  1502. must be allocated on the stack and must only be accessed by the
  1503. functions listed below.
  1504. @end deftp
  1505. @deftypefn {C Function} void scm_array_get_handle (SCM array, scm_t_array_handle *handle)
  1506. Reserve @var{array}, which must be an array, and prepare @var{handle} to
  1507. be used with the functions below. You must eventually call
  1508. @code{scm_array_handle_release} on @var{handle}, and do this in a
  1509. properly nested fashion, as explained above. The structure pointed to
  1510. by @var{handle} does not need to be initialized before calling this
  1511. function.
  1512. @end deftypefn
  1513. @deftypefn {C Function} void scm_array_handle_release (scm_t_array_handle *handle)
  1514. End the array reservation represented by @var{handle}. After a call to
  1515. this function, @var{handle} might be used for another reservation.
  1516. @end deftypefn
  1517. @deftypefn {C Function} size_t scm_array_handle_rank (scm_t_array_handle *handle)
  1518. Return the rank of the array represented by @var{handle}.
  1519. @end deftypefn
  1520. @deftp {C Type} scm_t_array_dim
  1521. This structure type holds information about the layout of one dimension
  1522. of an array. It includes the following fields:
  1523. @table @code
  1524. @item ssize_t lbnd
  1525. @itemx ssize_t ubnd
  1526. The lower and upper bounds (both inclusive) of the permissible index
  1527. range for the given dimension. Both values can be negative, but
  1528. @var{lbnd} is always less than or equal to @var{ubnd}.
  1529. @item ssize_t inc
  1530. The distance from one element of this dimension to the next. Note, too,
  1531. that this can be negative.
  1532. @end table
  1533. @end deftp
  1534. @deftypefn {C Function} {const scm_t_array_dim *} scm_array_handle_dims (scm_t_array_handle *handle)
  1535. Return a pointer to a C vector of information about the dimensions of
  1536. the array represented by @var{handle}. This pointer is valid as long as
  1537. the array remains reserved. As explained above, the
  1538. @code{scm_t_array_dim} structures returned by this function can be used
  1539. calculate the position of an element in the storage block of the array
  1540. from its indices.
  1541. This position can then be used as an index into the C array pointer
  1542. returned by the various @code{scm_array_handle_<foo>_elements}
  1543. functions, or with @code{scm_array_handle_ref} and
  1544. @code{scm_array_handle_set}.
  1545. Here is how one can compute the position @var{pos} of an element given
  1546. its indices in the vector @var{indices}:
  1547. @example
  1548. ssize_t indices[RANK];
  1549. scm_t_array_dim *dims;
  1550. ssize_t pos;
  1551. size_t i;
  1552. pos = 0;
  1553. for (i = 0; i < RANK; i++)
  1554. @{
  1555. if (indices[i] < dims[i].lbnd || indices[i] > dims[i].ubnd)
  1556. out_of_range ();
  1557. pos += (indices[i] - dims[i].lbnd) * dims[i].inc;
  1558. @}
  1559. @end example
  1560. @end deftypefn
  1561. @deftypefn {C Function} ssize_t scm_array_handle_pos (scm_t_array_handle *handle, SCM indices)
  1562. Compute the position corresponding to @var{indices}, a list of
  1563. indices. The position is computed as described above for
  1564. @code{scm_array_handle_dims}. The number of the indices and their
  1565. range is checked and an appropriate error is signalled for invalid
  1566. indices.
  1567. @end deftypefn
  1568. @deftypefn {C Function} SCM scm_array_handle_ref (scm_t_array_handle *handle, ssize_t pos)
  1569. Return the element at position @var{pos} in the storage block of the
  1570. array represented by @var{handle}. Any kind of array is acceptable. No
  1571. range checking is done on @var{pos}.
  1572. @end deftypefn
  1573. @deftypefn {C Function} void scm_array_handle_set (scm_t_array_handle *handle, ssize_t pos, SCM val)
  1574. Set the element at position @var{pos} in the storage block of the array
  1575. represented by @var{handle} to @var{val}. Any kind of array is
  1576. acceptable. No range checking is done on @var{pos}. An error is
  1577. signalled when the array can not store @var{val}.
  1578. @end deftypefn
  1579. @deftypefn {C Function} {const SCM *} scm_array_handle_elements (scm_t_array_handle *handle)
  1580. Return a pointer to the elements of a ordinary array of general Scheme
  1581. values (i.e., a non-uniform array) for reading. This pointer is valid
  1582. as long as the array remains reserved.
  1583. @end deftypefn
  1584. @deftypefn {C Function} {SCM *} scm_array_handle_writable_elements (scm_t_array_handle *handle)
  1585. Like @code{scm_array_handle_elements}, but the pointer is good for
  1586. reading and writing.
  1587. @end deftypefn
  1588. @deftypefn {C Function} {const void *} scm_array_handle_uniform_elements (scm_t_array_handle *handle)
  1589. Return a pointer to the elements of a uniform numeric array for reading.
  1590. This pointer is valid as long as the array remains reserved. The size
  1591. of each element is given by @code{scm_array_handle_uniform_element_size}.
  1592. @end deftypefn
  1593. @deftypefn {C Function} {void *} scm_array_handle_uniform_writable_elements (scm_t_array_handle *handle)
  1594. Like @code{scm_array_handle_uniform_elements}, but the pointer is good
  1595. reading and writing.
  1596. @end deftypefn
  1597. @deftypefn {C Function} size_t scm_array_handle_uniform_element_size (scm_t_array_handle *handle)
  1598. Return the size of one element of the uniform numeric array represented
  1599. by @var{handle}.
  1600. @end deftypefn
  1601. @deftypefn {C Function} {const scm_t_uint8 *} scm_array_handle_u8_elements (scm_t_array_handle *handle)
  1602. @deftypefnx {C Function} {const scm_t_int8 *} scm_array_handle_s8_elements (scm_t_array_handle *handle)
  1603. @deftypefnx {C Function} {const scm_t_uint16 *} scm_array_handle_u16_elements (scm_t_array_handle *handle)
  1604. @deftypefnx {C Function} {const scm_t_int16 *} scm_array_handle_s16_elements (scm_t_array_handle *handle)
  1605. @deftypefnx {C Function} {const scm_t_uint32 *} scm_array_handle_u32_elements (scm_t_array_handle *handle)
  1606. @deftypefnx {C Function} {const scm_t_int32 *} scm_array_handle_s32_elements (scm_t_array_handle *handle)
  1607. @deftypefnx {C Function} {const scm_t_uint64 *} scm_array_handle_u64_elements (scm_t_array_handle *handle)
  1608. @deftypefnx {C Function} {const scm_t_int64 *} scm_array_handle_s64_elements (scm_t_array_handle *handle)
  1609. @deftypefnx {C Function} {const float *} scm_array_handle_f32_elements (scm_t_array_handle *handle)
  1610. @deftypefnx {C Function} {const double *} scm_array_handle_f64_elements (scm_t_array_handle *handle)
  1611. @deftypefnx {C Function} {const float *} scm_array_handle_c32_elements (scm_t_array_handle *handle)
  1612. @deftypefnx {C Function} {const double *} scm_array_handle_c64_elements (scm_t_array_handle *handle)
  1613. Return a pointer to the elements of a uniform numeric array of the
  1614. indicated kind for reading. This pointer is valid as long as the array
  1615. remains reserved.
  1616. The pointers for @code{c32} and @code{c64} uniform numeric arrays point
  1617. to pairs of floating point numbers. The even index holds the real part,
  1618. the odd index the imaginary part of the complex number.
  1619. @end deftypefn
  1620. @deftypefn {C Function} {scm_t_uint8 *} scm_array_handle_u8_writable_elements (scm_t_array_handle *handle)
  1621. @deftypefnx {C Function} {scm_t_int8 *} scm_array_handle_s8_writable_elements (scm_t_array_handle *handle)
  1622. @deftypefnx {C Function} {scm_t_uint16 *} scm_array_handle_u16_writable_elements (scm_t_array_handle *handle)
  1623. @deftypefnx {C Function} {scm_t_int16 *} scm_array_handle_s16_writable_elements (scm_t_array_handle *handle)
  1624. @deftypefnx {C Function} {scm_t_uint32 *} scm_array_handle_u32_writable_elements (scm_t_array_handle *handle)
  1625. @deftypefnx {C Function} {scm_t_int32 *} scm_array_handle_s32_writable_elements (scm_t_array_handle *handle)
  1626. @deftypefnx {C Function} {scm_t_uint64 *} scm_array_handle_u64_writable_elements (scm_t_array_handle *handle)
  1627. @deftypefnx {C Function} {scm_t_int64 *} scm_array_handle_s64_writable_elements (scm_t_array_handle *handle)
  1628. @deftypefnx {C Function} {float *} scm_array_handle_f32_writable_elements (scm_t_array_handle *handle)
  1629. @deftypefnx {C Function} {double *} scm_array_handle_f64_writable_elements (scm_t_array_handle *handle)
  1630. @deftypefnx {C Function} {float *} scm_array_handle_c32_writable_elements (scm_t_array_handle *handle)
  1631. @deftypefnx {C Function} {double *} scm_array_handle_c64_writable_elements (scm_t_array_handle *handle)
  1632. Like @code{scm_array_handle_<kind>_elements}, but the pointer is good
  1633. for reading and writing.
  1634. @end deftypefn
  1635. @deftypefn {C Function} {const scm_t_uint32 *} scm_array_handle_bit_elements (scm_t_array_handle *handle)
  1636. Return a pointer to the words that store the bits of the represented
  1637. array, which must be a bit array.
  1638. Unlike other arrays, bit arrays have an additional offset that must be
  1639. figured into index calculations. That offset is returned by
  1640. @code{scm_array_handle_bit_elements_offset}.
  1641. To find a certain bit you first need to calculate its position as
  1642. explained above for @code{scm_array_handle_dims} and then add the
  1643. offset. This gives the absolute position of the bit, which is always a
  1644. non-negative integer.
  1645. Each word of the bit array storage block contains exactly 32 bits, with
  1646. the least significant bit in that word having the lowest absolute
  1647. position number. The next word contains the next 32 bits.
  1648. Thus, the following code can be used to access a bit whose position
  1649. according to @code{scm_array_handle_dims} is given in @var{pos}:
  1650. @example
  1651. SCM bit_array;
  1652. scm_t_array_handle handle;
  1653. scm_t_uint32 *bits;
  1654. ssize_t pos;
  1655. size_t abs_pos;
  1656. size_t word_pos, mask;
  1657. scm_array_get_handle (&bit_array, &handle);
  1658. bits = scm_array_handle_bit_elements (&handle);
  1659. pos = ...
  1660. abs_pos = pos + scm_array_handle_bit_elements_offset (&handle);
  1661. word_pos = abs_pos / 32;
  1662. mask = 1L << (abs_pos % 32);
  1663. if (bits[word_pos] & mask)
  1664. /* bit is set. */
  1665. scm_array_handle_release (&handle);
  1666. @end example
  1667. @end deftypefn
  1668. @deftypefn {C Function} {scm_t_uint32 *} scm_array_handle_bit_writable_elements (scm_t_array_handle *handle)
  1669. Like @code{scm_array_handle_bit_elements} but the pointer is good for
  1670. reading and writing. You must take care not to modify bits outside of
  1671. the allowed index range of the array, even for contiguous arrays.
  1672. @end deftypefn
  1673. @node VLists
  1674. @subsection VLists
  1675. @cindex vlist
  1676. The @code{(ice-9 vlist)} module provides an implementation of the @dfn{VList}
  1677. data structure designed by Phil Bagwell in 2002. VLists are immutable lists,
  1678. which can contain any Scheme object. They improve on standard Scheme linked
  1679. lists in several areas:
  1680. @itemize
  1681. @item
  1682. Random access has typically constant-time complexity.
  1683. @item
  1684. Computing the length of a VList has time complexity logarithmic in the number of
  1685. elements.
  1686. @item
  1687. VLists use less storage space than standard lists.
  1688. @item
  1689. VList elements are stored in contiguous regions, which improves memory locality
  1690. and leads to more efficient use of hardware caches.
  1691. @end itemize
  1692. The idea behind VLists is to store vlist elements in increasingly large
  1693. contiguous blocks (implemented as vectors here). These blocks are linked to one
  1694. another using a pointer to the next block and an offset within that block. The
  1695. size of these blocks form a geometric series with ratio
  1696. @code{block-growth-factor} (2 by default).
  1697. The VList structure also serves as the basis for the @dfn{VList-based hash
  1698. lists} or ``vhashes'', an immutable dictionary type (@pxref{VHashes}).
  1699. However, the current implementation in @code{(ice-9 vlist)} has several
  1700. noteworthy shortcomings:
  1701. @itemize
  1702. @item
  1703. It is @emph{not} thread-safe. Although operations on vlists are all
  1704. @dfn{referentially transparent} (i.e., purely functional), adding elements to a
  1705. vlist with @code{vlist-cons} mutates part of its internal structure, which makes
  1706. it non-thread-safe. This could be fixed, but it would slow down
  1707. @code{vlist-cons}.
  1708. @item
  1709. @code{vlist-cons} always allocates at least as much memory as @code{cons}.
  1710. Again, Phil Bagwell describes how to fix it, but that would require tuning the
  1711. garbage collector in a way that may not be generally beneficial.
  1712. @item
  1713. @code{vlist-cons} is a Scheme procedure compiled to bytecode, and it does not
  1714. compete with the straightforward C implementation of @code{cons}, and with the
  1715. fact that the VM has a special @code{cons} instruction.
  1716. @end itemize
  1717. We hope to address these in the future.
  1718. The programming interface exported by @code{(ice-9 vlist)} is defined below.
  1719. Most of it is the same as SRFI-1 with an added @code{vlist-} prefix to function
  1720. names.
  1721. @deffn {Scheme Procedure} vlist? obj
  1722. Return true if @var{obj} is a VList.
  1723. @end deffn
  1724. @defvr {Scheme Variable} vlist-null
  1725. The empty VList. Note that it's possible to create an empty VList not
  1726. @code{eq?} to @code{vlist-null}; thus, callers should always use
  1727. @code{vlist-null?} when testing whether a VList is empty.
  1728. @end defvr
  1729. @deffn {Scheme Procedure} vlist-null? vlist
  1730. Return true if @var{vlist} is empty.
  1731. @end deffn
  1732. @deffn {Scheme Procedure} vlist-cons item vlist
  1733. Return a new vlist with @var{item} as its head and @var{vlist} as its tail.
  1734. @end deffn
  1735. @deffn {Scheme Procedure} vlist-head vlist
  1736. Return the head of @var{vlist}.
  1737. @end deffn
  1738. @deffn {Scheme Procedure} vlist-tail vlist
  1739. Return the tail of @var{vlist}.
  1740. @end deffn
  1741. @defvr {Scheme Variable} block-growth-factor
  1742. A fluid that defines the growth factor of VList blocks, 2 by default.
  1743. @end defvr
  1744. The functions below provide the usual set of higher-level list operations.
  1745. @deffn {Scheme Procedure} vlist-fold proc init vlist
  1746. @deffnx {Scheme Procedure} vlist-fold-right proc init vlist
  1747. Fold over @var{vlist}, calling @var{proc} for each element, as for SRFI-1
  1748. @code{fold} and @code{fold-right} (@pxref{SRFI-1, @code{fold}}).
  1749. @end deffn
  1750. @deffn {Scheme Procedure} vlist-ref vlist index
  1751. Return the element at index @var{index} in @var{vlist}. This is typically a
  1752. constant-time operation.
  1753. @end deffn
  1754. @deffn {Scheme Procedure} vlist-length vlist
  1755. Return the length of @var{vlist}. This is typically logarithmic in the number
  1756. of elements in @var{vlist}.
  1757. @end deffn
  1758. @deffn {Scheme Procedure} vlist-reverse vlist
  1759. Return a new @var{vlist} whose content are those of @var{vlist} in reverse
  1760. order.
  1761. @end deffn
  1762. @deffn {Scheme Procedure} vlist-map proc vlist
  1763. Map @var{proc} over the elements of @var{vlist} and return a new vlist.
  1764. @end deffn
  1765. @deffn {Scheme Procedure} vlist-for-each proc vlist
  1766. Call @var{proc} on each element of @var{vlist}. The result is unspecified.
  1767. @end deffn
  1768. @deffn {Scheme Procedure} vlist-drop vlist count
  1769. Return a new vlist that does not contain the @var{count} first elements of
  1770. @var{vlist}. This is typically a constant-time operation.
  1771. @end deffn
  1772. @deffn {Scheme Procedure} vlist-take vlist count
  1773. Return a new vlist that contains only the @var{count} first elements of
  1774. @var{vlist}.
  1775. @end deffn
  1776. @deffn {Scheme Procedure} vlist-filter pred vlist
  1777. Return a new vlist containing all the elements from @var{vlist} that satisfy
  1778. @var{pred}.
  1779. @end deffn
  1780. @deffn {Scheme Procedure} vlist-delete x vlist [equal?]
  1781. Return a new vlist corresponding to @var{vlist} without the elements
  1782. @var{equal?} to @var{x}.
  1783. @end deffn
  1784. @deffn {Scheme Procedure} vlist-unfold p f g seed [tail-gen]
  1785. @deffnx {Scheme Procedure} vlist-unfold-right p f g seed [tail]
  1786. Return a new vlist, as for SRFI-1 @code{unfold} and @code{unfold-right}
  1787. (@pxref{SRFI-1, @code{unfold}}).
  1788. @end deffn
  1789. @deffn {Scheme Procedure} vlist-append vlist @dots{}
  1790. Append the given vlists and return the resulting vlist.
  1791. @end deffn
  1792. @deffn {Scheme Procedure} list->vlist lst
  1793. Return a new vlist whose contents correspond to @var{lst}.
  1794. @end deffn
  1795. @deffn {Scheme Procedure} vlist->list vlist
  1796. Return a new list whose contents match those of @var{vlist}.
  1797. @end deffn
  1798. @node Record Overview
  1799. @subsection Record Overview
  1800. @cindex record
  1801. @cindex structure
  1802. @dfn{Records}, also called @dfn{structures}, are Scheme's primary
  1803. mechanism to define new disjoint types. A @dfn{record type} defines a
  1804. list of @dfn{fields} that instances of the type consist of. This is like
  1805. C's @code{struct}.
  1806. Historically, Guile has offered several different ways to define record
  1807. types and to create records, offering different features, and making
  1808. different trade-offs. Over the years, each ``standard'' has also come
  1809. with its own new record interface, leading to a maze of record APIs.
  1810. At the highest level is SRFI-9, a high-level record interface
  1811. implemented by most Scheme implementations (@pxref{SRFI-9 Records}). It
  1812. defines a simple and efficient syntactic abstraction of record types and
  1813. their associated type predicate, fields, and field accessors. SRFI-9 is
  1814. suitable for most uses, and this is the recommended way to create record
  1815. types in Guile. Similar high-level record APIs include SRFI-35
  1816. (@pxref{SRFI-35}) and R6RS records (@pxref{rnrs records syntactic}).
  1817. Then comes Guile's historical ``records'' API (@pxref{Records}). Record
  1818. types defined this way are first-class objects. Introspection
  1819. facilities are available, allowing users to query the list of fields or
  1820. the value of a specific field at run-time, without prior knowledge of
  1821. the type.
  1822. Finally, the common denominator of these interfaces is Guile's
  1823. @dfn{structure} API (@pxref{Structures}). Guile's structures are the
  1824. low-level building block for all other record APIs. Application writers
  1825. will normally not need to use it.
  1826. Records created with these APIs may all be pattern-matched using Guile's
  1827. standard pattern matcher (@pxref{Pattern Matching}).
  1828. @node SRFI-9 Records
  1829. @subsection SRFI-9 Records
  1830. @cindex SRFI-9
  1831. @cindex record
  1832. SRFI-9 standardizes a syntax for defining new record types and creating
  1833. predicate, constructor, and field getter and setter functions. In Guile
  1834. this is the recommended option to create new record types (@pxref{Record
  1835. Overview}). It can be used with:
  1836. @example
  1837. (use-modules (srfi srfi-9))
  1838. @end example
  1839. @deffn {Scheme Syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
  1840. @sp 1
  1841. Create a new record type, and make various @code{define}s for using
  1842. it. This syntax can only occur at the top-level, not nested within
  1843. some other form.
  1844. @var{type} is bound to the record type, which is as per the return
  1845. from the core @code{make-record-type}. @var{type} also provides the
  1846. name for the record, as per @code{record-type-name}.
  1847. @var{constructor} is bound to a function to be called as
  1848. @code{(@var{constructor} fieldval @dots{})} to create a new record of
  1849. this type. The arguments are initial values for the fields, one
  1850. argument for each field, in the order they appear in the
  1851. @code{define-record-type} form.
  1852. The @var{fieldname}s provide the names for the record fields, as per
  1853. the core @code{record-type-fields} etc, and are referred to in the
  1854. subsequent accessor/modifier forms.
  1855. @var{predicate} is bound to a function to be called as
  1856. @code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
  1857. according to whether @var{obj} is a record of this type.
  1858. Each @var{accessor} is bound to a function to be called
  1859. @code{(@var{accessor} record)} to retrieve the respective field from a
  1860. @var{record}. Similarly each @var{modifier} is bound to a function to
  1861. be called @code{(@var{modifier} record val)} to set the respective
  1862. field in a @var{record}.
  1863. @end deffn
  1864. @noindent
  1865. An example will illustrate typical usage,
  1866. @example
  1867. (define-record-type <employee>
  1868. (make-employee name age salary)
  1869. employee?
  1870. (name employee-name)
  1871. (age employee-age set-employee-age!)
  1872. (salary employee-salary set-employee-salary!))
  1873. @end example
  1874. This creates a new employee data type, with name, age and salary
  1875. fields. Accessor functions are created for each field, but no
  1876. modifier function for the name (the intention in this example being
  1877. that it's established only when an employee object is created). These
  1878. can all then be used as for example,
  1879. @example
  1880. <employee> @result{} #<record-type <employee>>
  1881. (define fred (make-employee "Fred" 45 20000.00))
  1882. (employee? fred) @result{} #t
  1883. (employee-age fred) @result{} 45
  1884. (set-employee-salary! fred 25000.00) ;; pay rise
  1885. @end example
  1886. The functions created by @code{define-record-type} are ordinary
  1887. top-level @code{define}s. They can be redefined or @code{set!} as
  1888. desired, exported from a module, etc.
  1889. @unnumberedsubsubsec Non-toplevel Record Definitions
  1890. The SRFI-9 specification explicitly disallows record definitions in a
  1891. non-toplevel context, such as inside @code{lambda} body or inside a
  1892. @var{let} block. However, Guile's implementation does not enforce that
  1893. restriction.
  1894. @unnumberedsubsubsec Custom Printers
  1895. You may use @code{set-record-type-printer!} to customize the default printing
  1896. behavior of records. This is a Guile extension and is not part of SRFI-9. It
  1897. is located in the @nicode{(srfi srfi-9 gnu)} module.
  1898. @deffn {Scheme Syntax} set-record-type-printer! name proc
  1899. Where @var{type} corresponds to the first argument of @code{define-record-type},
  1900. and @var{proc} is a procedure accepting two arguments, the record to print, and
  1901. an output port.
  1902. @end deffn
  1903. @noindent
  1904. This example prints the employee's name in brackets, for instance @code{[Fred]}.
  1905. @example
  1906. (set-record-type-printer! <employee>
  1907. (lambda (record port)
  1908. (write-char #\[ port)
  1909. (display (employee-name record) port)
  1910. (write-char #\] port)))
  1911. @end example
  1912. @unnumberedsubsubsec Functional ``Setters''
  1913. @cindex functional setters
  1914. When writing code in a functional style, it is desirable to never alter
  1915. the contents of records. For such code, a simple way to return new
  1916. record instances based on existing ones is highly desirable.
  1917. The @code{(srfi srfi-9 gnu)} module extends SRFI-9 with facilities to
  1918. return new record instances based on existing ones, only with one or
  1919. more field values changed---@dfn{functional setters}. First, the
  1920. @code{define-immutable-record-type} works like
  1921. @code{define-record-type}, except that fields are immutable and setters
  1922. are defined as functional setters.
  1923. @deffn {Scheme Syntax} define-immutable-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
  1924. Define @var{type} as a new record type, like @code{define-record-type}.
  1925. However, the record type is made @emph{immutable} (records may not be
  1926. mutated, even with @code{struct-set!}), and any @var{modifier} is
  1927. defined to be a functional setter---a procedure that returns a new
  1928. record instance with the specified field changed, and leaves the
  1929. original unchanged (see example below.)
  1930. @end deffn
  1931. @noindent
  1932. In addition, the generic @code{set-field} and @code{set-fields} macros
  1933. may be applied to any SRFI-9 record.
  1934. @deffn {Scheme Syntax} set-field record (field sub-fields ...) value
  1935. Return a new record of @var{record}'s type whose fields are equal to
  1936. the corresponding fields of @var{record} except for the one specified by
  1937. @var{field}.
  1938. @var{field} must be the name of the getter corresponding to the field of
  1939. @var{record} being ``set''. Subsequent @var{sub-fields} must be record
  1940. getters designating sub-fields within that field value to be set (see
  1941. example below.)
  1942. @end deffn
  1943. @deffn {Scheme Syntax} set-fields record ((field sub-fields ...) value) ...
  1944. Like @code{set-field}, but can be used to set more than one field at a
  1945. time. This expands to code that is more efficient than a series of
  1946. single @code{set-field} calls.
  1947. @end deffn
  1948. To illustrate the use of functional setters, let's assume these two
  1949. record type definitions:
  1950. @example
  1951. (define-record-type <address>
  1952. (address street city country)
  1953. address?
  1954. (street address-street)
  1955. (city address-city)
  1956. (country address-country))
  1957. (define-immutable-record-type <person>
  1958. (person age email address)
  1959. person?
  1960. (age person-age set-person-age)
  1961. (email person-email set-person-email)
  1962. (address person-address set-person-address))
  1963. @end example
  1964. @noindent
  1965. First, note that the @code{<person>} record type definition introduces
  1966. named functional setters. These may be used like this:
  1967. @example
  1968. (define fsf-address
  1969. (address "Franklin Street" "Boston" "USA"))
  1970. (define rms
  1971. (person 30 "rms@@gnu.org" fsf-address))
  1972. (and (equal? (set-person-age rms 60)
  1973. (person 60 "rms@@gnu.org" fsf-address))
  1974. (= (person-age rms) 30))
  1975. @result{} #t
  1976. @end example
  1977. @noindent
  1978. Here, the original @code{<person>} record, to which @var{rms} is bound,
  1979. is left unchanged.
  1980. Now, suppose we want to change both the street and age of @var{rms}.
  1981. This can be achieved using @code{set-fields}:
  1982. @example
  1983. (set-fields rms
  1984. ((person-age) 60)
  1985. ((person-address address-street) "Temple Place"))
  1986. @result{} #<<person> age: 60 email: "rms@@gnu.org"
  1987. address: #<<address> street: "Temple Place" city: "Boston" country: "USA">>
  1988. @end example
  1989. @noindent
  1990. Notice how the above changed two fields of @var{rms}, including the
  1991. @code{street} field of its @code{address} field, in a concise way. Also
  1992. note that @code{set-fields} works equally well for types defined with
  1993. just @code{define-record-type}.
  1994. @node Records
  1995. @subsection Records
  1996. A @dfn{record type} is a first class object representing a user-defined
  1997. data type. A @dfn{record} is an instance of a record type.
  1998. Note that in many ways, this interface is too low-level for every-day
  1999. use. Most uses of records are better served by SRFI-9 records.
  2000. @xref{SRFI-9 Records}.
  2001. @deffn {Scheme Procedure} record? obj
  2002. Return @code{#t} if @var{obj} is a record of any type and @code{#f}
  2003. otherwise.
  2004. Note that @code{record?} may be true of any Scheme value; there is no
  2005. promise that records are disjoint with other Scheme types.
  2006. @end deffn
  2007. @deffn {Scheme Procedure} make-record-type type-name field-names [print]
  2008. Create and return a new @dfn{record-type descriptor}.
  2009. @var{type-name} is a string naming the type. Currently it's only used
  2010. in the printed representation of records, and in diagnostics.
  2011. @var{field-names} is a list of symbols naming the fields of a record
  2012. of the type. Duplicates are not allowed among these symbols.
  2013. @example
  2014. (make-record-type "employee" '(name age salary))
  2015. @end example
  2016. The optional @var{print} argument is a function used by
  2017. @code{display}, @code{write}, etc, for printing a record of the new
  2018. type. It's called as @code{(@var{print} record port)} and should look
  2019. at @var{record} and write to @var{port}.
  2020. @end deffn
  2021. @deffn {Scheme Procedure} record-constructor rtd [field-names]
  2022. Return a procedure for constructing new members of the type represented
  2023. by @var{rtd}. The returned procedure accepts exactly as many arguments
  2024. as there are symbols in the given list, @var{field-names}; these are
  2025. used, in order, as the initial values of those fields in a new record,
  2026. which is returned by the constructor procedure. The values of any
  2027. fields not named in that list are unspecified. The @var{field-names}
  2028. argument defaults to the list of field names in the call to
  2029. @code{make-record-type} that created the type represented by @var{rtd};
  2030. if the @var{field-names} argument is provided, it is an error if it
  2031. contains any duplicates or any symbols not in the default list.
  2032. @end deffn
  2033. @deffn {Scheme Procedure} record-predicate rtd
  2034. Return a procedure for testing membership in the type represented by
  2035. @var{rtd}. The returned procedure accepts exactly one argument and
  2036. returns a true value if the argument is a member of the indicated record
  2037. type; it returns a false value otherwise.
  2038. @end deffn
  2039. @deffn {Scheme Procedure} record-accessor rtd field-name
  2040. Return a procedure for reading the value of a particular field of a
  2041. member of the type represented by @var{rtd}. The returned procedure
  2042. accepts exactly one argument which must be a record of the appropriate
  2043. type; it returns the current value of the field named by the symbol
  2044. @var{field-name} in that record. The symbol @var{field-name} must be a
  2045. member of the list of field-names in the call to @code{make-record-type}
  2046. that created the type represented by @var{rtd}.
  2047. @end deffn
  2048. @deffn {Scheme Procedure} record-modifier rtd field-name
  2049. Return a procedure for writing the value of a particular field of a
  2050. member of the type represented by @var{rtd}. The returned procedure
  2051. accepts exactly two arguments: first, a record of the appropriate type,
  2052. and second, an arbitrary Scheme value; it modifies the field named by
  2053. the symbol @var{field-name} in that record to contain the given value.
  2054. The returned value of the modifier procedure is unspecified. The symbol
  2055. @var{field-name} must be a member of the list of field-names in the call
  2056. to @code{make-record-type} that created the type represented by
  2057. @var{rtd}.
  2058. @end deffn
  2059. @deffn {Scheme Procedure} record-type-descriptor record
  2060. Return a record-type descriptor representing the type of the given
  2061. record. That is, for example, if the returned descriptor were passed to
  2062. @code{record-predicate}, the resulting predicate would return a true
  2063. value when passed the given record. Note that it is not necessarily the
  2064. case that the returned descriptor is the one that was passed to
  2065. @code{record-constructor} in the call that created the constructor
  2066. procedure that created the given record.
  2067. @end deffn
  2068. @deffn {Scheme Procedure} record-type-name rtd
  2069. Return the type-name associated with the type represented by rtd. The
  2070. returned value is @code{eqv?} to the @var{type-name} argument given in
  2071. the call to @code{make-record-type} that created the type represented by
  2072. @var{rtd}.
  2073. @end deffn
  2074. @deffn {Scheme Procedure} record-type-fields rtd
  2075. Return a list of the symbols naming the fields in members of the type
  2076. represented by @var{rtd}. The returned value is @code{equal?} to the
  2077. field-names argument given in the call to @code{make-record-type} that
  2078. created the type represented by @var{rtd}.
  2079. @end deffn
  2080. @node Structures
  2081. @subsection Structures
  2082. @tpindex Structures
  2083. A @dfn{structure} is a first class data type which holds Scheme values
  2084. or C words in fields numbered 0 upwards. A @dfn{vtable} is a structure
  2085. that represents a structure type, giving field types and permissions,
  2086. and an optional print function for @code{write} etc.
  2087. Structures are lower level than records (@pxref{Records}). Usually,
  2088. when you need to represent structured data, you just want to use
  2089. records. But sometimes you need to implement new kinds of structured
  2090. data abstractions, and for that purpose structures are useful. Indeed,
  2091. records in Guile are implemented with structures.
  2092. @menu
  2093. * Vtables::
  2094. * Structure Basics::
  2095. * Vtable Contents::
  2096. * Meta-Vtables::
  2097. * Vtable Example::
  2098. * Tail Arrays::
  2099. @end menu
  2100. @node Vtables
  2101. @subsubsection Vtables
  2102. A vtable is a structure type, specifying its layout, and other
  2103. information. A vtable is actually itself a structure, but there's no
  2104. need to worry about that initially (@pxref{Vtable Contents}.)
  2105. @deffn {Scheme Procedure} make-vtable fields [print]
  2106. Create a new vtable.
  2107. @var{fields} is a string describing the fields in the structures to be
  2108. created. Each field is represented by two characters, a type letter
  2109. and a permissions letter, for example @code{"pw"}. The types are as
  2110. follows.
  2111. @itemize @bullet{}
  2112. @item
  2113. @code{p} -- a Scheme value. ``p'' stands for ``protected'' meaning
  2114. it's protected against garbage collection.
  2115. @item
  2116. @code{u} -- an arbitrary word of data (an @code{scm_t_bits}). At the
  2117. Scheme level it's read and written as an unsigned integer. ``u''
  2118. stands for ``uninterpreted'' (it's not treated as a Scheme value), or
  2119. ``unprotected'' (it's not marked during GC), or ``unsigned long'' (its
  2120. size), or all of these things.
  2121. @item
  2122. @code{s} -- a self-reference. Such a field holds the @code{SCM} value
  2123. of the structure itself (a circular reference). This can be useful in
  2124. C code where you might have a pointer to the data array, and want to
  2125. get the Scheme @code{SCM} handle for the structure. In Scheme code it
  2126. has no use.
  2127. @end itemize
  2128. The second letter for each field is a permission code,
  2129. @itemize @bullet{}
  2130. @item
  2131. @code{w} -- writable, the field can be read and written.
  2132. @item
  2133. @code{r} -- read-only, the field can be read but not written.
  2134. @item
  2135. @code{o} -- opaque, the field can be neither read nor written at the
  2136. Scheme level. This can be used for fields which should only be used
  2137. from C code.
  2138. @end itemize
  2139. Here are some examples. @xref{Tail Arrays}, for information on the
  2140. legacy tail array facility.
  2141. @example
  2142. (make-vtable "pw") ;; one writable field
  2143. (make-vtable "prpw") ;; one read-only and one writable
  2144. (make-vtable "pwuwuw") ;; one scheme and two uninterpreted
  2145. @end example
  2146. The optional @var{print} argument is a function called by
  2147. @code{display} and @code{write} (etc) to give a printed representation
  2148. of a structure created from this vtable. It's called
  2149. @code{(@var{print} struct port)} and should look at @var{struct} and
  2150. write to @var{port}. The default print merely gives a form like
  2151. @samp{#<struct ADDR:ADDR>} with a pair of machine addresses.
  2152. The following print function for example shows the two fields of its
  2153. structure.
  2154. @example
  2155. (make-vtable "prpw"
  2156. (lambda (struct port)
  2157. (format port "#<~a and ~a>"
  2158. (struct-ref struct 0)
  2159. (struct-ref struct 1))))
  2160. @end example
  2161. @end deffn
  2162. @node Structure Basics
  2163. @subsubsection Structure Basics
  2164. This section describes the basic procedures for working with
  2165. structures. @code{make-struct} creates a structure, and
  2166. @code{struct-ref} and @code{struct-set!} access its fields.
  2167. @deffn {Scheme Procedure} make-struct vtable tail-size init @dots{}
  2168. @deffnx {Scheme Procedure} make-struct/no-tail vtable init @dots{}
  2169. Create a new structure, with layout per the given @var{vtable}
  2170. (@pxref{Vtables}).
  2171. The optional @var{init}@dots{} arguments are initial values for the
  2172. fields of the structure. This is the only way to
  2173. put values in read-only fields. If there are fewer @var{init}
  2174. arguments than fields then the defaults are @code{#f} for a Scheme
  2175. field (type @code{p}) or 0 for an uninterpreted field (type @code{u}).
  2176. Structures also have the ability to allocate a variable number of
  2177. additional cells at the end, at their tails. However, this legacy
  2178. @dfn{tail array} facilty is confusing and inefficient, and so we do not
  2179. recommend it. @xref{Tail Arrays}, for more on the legacy tail array
  2180. interface.
  2181. Type @code{s} self-reference fields, permission @code{o} opaque
  2182. fields, and the count field of a tail array are all ignored for the
  2183. @var{init} arguments, ie.@: an argument is not consumed by such a
  2184. field. An @code{s} is always set to the structure itself, an @code{o}
  2185. is always set to @code{#f} or 0 (with the intention that C code will
  2186. do something to it later), and the tail count is always the given
  2187. @var{tail-size}.
  2188. For example,
  2189. @example
  2190. (define v (make-vtable "prpwpw"))
  2191. (define s (make-struct v 0 123 "abc" 456))
  2192. (struct-ref s 0) @result{} 123
  2193. (struct-ref s 1) @result{} "abc"
  2194. @end example
  2195. @end deffn
  2196. @deftypefn {C Function} SCM scm_make_struct (SCM vtable, SCM tail_size, SCM init_list)
  2197. @deftypefnx {C Function} SCM scm_c_make_struct (SCM vtable, SCM tail_size, SCM init, ...)
  2198. @deftypefnx {C Function} SCM scm_c_make_structv (SCM vtable, SCM tail_size, size_t n_inits, scm_t_bits init[])
  2199. There are a few ways to make structures from C. @code{scm_make_struct}
  2200. takes a list, @code{scm_c_make_struct} takes variable arguments
  2201. terminated with SCM_UNDEFINED, and @code{scm_c_make_structv} takes a
  2202. packed array.
  2203. @end deftypefn
  2204. @deffn {Scheme Procedure} struct? obj
  2205. @deffnx {C Function} scm_struct_p (obj)
  2206. Return @code{#t} if @var{obj} is a structure, or @code{#f} if not.
  2207. @end deffn
  2208. @deffn {Scheme Procedure} struct-ref struct n
  2209. @deffnx {C Function} scm_struct_ref (struct, n)
  2210. Return the contents of field number @var{n} in @var{struct}. The
  2211. first field is number 0.
  2212. An error is thrown if @var{n} is out of range, or if the field cannot
  2213. be read because it's @code{o} opaque.
  2214. @end deffn
  2215. @deffn {Scheme Procedure} struct-set! struct n value
  2216. @deffnx {C Function} scm_struct_set_x (struct, n, value)
  2217. Set field number @var{n} in @var{struct} to @var{value}. The first
  2218. field is number 0.
  2219. An error is thrown if @var{n} is out of range, or if the field cannot
  2220. be written because it's @code{r} read-only or @code{o} opaque.
  2221. @end deffn
  2222. @deffn {Scheme Procedure} struct-vtable struct
  2223. @deffnx {C Function} scm_struct_vtable (struct)
  2224. Return the vtable that describes @var{struct}.
  2225. The vtable is effectively the type of the structure. See @ref{Vtable
  2226. Contents}, for more on vtables.
  2227. @end deffn
  2228. @node Vtable Contents
  2229. @subsubsection Vtable Contents
  2230. A vtable is itself a structure. It has a specific set of fields
  2231. describing various aspects of its @dfn{instances}: the structures
  2232. created from a vtable. Some of the fields are internal to Guile, some
  2233. of them are part of the public interface, and there may be additional
  2234. fields added on by the user.
  2235. Every vtable has a field for the layout of their instances, a field for
  2236. the procedure used to print its instances, and a field for the name of
  2237. the vtable itself. Access to the layout and printer is exposed directly
  2238. via field indexes. Access to the vtable name is exposed via accessor
  2239. procedures.
  2240. @defvr {Scheme Variable} vtable-index-layout
  2241. @defvrx {C Macro} scm_vtable_index_layout
  2242. The field number of the layout specification in a vtable. The layout
  2243. specification is a symbol like @code{pwpw} formed from the fields
  2244. string passed to @code{make-vtable}, or created by
  2245. @code{make-struct-layout} (@pxref{Meta-Vtables}).
  2246. @example
  2247. (define v (make-vtable "pwpw" 0))
  2248. (struct-ref v vtable-index-layout) @result{} pwpw
  2249. @end example
  2250. This field is read-only, since the layout of structures using a vtable
  2251. cannot be changed.
  2252. @end defvr
  2253. @defvr {Scheme Variable} vtable-index-printer
  2254. @defvrx {C Macro} scm_vtable_index_printer
  2255. The field number of the printer function. This field contains @code{#f}
  2256. if the default print function should be used.
  2257. @example
  2258. (define (my-print-func struct port)
  2259. ...)
  2260. (define v (make-vtable "pwpw" my-print-func))
  2261. (struct-ref v vtable-index-printer) @result{} my-print-func
  2262. @end example
  2263. This field is writable, allowing the print function to be changed
  2264. dynamically.
  2265. @end defvr
  2266. @deffn {Scheme Procedure} struct-vtable-name vtable
  2267. @deffnx {Scheme Procedure} set-struct-vtable-name! vtable name
  2268. @deffnx {C Function} scm_struct_vtable_name (vtable)
  2269. @deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
  2270. Get or set the name of @var{vtable}. @var{name} is a symbol and is
  2271. used in the default print function when printing structures created
  2272. from @var{vtable}.
  2273. @example
  2274. (define v (make-vtable "pw"))
  2275. (set-struct-vtable-name! v 'my-name)
  2276. (define s (make-struct v 0))
  2277. (display s) @print{} #<my-name b7ab3ae0:b7ab3730>
  2278. @end example
  2279. @end deffn
  2280. @node Meta-Vtables
  2281. @subsubsection Meta-Vtables
  2282. As a structure, a vtable also has a vtable, which is also a structure.
  2283. Structures, their vtables, the vtables of the vtables, and so on form a
  2284. tree of structures. Making a new structure adds a leaf to the tree, and
  2285. if that structure is a vtable, it may be used to create other leaves.
  2286. If you traverse up the tree of vtables, via calling
  2287. @code{struct-vtable}, eventually you reach a root which is the vtable of
  2288. itself:
  2289. @example
  2290. scheme@@(guile-user)> (current-module)
  2291. $1 = #<directory (guile-user) 221b090>
  2292. scheme@@(guile-user)> (struct-vtable $1)
  2293. $2 = #<record-type module>
  2294. scheme@@(guile-user)> (struct-vtable $2)
  2295. $3 = #<<standard-vtable> 12c30a0>
  2296. scheme@@(guile-user)> (struct-vtable $3)
  2297. $4 = #<<standard-vtable> 12c3fa0>
  2298. scheme@@(guile-user)> (struct-vtable $4)
  2299. $5 = #<<standard-vtable> 12c3fa0>
  2300. scheme@@(guile-user)> <standard-vtable>
  2301. $6 = #<<standard-vtable> 12c3fa0>
  2302. @end example
  2303. In this example, we can say that @code{$1} is an instance of @code{$2},
  2304. @code{$2} is an instance of @code{$3}, @code{$3} is an instance of
  2305. @code{$4}, and @code{$4}, strangely enough, is an instance of itself.
  2306. The value bound to @code{$4} in this console session also bound to
  2307. @code{<standard-vtable>} in the default environment.
  2308. @defvr {Scheme Variable} <standard-vtable>
  2309. A meta-vtable, useful for making new vtables.
  2310. @end defvr
  2311. All of these values are structures. All but @code{$1} are vtables. As
  2312. @code{$2} is an instance of @code{$3}, and @code{$3} is a vtable, we can
  2313. say that @code{$3} is a @dfn{meta-vtable}: a vtable that can create
  2314. vtables.
  2315. With this definition, we can specify more precisely what a vtable is: a
  2316. vtable is a structure made from a meta-vtable. Making a structure from
  2317. a meta-vtable runs some special checks to ensure that the first field of
  2318. the structure is a valid layout. Additionally, if these checks see that
  2319. the layout of the child vtable contains all the required fields of a
  2320. vtable, in the correct order, then the child vtable will also be a
  2321. meta-table, inheriting a magical bit from the parent.
  2322. @deffn {Scheme Procedure} struct-vtable? obj
  2323. @deffnx {C Function} scm_struct_vtable_p (obj)
  2324. Return @code{#t} if @var{obj} is a vtable structure: an instance of a
  2325. meta-vtable.
  2326. @end deffn
  2327. @code{<standard-vtable>} is a root of the vtable tree. (Normally there
  2328. is only one root in a given Guile process, but due to some legacy
  2329. interfaces there may be more than one.)
  2330. The set of required fields of a vtable is the set of fields in the
  2331. @code{<standard-vtable>}, and is bound to @code{standard-vtable-fields}
  2332. in the default environment. It is possible to create a meta-vtable that
  2333. with additional fields in its layout, which can be used to create
  2334. vtables with additional data:
  2335. @example
  2336. scheme@@(guile-user)> (struct-ref $3 vtable-index-layout)
  2337. $6 = pruhsruhpwphuhuhprprpw
  2338. scheme@@(guile-user)> (struct-ref $4 vtable-index-layout)
  2339. $7 = pruhsruhpwphuhuh
  2340. scheme@@(guile-user)> standard-vtable-fields
  2341. $8 = "pruhsruhpwphuhuh"
  2342. scheme@@(guile-user)> (struct-ref $2 vtable-offset-user)
  2343. $9 = module
  2344. @end example
  2345. In this continuation of our earlier example, @code{$2} is a vtable that
  2346. has extra fields, because its vtable, @code{$3}, was made from a
  2347. meta-vtable with an extended layout. @code{vtable-offset-user} is a
  2348. convenient definition that indicates the number of fields in
  2349. @code{standard-vtable-fields}.
  2350. @defvr {Scheme Variable} standard-vtable-fields
  2351. A string containing the orderedq set of fields that a vtable must have.
  2352. @end defvr
  2353. @defvr {Scheme Variable} vtable-offset-user
  2354. The first index in a vtable that is available for a user.
  2355. @end defvr
  2356. @deffn {Scheme Procedure} make-struct-layout fields
  2357. @deffnx {C Function} scm_make_struct_layout (fields)
  2358. Return a structure layout symbol, from a @var{fields} string.
  2359. @var{fields} is as described under @code{make-vtable}
  2360. (@pxref{Vtables}). An invalid @var{fields} string is an error.
  2361. @end deffn
  2362. With these definitions, one can define @code{make-vtable} in this way:
  2363. @example
  2364. (define* (make-vtable fields #:optional printer)
  2365. (make-struct/no-tail <standard-vtable>
  2366. (make-struct-layout fields)
  2367. printer))
  2368. @end example
  2369. @node Vtable Example
  2370. @subsubsection Vtable Example
  2371. Let us bring these points together with an example. Consider a simple
  2372. object system with single inheritance. Objects will be normal
  2373. structures, and classes will be vtables with three extra class fields:
  2374. the name of the class, the parent class, and the list of fields.
  2375. So, first we need a meta-vtable that allocates instances with these
  2376. extra class fields.
  2377. @example
  2378. (define <class>
  2379. (make-vtable
  2380. (string-append standard-vtable-fields "pwpwpw")
  2381. (lambda (x port)
  2382. (format port "<<class> ~a>" (class-name x)))))
  2383. (define (class? x)
  2384. (and (struct? x)
  2385. (eq? (struct-vtable x) <class>)))
  2386. @end example
  2387. To make a structure with a specific meta-vtable, we will use
  2388. @code{make-struct/no-tail}, passing it the computed instance layout and
  2389. printer, as with @code{make-vtable}, and additionally the extra three
  2390. class fields.
  2391. @example
  2392. (define (make-class name parent fields)
  2393. (let* ((fields (compute-fields parent fields))
  2394. (layout (compute-layout fields)))
  2395. (make-struct/no-tail <class>
  2396. layout
  2397. (lambda (x port)
  2398. (print-instance x port))
  2399. name
  2400. parent
  2401. fields)))
  2402. @end example
  2403. Instances will store their associated data in slots in the structure: as
  2404. many slots as there are fields. The @code{compute-layout} procedure
  2405. below can compute a layout, and @code{field-index} returns the slot
  2406. corresponding to a field.
  2407. @example
  2408. (define-syntax-rule (define-accessor name n)
  2409. (define (name obj)
  2410. (struct-ref obj n)))
  2411. ;; Accessors for classes
  2412. (define-accessor class-name (+ vtable-offset-user 0))
  2413. (define-accessor class-parent (+ vtable-offset-user 1))
  2414. (define-accessor class-fields (+ vtable-offset-user 2))
  2415. (define (compute-fields parent fields)
  2416. (if parent
  2417. (append (class-fields parent) fields)
  2418. fields))
  2419. (define (compute-layout fields)
  2420. (make-struct-layout
  2421. (string-concatenate (make-list (length fields) "pw"))))
  2422. (define (field-index class field)
  2423. (list-index (class-fields class) field))
  2424. (define (print-instance x port)
  2425. (format port "<~a" (class-name (struct-vtable x)))
  2426. (for-each (lambda (field idx)
  2427. (format port " ~a: ~a" field (struct-ref x idx)))
  2428. (class-fields (struct-vtable x))
  2429. (iota (length (class-fields (struct-vtable x)))))
  2430. (format port ">"))
  2431. @end example
  2432. So, at this point we can actually make a few classes:
  2433. @example
  2434. (define-syntax-rule (define-class name parent field ...)
  2435. (define name (make-class 'name parent '(field ...))))
  2436. (define-class <surface> #f
  2437. width height)
  2438. (define-class <window> <surface>
  2439. x y)
  2440. @end example
  2441. And finally, make an instance:
  2442. @example
  2443. (make-struct/no-tail <window> 400 300 10 20)
  2444. @result{} <<window> width: 400 height: 300 x: 10 y: 20>
  2445. @end example
  2446. And that's that. Note that there are many possible optimizations and
  2447. feature enhancements that can be made to this object system, and the
  2448. included GOOPS system does make most of them. For more simple use
  2449. cases, the records facility is usually sufficient. But sometimes you
  2450. need to make new kinds of data abstractions, and for that purpose,
  2451. structs are here.
  2452. @node Tail Arrays
  2453. @subsubsection Tail Arrays
  2454. Guile's structures have a facility whereby each instance of a vtable can
  2455. contain a variable-length tail array of values. The length of the tail
  2456. array is stored in the structure. This facility was originally intended
  2457. to allow C code to expose raw C structures with word-sized tail arrays
  2458. to Scheme.
  2459. However, the tail array facility is confusing and doesn't work very
  2460. well. It is very rarely used, but it insinuates itself into all
  2461. invocations of @code{make-struct}. For this reason the clumsily-named
  2462. @code{make-struct/no-tail} procedure can actually be more elegant in
  2463. actual use, because it doesn't have a random @code{0} argument stuck in
  2464. the middle.
  2465. Tail arrays also inhibit optimization by allowing instances to affect
  2466. their shapes. In the absence of tail arrays, all instances of a given
  2467. vtable have the same number and kinds of fields. This uniformity can be
  2468. exploited by the runtime and the optimizer. The presence of tail arrays
  2469. make some of these optimizations more difficult.
  2470. Finally, the tail array facility is ad-hoc and does not compose with the
  2471. rest of Guile. If a Guile user wants an array with user-specified
  2472. length, it's best to use a vector. It is more clear in the code, and
  2473. the standard optimization techniques will do a good job with it.
  2474. That said, we should mention some details about the interface. A vtable
  2475. that has tail array has upper-case permission descriptors: @code{W},
  2476. @code{R} or @code{O}, correspoding to tail arrays of writable,
  2477. read-only, or opaque elements. A tail array permission descriptor may
  2478. only appear in the last element of a vtable layout.
  2479. For exampple, @samp{pW} indicates a tail of writable Scheme-valued
  2480. fields. The @samp{pW} field itself holds the tail size, and the tail
  2481. fields come after it.
  2482. @example
  2483. (define v (make-vtable "prpW")) ;; one fixed then a tail array
  2484. (define s (make-struct v 6 "fixed field" 'x 'y))
  2485. (struct-ref s 0) @result{} "fixed field"
  2486. (struct-ref s 1) @result{} 2 ;; tail size
  2487. (struct-ref s 2) @result{} x ;; tail array ...
  2488. (struct-ref s 3) @result{} y
  2489. (struct-ref s 4) @result{} #f
  2490. @end example
  2491. @node Dictionary Types
  2492. @subsection Dictionary Types
  2493. A @dfn{dictionary} object is a data structure used to index
  2494. information in a user-defined way. In standard Scheme, the main
  2495. aggregate data types are lists and vectors. Lists are not really
  2496. indexed at all, and vectors are indexed only by number
  2497. (e.g.@: @code{(vector-ref foo 5)}). Often you will find it useful
  2498. to index your data on some other type; for example, in a library
  2499. catalog you might want to look up a book by the name of its
  2500. author. Dictionaries are used to help you organize information in
  2501. such a way.
  2502. An @dfn{association list} (or @dfn{alist} for short) is a list of
  2503. key-value pairs. Each pair represents a single quantity or
  2504. object; the @code{car} of the pair is a key which is used to
  2505. identify the object, and the @code{cdr} is the object's value.
  2506. A @dfn{hash table} also permits you to index objects with
  2507. arbitrary keys, but in a way that makes looking up any one object
  2508. extremely fast. A well-designed hash system makes hash table
  2509. lookups almost as fast as conventional array or vector references.
  2510. Alists are popular among Lisp programmers because they use only
  2511. the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
  2512. and the equality primitives). No changes to the language core are
  2513. necessary. Therefore, with Scheme's built-in list manipulation
  2514. facilities, it is very convenient to handle data stored in an
  2515. association list. Also, alists are highly portable and can be
  2516. easily implemented on even the most minimal Lisp systems.
  2517. However, alists are inefficient, especially for storing large
  2518. quantities of data. Because we want Guile to be useful for large
  2519. software systems as well as small ones, Guile provides a rich set
  2520. of tools for using either association lists or hash tables.
  2521. @node Association Lists
  2522. @subsection Association Lists
  2523. @tpindex Association Lists
  2524. @tpindex Alist
  2525. @cindex association List
  2526. @cindex alist
  2527. @cindex database
  2528. An association list is a conventional data structure that is often used
  2529. to implement simple key-value databases. It consists of a list of
  2530. entries in which each entry is a pair. The @dfn{key} of each entry is
  2531. the @code{car} of the pair and the @dfn{value} of each entry is the
  2532. @code{cdr}.
  2533. @example
  2534. ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
  2535. (KEY2 . VALUE2)
  2536. (KEY3 . VALUE3)
  2537. @dots{}
  2538. )
  2539. @end example
  2540. @noindent
  2541. Association lists are also known, for short, as @dfn{alists}.
  2542. The structure of an association list is just one example of the infinite
  2543. number of possible structures that can be built using pairs and lists.
  2544. As such, the keys and values in an association list can be manipulated
  2545. using the general list structure procedures @code{cons}, @code{car},
  2546. @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
  2547. because association lists are so useful, Guile also provides specific
  2548. procedures for manipulating them.
  2549. @menu
  2550. * Alist Key Equality::
  2551. * Adding or Setting Alist Entries::
  2552. * Retrieving Alist Entries::
  2553. * Removing Alist Entries::
  2554. * Sloppy Alist Functions::
  2555. * Alist Example::
  2556. @end menu
  2557. @node Alist Key Equality
  2558. @subsubsection Alist Key Equality
  2559. All of Guile's dedicated association list procedures, apart from
  2560. @code{acons}, come in three flavours, depending on the level of equality
  2561. that is required to decide whether an existing key in the association
  2562. list is the same as the key that the procedure call uses to identify the
  2563. required entry.
  2564. @itemize @bullet
  2565. @item
  2566. Procedures with @dfn{assq} in their name use @code{eq?} to determine key
  2567. equality.
  2568. @item
  2569. Procedures with @dfn{assv} in their name use @code{eqv?} to determine
  2570. key equality.
  2571. @item
  2572. Procedures with @dfn{assoc} in their name use @code{equal?} to
  2573. determine key equality.
  2574. @end itemize
  2575. @code{acons} is an exception because it is used to build association
  2576. lists which do not require their entries' keys to be unique.
  2577. @node Adding or Setting Alist Entries
  2578. @subsubsection Adding or Setting Alist Entries
  2579. @code{acons} adds a new entry to an association list and returns the
  2580. combined association list. The combined alist is formed by consing the
  2581. new entry onto the head of the alist specified in the @code{acons}
  2582. procedure call. So the specified alist is not modified, but its
  2583. contents become shared with the tail of the combined alist that
  2584. @code{acons} returns.
  2585. In the most common usage of @code{acons}, a variable holding the
  2586. original association list is updated with the combined alist:
  2587. @example
  2588. (set! address-list (acons name address address-list))
  2589. @end example
  2590. In such cases, it doesn't matter that the old and new values of
  2591. @code{address-list} share some of their contents, since the old value is
  2592. usually no longer independently accessible.
  2593. Note that @code{acons} adds the specified new entry regardless of
  2594. whether the alist may already contain entries with keys that are, in
  2595. some sense, the same as that of the new entry. Thus @code{acons} is
  2596. ideal for building alists where there is no concept of key uniqueness.
  2597. @example
  2598. (set! task-list (acons 3 "pay gas bill" '()))
  2599. task-list
  2600. @result{}
  2601. ((3 . "pay gas bill"))
  2602. (set! task-list (acons 3 "tidy bedroom" task-list))
  2603. task-list
  2604. @result{}
  2605. ((3 . "tidy bedroom") (3 . "pay gas bill"))
  2606. @end example
  2607. @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
  2608. or replace an entry in an association list where there @emph{is} a
  2609. concept of key uniqueness. If the specified association list already
  2610. contains an entry whose key is the same as that specified in the
  2611. procedure call, the existing entry is replaced by the new one.
  2612. Otherwise, the new entry is consed onto the head of the old association
  2613. list to create the combined alist. In all cases, these procedures
  2614. return the combined alist.
  2615. @code{assq-set!} and friends @emph{may} destructively modify the
  2616. structure of the old association list in such a way that an existing
  2617. variable is correctly updated without having to @code{set!} it to the
  2618. value returned:
  2619. @example
  2620. address-list
  2621. @result{}
  2622. (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
  2623. (assoc-set! address-list "james" "1a London Road")
  2624. @result{}
  2625. (("mary" . "34 Elm Road") ("james" . "1a London Road"))
  2626. address-list
  2627. @result{}
  2628. (("mary" . "34 Elm Road") ("james" . "1a London Road"))
  2629. @end example
  2630. Or they may not:
  2631. @example
  2632. (assoc-set! address-list "bob" "11 Newington Avenue")
  2633. @result{}
  2634. (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
  2635. ("james" . "1a London Road"))
  2636. address-list
  2637. @result{}
  2638. (("mary" . "34 Elm Road") ("james" . "1a London Road"))
  2639. @end example
  2640. The only safe way to update an association list variable when adding or
  2641. replacing an entry like this is to @code{set!} the variable to the
  2642. returned value:
  2643. @example
  2644. (set! address-list
  2645. (assoc-set! address-list "bob" "11 Newington Avenue"))
  2646. address-list
  2647. @result{}
  2648. (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
  2649. ("james" . "1a London Road"))
  2650. @end example
  2651. Because of this slight inconvenience, you may find it more convenient to
  2652. use hash tables to store dictionary data. If your application will not
  2653. be modifying the contents of an alist very often, this may not make much
  2654. difference to you.
  2655. If you need to keep the old value of an association list in a form
  2656. independent from the list that results from modification by
  2657. @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
  2658. use @code{list-copy} to copy the old association list before modifying
  2659. it.
  2660. @deffn {Scheme Procedure} acons key value alist
  2661. @deffnx {C Function} scm_acons (key, value, alist)
  2662. Add a new key-value pair to @var{alist}. A new pair is
  2663. created whose car is @var{key} and whose cdr is @var{value}, and the
  2664. pair is consed onto @var{alist}, and the new list is returned. This
  2665. function is @emph{not} destructive; @var{alist} is not modified.
  2666. @end deffn
  2667. @deffn {Scheme Procedure} assq-set! alist key val
  2668. @deffnx {Scheme Procedure} assv-set! alist key value
  2669. @deffnx {Scheme Procedure} assoc-set! alist key value
  2670. @deffnx {C Function} scm_assq_set_x (alist, key, val)
  2671. @deffnx {C Function} scm_assv_set_x (alist, key, val)
  2672. @deffnx {C Function} scm_assoc_set_x (alist, key, val)
  2673. Reassociate @var{key} in @var{alist} with @var{value}: find any existing
  2674. @var{alist} entry for @var{key} and associate it with the new
  2675. @var{value}. If @var{alist} does not contain an entry for @var{key},
  2676. add a new one. Return the (possibly new) alist.
  2677. These functions do not attempt to verify the structure of @var{alist},
  2678. and so may cause unusual results if passed an object that is not an
  2679. association list.
  2680. @end deffn
  2681. @node Retrieving Alist Entries
  2682. @subsubsection Retrieving Alist Entries
  2683. @rnindex assq
  2684. @rnindex assv
  2685. @rnindex assoc
  2686. @code{assq}, @code{assv} and @code{assoc} find the entry in an alist
  2687. for a given key, and return the @code{(@var{key} . @var{value})} pair.
  2688. @code{assq-ref}, @code{assv-ref} and @code{assoc-ref} do a similar
  2689. lookup, but return just the @var{value}.
  2690. @deffn {Scheme Procedure} assq key alist
  2691. @deffnx {Scheme Procedure} assv key alist
  2692. @deffnx {Scheme Procedure} assoc key alist
  2693. @deffnx {C Function} scm_assq (key, alist)
  2694. @deffnx {C Function} scm_assv (key, alist)
  2695. @deffnx {C Function} scm_assoc (key, alist)
  2696. Return the first entry in @var{alist} with the given @var{key}. The
  2697. return is the pair @code{(KEY . VALUE)} from @var{alist}. If there's
  2698. no matching entry the return is @code{#f}.
  2699. @code{assq} compares keys with @code{eq?}, @code{assv} uses
  2700. @code{eqv?} and @code{assoc} uses @code{equal?}. See also SRFI-1
  2701. which has an extended @code{assoc} (@ref{SRFI-1 Association Lists}).
  2702. @end deffn
  2703. @deffn {Scheme Procedure} assq-ref alist key
  2704. @deffnx {Scheme Procedure} assv-ref alist key
  2705. @deffnx {Scheme Procedure} assoc-ref alist key
  2706. @deffnx {C Function} scm_assq_ref (alist, key)
  2707. @deffnx {C Function} scm_assv_ref (alist, key)
  2708. @deffnx {C Function} scm_assoc_ref (alist, key)
  2709. Return the value from the first entry in @var{alist} with the given
  2710. @var{key}, or @code{#f} if there's no such entry.
  2711. @code{assq-ref} compares keys with @code{eq?}, @code{assv-ref} uses
  2712. @code{eqv?} and @code{assoc-ref} uses @code{equal?}.
  2713. Notice these functions have the @var{key} argument last, like other
  2714. @code{-ref} functions, but this is opposite to what @code{assq}
  2715. etc above use.
  2716. When the return is @code{#f} it can be either @var{key} not found, or
  2717. an entry which happens to have value @code{#f} in the @code{cdr}. Use
  2718. @code{assq} etc above if you need to differentiate these cases.
  2719. @end deffn
  2720. @node Removing Alist Entries
  2721. @subsubsection Removing Alist Entries
  2722. To remove the element from an association list whose key matches a
  2723. specified key, use @code{assq-remove!}, @code{assv-remove!} or
  2724. @code{assoc-remove!} (depending, as usual, on the level of equality
  2725. required between the key that you specify and the keys in the
  2726. association list).
  2727. As with @code{assq-set!} and friends, the specified alist may or may not
  2728. be modified destructively, and the only safe way to update a variable
  2729. containing the alist is to @code{set!} it to the value that
  2730. @code{assq-remove!} and friends return.
  2731. @example
  2732. address-list
  2733. @result{}
  2734. (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
  2735. ("james" . "1a London Road"))
  2736. (set! address-list (assoc-remove! address-list "mary"))
  2737. address-list
  2738. @result{}
  2739. (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
  2740. @end example
  2741. Note that, when @code{assq/v/oc-remove!} is used to modify an
  2742. association list that has been constructed only using the corresponding
  2743. @code{assq/v/oc-set!}, there can be at most one matching entry in the
  2744. alist, so the question of multiple entries being removed in one go does
  2745. not arise. If @code{assq/v/oc-remove!} is applied to an association
  2746. list that has been constructed using @code{acons}, or an
  2747. @code{assq/v/oc-set!} with a different level of equality, or any mixture
  2748. of these, it removes only the first matching entry from the alist, even
  2749. if the alist might contain further matching entries. For example:
  2750. @example
  2751. (define address-list '())
  2752. (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
  2753. (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
  2754. address-list
  2755. @result{}
  2756. (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
  2757. (set! address-list (assoc-remove! address-list "mary"))
  2758. address-list
  2759. @result{}
  2760. (("mary" . "11 Elm Street"))
  2761. @end example
  2762. In this example, the two instances of the string "mary" are not the same
  2763. when compared using @code{eq?}, so the two @code{assq-set!} calls add
  2764. two distinct entries to @code{address-list}. When compared using
  2765. @code{equal?}, both "mary"s in @code{address-list} are the same as the
  2766. "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
  2767. after removing the first matching entry that it finds, and so one of the
  2768. "mary" entries is left in place.
  2769. @deffn {Scheme Procedure} assq-remove! alist key
  2770. @deffnx {Scheme Procedure} assv-remove! alist key
  2771. @deffnx {Scheme Procedure} assoc-remove! alist key
  2772. @deffnx {C Function} scm_assq_remove_x (alist, key)
  2773. @deffnx {C Function} scm_assv_remove_x (alist, key)
  2774. @deffnx {C Function} scm_assoc_remove_x (alist, key)
  2775. Delete the first entry in @var{alist} associated with @var{key}, and return
  2776. the resulting alist.
  2777. @end deffn
  2778. @node Sloppy Alist Functions
  2779. @subsubsection Sloppy Alist Functions
  2780. @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
  2781. like the corresponding non-@code{sloppy-} procedures, except that they
  2782. return @code{#f} when the specified association list is not well-formed,
  2783. where the non-@code{sloppy-} versions would signal an error.
  2784. Specifically, there are two conditions for which the non-@code{sloppy-}
  2785. procedures signal an error, which the @code{sloppy-} procedures handle
  2786. instead by returning @code{#f}. Firstly, if the specified alist as a
  2787. whole is not a proper list:
  2788. @example
  2789. (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
  2790. @result{}
  2791. ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
  2792. ERROR: Wrong type argument in position 2 (expecting
  2793. association list): ((1 . 2) ("key" . "door") . "open sesame")
  2794. (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
  2795. @result{}
  2796. #f
  2797. @end example
  2798. @noindent
  2799. Secondly, if one of the entries in the specified alist is not a pair:
  2800. @example
  2801. (assoc 2 '((1 . 1) 2 (3 . 9)))
  2802. @result{}
  2803. ERROR: In procedure assoc in expression (assoc 2 (quote #)):
  2804. ERROR: Wrong type argument in position 2 (expecting
  2805. association list): ((1 . 1) 2 (3 . 9))
  2806. (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
  2807. @result{}
  2808. #f
  2809. @end example
  2810. Unless you are explicitly working with badly formed association lists,
  2811. it is much safer to use the non-@code{sloppy-} procedures, because they
  2812. help to highlight coding and data errors that the @code{sloppy-}
  2813. versions would silently cover up.
  2814. @deffn {Scheme Procedure} sloppy-assq key alist
  2815. @deffnx {C Function} scm_sloppy_assq (key, alist)
  2816. Behaves like @code{assq} but does not do any error checking.
  2817. Recommended only for use in Guile internals.
  2818. @end deffn
  2819. @deffn {Scheme Procedure} sloppy-assv key alist
  2820. @deffnx {C Function} scm_sloppy_assv (key, alist)
  2821. Behaves like @code{assv} but does not do any error checking.
  2822. Recommended only for use in Guile internals.
  2823. @end deffn
  2824. @deffn {Scheme Procedure} sloppy-assoc key alist
  2825. @deffnx {C Function} scm_sloppy_assoc (key, alist)
  2826. Behaves like @code{assoc} but does not do any error checking.
  2827. Recommended only for use in Guile internals.
  2828. @end deffn
  2829. @node Alist Example
  2830. @subsubsection Alist Example
  2831. Here is a longer example of how alists may be used in practice.
  2832. @lisp
  2833. (define capitals '(("New York" . "Albany")
  2834. ("Oregon" . "Salem")
  2835. ("Florida" . "Miami")))
  2836. ;; What's the capital of Oregon?
  2837. (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
  2838. (assoc-ref capitals "Oregon") @result{} "Salem"
  2839. ;; We left out South Dakota.
  2840. (set! capitals
  2841. (assoc-set! capitals "South Dakota" "Pierre"))
  2842. capitals
  2843. @result{} (("South Dakota" . "Pierre")
  2844. ("New York" . "Albany")
  2845. ("Oregon" . "Salem")
  2846. ("Florida" . "Miami"))
  2847. ;; And we got Florida wrong.
  2848. (set! capitals
  2849. (assoc-set! capitals "Florida" "Tallahassee"))
  2850. capitals
  2851. @result{} (("South Dakota" . "Pierre")
  2852. ("New York" . "Albany")
  2853. ("Oregon" . "Salem")
  2854. ("Florida" . "Tallahassee"))
  2855. ;; After Oregon secedes, we can remove it.
  2856. (set! capitals
  2857. (assoc-remove! capitals "Oregon"))
  2858. capitals
  2859. @result{} (("South Dakota" . "Pierre")
  2860. ("New York" . "Albany")
  2861. ("Florida" . "Tallahassee"))
  2862. @end lisp
  2863. @node VHashes
  2864. @subsection VList-Based Hash Lists or ``VHashes''
  2865. @cindex VList-based hash lists
  2866. @cindex VHash
  2867. The @code{(ice-9 vlist)} module provides an implementation of @dfn{VList-based
  2868. hash lists} (@pxref{VLists}). VList-based hash lists, or @dfn{vhashes}, are an
  2869. immutable dictionary type similar to association lists that maps @dfn{keys} to
  2870. @dfn{values}. However, unlike association lists, accessing a value given its
  2871. key is typically a constant-time operation.
  2872. The VHash programming interface of @code{(ice-9 vlist)} is mostly the same as
  2873. that of association lists found in SRFI-1, with procedure names prefixed by
  2874. @code{vhash-} instead of @code{alist-} (@pxref{SRFI-1 Association Lists}).
  2875. In addition, vhashes can be manipulated using VList operations:
  2876. @example
  2877. (vlist-head (vhash-consq 'a 1 vlist-null))
  2878. @result{} (a . 1)
  2879. (define vh1 (vhash-consq 'b 2 (vhash-consq 'a 1 vlist-null)))
  2880. (define vh2 (vhash-consq 'c 3 (vlist-tail vh1)))
  2881. (vhash-assq 'a vh2)
  2882. @result{} (a . 1)
  2883. (vhash-assq 'b vh2)
  2884. @result{} #f
  2885. (vhash-assq 'c vh2)
  2886. @result{} (c . 3)
  2887. (vlist->list vh2)
  2888. @result{} ((c . 3) (a . 1))
  2889. @end example
  2890. However, keep in mind that procedures that construct new VLists
  2891. (@code{vlist-map}, @code{vlist-filter}, etc.) return raw VLists, not vhashes:
  2892. @example
  2893. (define vh (alist->vhash '((a . 1) (b . 2) (c . 3)) hashq))
  2894. (vhash-assq 'a vh)
  2895. @result{} (a . 1)
  2896. (define vl
  2897. ;; This will create a raw vlist.
  2898. (vlist-filter (lambda (key+value) (odd? (cdr key+value))) vh))
  2899. (vhash-assq 'a vl)
  2900. @result{} ERROR: Wrong type argument in position 2
  2901. (vlist->list vl)
  2902. @result{} ((a . 1) (c . 3))
  2903. @end example
  2904. @deffn {Scheme Procedure} vhash? obj
  2905. Return true if @var{obj} is a vhash.
  2906. @end deffn
  2907. @deffn {Scheme Procedure} vhash-cons key value vhash [hash-proc]
  2908. @deffnx {Scheme Procedure} vhash-consq key value vhash
  2909. @deffnx {Scheme Procedure} vhash-consv key value vhash
  2910. Return a new hash list based on @var{vhash} where @var{key} is associated with
  2911. @var{value}, using @var{hash-proc} to compute the hash of @var{key}.
  2912. @var{vhash} must be either @code{vlist-null} or a vhash returned by a previous
  2913. call to @code{vhash-cons}. @var{hash-proc} defaults to @code{hash} (@pxref{Hash
  2914. Table Reference, @code{hash} procedure}). With @code{vhash-consq}, the
  2915. @code{hashq} hash function is used; with @code{vhash-consv} the @code{hashv}
  2916. hash function is used.
  2917. All @code{vhash-cons} calls made to construct a vhash should use the same
  2918. @var{hash-proc}. Failing to do that, the result is undefined.
  2919. @end deffn
  2920. @deffn {Scheme Procedure} vhash-assoc key vhash [equal? [hash-proc]]
  2921. @deffnx {Scheme Procedure} vhash-assq key vhash
  2922. @deffnx {Scheme Procedure} vhash-assv key vhash
  2923. Return the first key/value pair from @var{vhash} whose key is equal to @var{key}
  2924. according to the @var{equal?} equality predicate (which defaults to
  2925. @code{equal?}), and using @var{hash-proc} (which defaults to @code{hash}) to
  2926. compute the hash of @var{key}. The second form uses @code{eq?} as the equality
  2927. predicate and @code{hashq} as the hash function; the last form uses @code{eqv?}
  2928. and @code{hashv}.
  2929. Note that it is important to consistently use the same hash function for
  2930. @var{hash-proc} as was passed to @code{vhash-cons}. Failing to do that, the
  2931. result is unpredictable.
  2932. @end deffn
  2933. @deffn {Scheme Procedure} vhash-delete key vhash [equal? [hash-proc]]
  2934. @deffnx {Scheme Procedure} vhash-delq key vhash
  2935. @deffnx {Scheme Procedure} vhash-delv key vhash
  2936. Remove all associations from @var{vhash} with @var{key}, comparing keys with
  2937. @var{equal?} (which defaults to @code{equal?}), and computing the hash of
  2938. @var{key} using @var{hash-proc} (which defaults to @code{hash}). The second
  2939. form uses @code{eq?} as the equality predicate and @code{hashq} as the hash
  2940. function; the last one uses @code{eqv?} and @code{hashv}.
  2941. Again the choice of @var{hash-proc} must be consistent with previous calls to
  2942. @code{vhash-cons}.
  2943. @end deffn
  2944. @deffn {Scheme Procedure} vhash-fold proc init vhash
  2945. @deffnx {Scheme Procedure} vhash-fold-right proc init vhash
  2946. Fold over the key/value elements of @var{vhash} in the given direction,
  2947. with each call to @var{proc} having the form @code{(@var{proc} key value
  2948. result)}, where @var{result} is the result of the previous call to
  2949. @var{proc} and @var{init} the value of @var{result} for the first call
  2950. to @var{proc}.
  2951. @end deffn
  2952. @deffn {Scheme Procedure} vhash-fold* proc init key vhash [equal? [hash]]
  2953. @deffnx {Scheme Procedure} vhash-foldq* proc init key vhash
  2954. @deffnx {Scheme Procedure} vhash-foldv* proc init key vhash
  2955. Fold over all the values associated with @var{key} in @var{vhash}, with each
  2956. call to @var{proc} having the form @code{(proc value result)}, where
  2957. @var{result} is the result of the previous call to @var{proc} and @var{init} the
  2958. value of @var{result} for the first call to @var{proc}.
  2959. Keys in @var{vhash} are hashed using @var{hash} are compared using @var{equal?}.
  2960. The second form uses @code{eq?} as the equality predicate and @code{hashq} as
  2961. the hash function; the third one uses @code{eqv?} and @code{hashv}.
  2962. Example:
  2963. @example
  2964. (define vh
  2965. (alist->vhash '((a . 1) (a . 2) (z . 0) (a . 3))))
  2966. (vhash-fold* cons '() 'a vh)
  2967. @result{} (3 2 1)
  2968. (vhash-fold* cons '() 'z vh)
  2969. @result{} (0)
  2970. @end example
  2971. @end deffn
  2972. @deffn {Scheme Procedure} alist->vhash alist [hash-proc]
  2973. Return the vhash corresponding to @var{alist}, an association list, using
  2974. @var{hash-proc} to compute key hashes. When omitted, @var{hash-proc} defaults
  2975. to @code{hash}.
  2976. @end deffn
  2977. @node Hash Tables
  2978. @subsection Hash Tables
  2979. @tpindex Hash Tables
  2980. Hash tables are dictionaries which offer similar functionality as
  2981. association lists: They provide a mapping from keys to values. The
  2982. difference is that association lists need time linear in the size of
  2983. elements when searching for entries, whereas hash tables can normally
  2984. search in constant time. The drawback is that hash tables require a
  2985. little bit more memory, and that you can not use the normal list
  2986. procedures (@pxref{Lists}) for working with them.
  2987. @menu
  2988. * Hash Table Examples:: Demonstration of hash table usage.
  2989. * Hash Table Reference:: Hash table procedure descriptions.
  2990. @end menu
  2991. @node Hash Table Examples
  2992. @subsubsection Hash Table Examples
  2993. For demonstration purposes, this section gives a few usage examples of
  2994. some hash table procedures, together with some explanation what they do.
  2995. First we start by creating a new hash table with 31 slots, and
  2996. populate it with two key/value pairs.
  2997. @lisp
  2998. (define h (make-hash-table 31))
  2999. ;; This is an opaque object
  3000. h
  3001. @result{}
  3002. #<hash-table 0/31>
  3003. ;; Inserting into a hash table can be done with hashq-set!
  3004. (hashq-set! h 'foo "bar")
  3005. @result{}
  3006. "bar"
  3007. (hashq-set! h 'braz "zonk")
  3008. @result{}
  3009. "zonk"
  3010. ;; Or with hash-create-handle!
  3011. (hashq-create-handle! h 'frob #f)
  3012. @result{}
  3013. (frob . #f)
  3014. @end lisp
  3015. You can get the value for a given key with the procedure
  3016. @code{hashq-ref}, but the problem with this procedure is that you
  3017. cannot reliably determine whether a key does exists in the table. The
  3018. reason is that the procedure returns @code{#f} if the key is not in
  3019. the table, but it will return the same value if the key is in the
  3020. table and just happens to have the value @code{#f}, as you can see in
  3021. the following examples.
  3022. @lisp
  3023. (hashq-ref h 'foo)
  3024. @result{}
  3025. "bar"
  3026. (hashq-ref h 'frob)
  3027. @result{}
  3028. #f
  3029. (hashq-ref h 'not-there)
  3030. @result{}
  3031. #f
  3032. @end lisp
  3033. Better is to use the procedure @code{hashq-get-handle}, which makes a
  3034. distinction between the two cases. Just like @code{assq}, this
  3035. procedure returns a key/value-pair on success, and @code{#f} if the
  3036. key is not found.
  3037. @lisp
  3038. (hashq-get-handle h 'foo)
  3039. @result{}
  3040. (foo . "bar")
  3041. (hashq-get-handle h 'not-there)
  3042. @result{}
  3043. #f
  3044. @end lisp
  3045. Interesting results can be computed by using @code{hash-fold} to work
  3046. through each element. This example will count the total number of
  3047. elements:
  3048. @lisp
  3049. (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
  3050. @result{}
  3051. 3
  3052. @end lisp
  3053. The same thing can be done with the procedure @code{hash-count}, which
  3054. can also count the number of elements matching a particular predicate.
  3055. For example, count the number of elements with string values:
  3056. @lisp
  3057. (hash-count (lambda (key value) (string? value)) h)
  3058. @result{}
  3059. 2
  3060. @end lisp
  3061. Counting all the elements is a simple task using @code{const}:
  3062. @lisp
  3063. (hash-count (const #t) h)
  3064. @result{}
  3065. 3
  3066. @end lisp
  3067. @node Hash Table Reference
  3068. @subsubsection Hash Table Reference
  3069. @c FIXME: Describe in broad terms what happens for resizing, and what
  3070. @c the initial size means for this.
  3071. Like the association list functions, the hash table functions come in
  3072. several varieties, according to the equality test used for the keys.
  3073. Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
  3074. functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
  3075. the @code{hashx-} functions use an application supplied test.
  3076. A single @code{make-hash-table} creates a hash table suitable for use
  3077. with any set of functions, but it's imperative that just one set is
  3078. then used consistently, or results will be unpredictable.
  3079. Hash tables are implemented as a vector indexed by a hash value formed
  3080. from the key, with an association list of key/value pairs for each
  3081. bucket in case distinct keys hash together. Direct access to the
  3082. pairs in those lists is provided by the @code{-handle-} functions.
  3083. When the number of entries in a hash table goes above a threshold, the
  3084. vector is made larger and the entries are rehashed, to prevent the
  3085. bucket lists from becoming too long and slowing down accesses. When the
  3086. number of entries goes below a threshold, the vector is shrunk to save
  3087. space.
  3088. For the @code{hashx-} ``extended'' routines, an application supplies a
  3089. @var{hash} function producing an integer index like @code{hashq} etc
  3090. below, and an @var{assoc} alist search function like @code{assq} etc
  3091. (@pxref{Retrieving Alist Entries}). Here's an example of such
  3092. functions implementing case-insensitive hashing of string keys,
  3093. @example
  3094. (use-modules (srfi srfi-1)
  3095. (srfi srfi-13))
  3096. (define (my-hash str size)
  3097. (remainder (string-hash-ci str) size))
  3098. (define (my-assoc str alist)
  3099. (find (lambda (pair) (string-ci=? str (car pair))) alist))
  3100. (define my-table (make-hash-table))
  3101. (hashx-set! my-hash my-assoc my-table "foo" 123)
  3102. (hashx-ref my-hash my-assoc my-table "FOO")
  3103. @result{} 123
  3104. @end example
  3105. In a @code{hashx-} @var{hash} function the aim is to spread keys
  3106. across the vector, so bucket lists don't become long. But the actual
  3107. values are arbitrary as long as they're in the range 0 to
  3108. @math{@var{size}-1}. Helpful functions for forming a hash value, in
  3109. addition to @code{hashq} etc below, include @code{symbol-hash}
  3110. (@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
  3111. (@pxref{String Comparison}), and @code{char-set-hash}
  3112. (@pxref{Character Set Predicates/Comparison}).
  3113. @sp 1
  3114. @deffn {Scheme Procedure} make-hash-table [size]
  3115. Create a new hash table object, with an optional minimum
  3116. vector @var{size}.
  3117. When @var{size} is given, the table vector will still grow and shrink
  3118. automatically, as described above, but with @var{size} as a minimum.
  3119. If an application knows roughly how many entries the table will hold
  3120. then it can use @var{size} to avoid rehashing when initial entries are
  3121. added.
  3122. @end deffn
  3123. @deffn {Scheme Procedure} alist->hash-table alist
  3124. @deffnx {Scheme Procedure} alist->hashq-table alist
  3125. @deffnx {Scheme Procedure} alist->hashv-table alist
  3126. @deffnx {Scheme Procedure} alist->hashx-table hash assoc alist
  3127. Convert @var{alist} into a hash table. When keys are repeated in
  3128. @var{alist}, the leftmost association takes precedence.
  3129. @example
  3130. (use-modules (ice-9 hash-table))
  3131. (alist->hash-table '((foo . 1) (bar . 2)))
  3132. @end example
  3133. When converting to an extended hash table, custom @var{hash} and
  3134. @var{assoc} procedures must be provided.
  3135. @example
  3136. (alist->hashx-table hash assoc '((foo . 1) (bar . 2)))
  3137. @end example
  3138. @end deffn
  3139. @deffn {Scheme Procedure} hash-table? obj
  3140. @deffnx {C Function} scm_hash_table_p (obj)
  3141. Return @code{#t} if @var{obj} is a abstract hash table object.
  3142. @end deffn
  3143. @deffn {Scheme Procedure} hash-clear! table
  3144. @deffnx {C Function} scm_hash_clear_x (table)
  3145. Remove all items from @var{table} (without triggering a resize).
  3146. @end deffn
  3147. @deffn {Scheme Procedure} hash-ref table key [dflt]
  3148. @deffnx {Scheme Procedure} hashq-ref table key [dflt]
  3149. @deffnx {Scheme Procedure} hashv-ref table key [dflt]
  3150. @deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
  3151. @deffnx {C Function} scm_hash_ref (table, key, dflt)
  3152. @deffnx {C Function} scm_hashq_ref (table, key, dflt)
  3153. @deffnx {C Function} scm_hashv_ref (table, key, dflt)
  3154. @deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
  3155. Lookup @var{key} in the given hash @var{table}, and return the
  3156. associated value. If @var{key} is not found, return @var{dflt}, or
  3157. @code{#f} if @var{dflt} is not given.
  3158. @end deffn
  3159. @deffn {Scheme Procedure} hash-set! table key val
  3160. @deffnx {Scheme Procedure} hashq-set! table key val
  3161. @deffnx {Scheme Procedure} hashv-set! table key val
  3162. @deffnx {Scheme Procedure} hashx-set! hash assoc table key val
  3163. @deffnx {C Function} scm_hash_set_x (table, key, val)
  3164. @deffnx {C Function} scm_hashq_set_x (table, key, val)
  3165. @deffnx {C Function} scm_hashv_set_x (table, key, val)
  3166. @deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
  3167. Associate @var{val} with @var{key} in the given hash @var{table}. If
  3168. @var{key} is already present then it's associated value is changed.
  3169. If it's not present then a new entry is created.
  3170. @end deffn
  3171. @deffn {Scheme Procedure} hash-remove! table key
  3172. @deffnx {Scheme Procedure} hashq-remove! table key
  3173. @deffnx {Scheme Procedure} hashv-remove! table key
  3174. @deffnx {Scheme Procedure} hashx-remove! hash assoc table key
  3175. @deffnx {C Function} scm_hash_remove_x (table, key)
  3176. @deffnx {C Function} scm_hashq_remove_x (table, key)
  3177. @deffnx {C Function} scm_hashv_remove_x (table, key)
  3178. @deffnx {C Function} scm_hashx_remove_x (hash, assoc, table, key)
  3179. Remove any association for @var{key} in the given hash @var{table}.
  3180. If @var{key} is not in @var{table} then nothing is done.
  3181. @end deffn
  3182. @deffn {Scheme Procedure} hash key size
  3183. @deffnx {Scheme Procedure} hashq key size
  3184. @deffnx {Scheme Procedure} hashv key size
  3185. @deffnx {C Function} scm_hash (key, size)
  3186. @deffnx {C Function} scm_hashq (key, size)
  3187. @deffnx {C Function} scm_hashv (key, size)
  3188. Return a hash value for @var{key}. This is a number in the range
  3189. @math{0} to @math{@var{size}-1}, which is suitable for use in a hash
  3190. table of the given @var{size}.
  3191. Note that @code{hashq} and @code{hashv} may use internal addresses of
  3192. objects, so if an object is garbage collected and re-created it can
  3193. have a different hash value, even when the two are notionally
  3194. @code{eq?}. For instance with symbols,
  3195. @example
  3196. (hashq 'something 123) @result{} 19
  3197. (gc)
  3198. (hashq 'something 123) @result{} 62
  3199. @end example
  3200. In normal use this is not a problem, since an object entered into a
  3201. hash table won't be garbage collected until removed. It's only if
  3202. hashing calculations are somehow separated from normal references that
  3203. its lifetime needs to be considered.
  3204. @end deffn
  3205. @deffn {Scheme Procedure} hash-get-handle table key
  3206. @deffnx {Scheme Procedure} hashq-get-handle table key
  3207. @deffnx {Scheme Procedure} hashv-get-handle table key
  3208. @deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
  3209. @deffnx {C Function} scm_hash_get_handle (table, key)
  3210. @deffnx {C Function} scm_hashq_get_handle (table, key)
  3211. @deffnx {C Function} scm_hashv_get_handle (table, key)
  3212. @deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
  3213. Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
  3214. given hash @var{table}, or @code{#f} if @var{key} is not in
  3215. @var{table}.
  3216. @end deffn
  3217. @deffn {Scheme Procedure} hash-create-handle! table key init
  3218. @deffnx {Scheme Procedure} hashq-create-handle! table key init
  3219. @deffnx {Scheme Procedure} hashv-create-handle! table key init
  3220. @deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
  3221. @deffnx {C Function} scm_hash_create_handle_x (table, key, init)
  3222. @deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
  3223. @deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
  3224. @deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
  3225. Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
  3226. given hash @var{table}. If @var{key} is not in @var{table} then
  3227. create an entry for it with @var{init} as the value, and return that
  3228. pair.
  3229. @end deffn
  3230. @deffn {Scheme Procedure} hash-map->list proc table
  3231. @deffnx {Scheme Procedure} hash-for-each proc table
  3232. @deffnx {C Function} scm_hash_map_to_list (proc, table)
  3233. @deffnx {C Function} scm_hash_for_each (proc, table)
  3234. Apply @var{proc} to the entries in the given hash @var{table}. Each
  3235. call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map->list}
  3236. returns a list of the results from these calls, @code{hash-for-each}
  3237. discards the results and returns an unspecified value.
  3238. Calls are made over the table entries in an unspecified order, and for
  3239. @code{hash-map->list} the order of the values in the returned list is
  3240. unspecified. Results will be unpredictable if @var{table} is modified
  3241. while iterating.
  3242. For example the following returns a new alist comprising all the
  3243. entries from @code{mytable}, in no particular order.
  3244. @example
  3245. (hash-map->list cons mytable)
  3246. @end example
  3247. @end deffn
  3248. @deffn {Scheme Procedure} hash-for-each-handle proc table
  3249. @deffnx {C Function} scm_hash_for_each_handle (proc, table)
  3250. Apply @var{proc} to the entries in the given hash @var{table}. Each
  3251. call is @code{(@var{proc} @var{handle})}, where @var{handle} is a
  3252. @code{(@var{key} . @var{value})} pair. Return an unspecified value.
  3253. @code{hash-for-each-handle} differs from @code{hash-for-each} only in
  3254. the argument list of @var{proc}.
  3255. @end deffn
  3256. @deffn {Scheme Procedure} hash-fold proc init table
  3257. @deffnx {C Function} scm_hash_fold (proc, init, table)
  3258. Accumulate a result by applying @var{proc} to the elements of the
  3259. given hash @var{table}. Each call is @code{(@var{proc} @var{key}
  3260. @var{value} @var{prior-result})}, where @var{key} and @var{value} are
  3261. from the @var{table} and @var{prior-result} is the return from the
  3262. previous @var{proc} call. For the first call, @var{prior-result} is
  3263. the given @var{init} value.
  3264. Calls are made over the table entries in an unspecified order.
  3265. Results will be unpredictable if @var{table} is modified while
  3266. @code{hash-fold} is running.
  3267. For example, the following returns a count of how many keys in
  3268. @code{mytable} are strings.
  3269. @example
  3270. (hash-fold (lambda (key value prior)
  3271. (if (string? key) (1+ prior) prior))
  3272. 0 mytable)
  3273. @end example
  3274. @end deffn
  3275. @deffn {Scheme Procedure} hash-count pred table
  3276. @deffnx {C Function} scm_hash_count (pred, table)
  3277. Return the number of elements in the given hash @var{table} that cause
  3278. @code{(@var{pred} @var{key} @var{value})} to return true. To quickly
  3279. determine the total number of elements, use @code{(const #t)} for
  3280. @var{pred}.
  3281. @end deffn
  3282. @c Local Variables:
  3283. @c TeX-master: "guile.texi"
  3284. @c End: