api-compound.texi 135 KB

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