api-compound.texi 146 KB

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