primer.tex 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386
  1. \documentstyle[11pt,makeidx]{article}
  2. \newcommand{\reduce}{\small REDUCE}
  3. \newcommand{\ttindex}[1]{\index{#1@{\tt #1}}}
  4. \title{REDUCE Symbolic Mode Primer}
  5. \date{}
  6. \author{
  7. H. Melenk \\[0.05in]
  8. Konrad--Zuse--Zentrum \\
  9. f\"ur Informationstechnik Berlin \\
  10. Takustrasse 7 \\
  11. 14195 Berlin-Dahlem \\
  12. Germany \\[0.05in]
  13. Email: melenk@zib.de \\[0.05in]}
  14. \makeindex
  15. \begin{document}
  16. \maketitle
  17. \section{Introduction}
  18. This document should explain some essential technical details for
  19. symbolic mode programming in {\reduce} for those who
  20. have some experience in {\reduce} algebraic programming
  21. and need to write a program in symbolic mode. For a general
  22. introduction to {\reduce} please consult the {\reduce} User's
  23. Manual or one of the available books, e.g.\ ``Algebraic
  24. computing with REDUCE" by Malcolm MacCallum and Francis
  25. Wright (Oxford Press).
  26. This text cannot be complete, as the set of facilities
  27. available in {\reduce} is so rich that it would take years
  28. to describe all and months to read and understand such text.
  29. So a good policy for entering the business of symbolic mode
  30. programming is to study the source files - the
  31. liberal {\reduce} distribution policy simplifies this -
  32. and to understand those parts which contribute to the
  33. field which one would like to use. This text tries to
  34. collect in one place some of the wide spread basic information
  35. in order to facilitate your walk through the {\reduce} mountains.
  36. When should you write a program in symbolic mode?
  37. Symbolic programs are not {\it a priori} better than algebraic
  38. programs - the essential thing is the mathematics which they
  39. implement. A common prejudice is that symbolic programs
  40. are more ``efficient". This is true only if you can
  41. save in symbolic mode substantial algebraic evaluation
  42. steps. As long as most of the
  43. computing time is needed for a few big calculations steps
  44. (integrals, equation solving, polynomial gcd etc.)
  45. you will gain nothing when calling the same procedures
  46. from symbolic mode. However, if you need structures
  47. which are not present in algebraic mode or if you
  48. can design an evaluation avoiding lots of conversions,
  49. the step to symbolic mode programming is justified.
  50. As it is very difficult to design non trivial but short
  51. examples for symbolic mathematical programming no
  52. attempt has been made in that direction. The examples
  53. in this text all are silly - please look at the
  54. sources of {\reduce} for meaningful material. The following pieces
  55. of the sources are good points for first reading as they
  56. provide a substantial functionality within a few pages
  57. of code:
  58. \begin{enumerate}
  59. \item module {\tt polrep} in package {\tt poly}: routines
  60. addf, addd and addm, the heart of standard form and
  61. standard quotient arithmetic,
  62. \item module {\tt det} of package {\tt matrix}: internal
  63. arithmetic with symbolic entities (standard quotients)
  64. and clever local data structure,
  65. \item module {\tt rational} in package {\tt poly}: implementation
  66. of a typical {\reduce} domain,
  67. \item module {\tt maxmin} in package {\tt alg}: a typical
  68. simplification routine for an operator,
  69. \item module {\tt algbool} in package {\tt alg}: demonstrates
  70. how to supply ``small" pieces of symbolic code for
  71. algebraic use.
  72. \end{enumerate}
  73. For symbolic mode programming you will urgently need the
  74. {\em Standard LISP Report} which describes
  75. the basic LISP functions; these will be available under all
  76. {\reduce} implementations and they guarantee an optimum
  77. of portability. However, in the course of the
  78. years {\reduce} has imported some additional functions on the
  79. LISP level -- they have been implemented on top of Standard LISP
  80. and live in the module {\tt support}\index{support} of
  81. the package {\tt rlisp.red}.
  82. In order to prevent the reinvention of the wheel these functions
  83. are described in the appendix as an extension to the
  84. {\em Standard LISP Report}.
  85. The description is based on the recent version of REDUCE. Some of the
  86. described features are not available in earlier versions.
  87. \section{Very short course on RLISP}
  88. \subsection{What is RLISP}
  89. As you will know {\reduce} is based on the programming
  90. language LISP, or to be more exact, on the LISP dialect
  91. {\tt Standard LISP}. Fortunately
  92. \ttindex{LISP} \ttindex{Standard LISP}
  93. you need not learn the syntax of this language with its
  94. large number of brackets - the {\reduce}
  95. language is used for algebraic programming as well as
  96. for symbolic programs and in that mode it allows you to
  97. use all of the rich LISP data structures. It is LISP
  98. semantics in high level {\reduce} syntax. In the following
  99. it is expected that you are familiar with the {\reduce}
  100. programming language as far as it is used for algebraic
  101. mode programs. You should know how to write a (recursive) procedure
  102. with parameters and local variables, how to build loops,
  103. while blocks, {\tt if-then-else} clauses and {\tt begin-end} resp $<< - >>$
  104. blocks. If not, please study the {\reduce} manual first
  105. or have a look at the source files of the {\reduce}
  106. kernel - this is the best method for learning how to
  107. program in RLISP.
  108. \subsection{Modes, function classes}
  109. The symbols {\tt symbolic} (or equivalent {\tt lisp})
  110. \ttindex{symbolic} \ttindex{LISP}
  111. and {\tt algebraic} \ttindex{algebraic}
  112. play a double role: as a statement
  113. they switch the evaluation mode globally to {\em symbolic}
  114. or {\em algebraic mode} respectively, as a {\em mode prefix}
  115. \index{mode prefix} they tell the
  116. {\reduce} evaluator that one isolated evaluation should
  117. be done in the named mode. The scope of this prefix use
  118. can be rather narrow (e.g.\ one single expression) or
  119. cover a larger piece of code up to a complete procedure.
  120. Typically procedures in symbolic modules should be tagged
  121. ``symbolic" explicitly although this might be redundant
  122. information in a totally symbolic context. If a procedure
  123. needs an evaluation mode different from the actual global
  124. one the {\em mode prefix} must be set.
  125. In symbolic mode there are two additional procedure types
  126. available, {\tt macro} \ttindex{macro} and {\tt smacro}\ttindex{smacro}.
  127. The discussion of {\tt macro}s is beyond the scope of
  128. this document - their use requires extensive knowledge of
  129. LISP. On the other hand {\tt smacro}s are frequently use
  130. in {\reduce} and you will see lots of them in the sources.
  131. An {\tt smacro} (an abbreviation for ``substitution macro")
  132. is an ordinary procedure tagged with
  133. the symbol ``smacro" and usually with a rather small body.
  134. At source read time (or better: at {\reduce} translator
  135. time) any call for an {\tt smacro} will be replaced
  136. literally by the body of the {\tt smacro} procedure
  137. which saves execution time for the call protocol at
  138. run time. So the purpose of {\tt smacro}s is twofold:
  139. encapsulation of frequently used pieces of code and
  140. an increased efficiency (avoiding function calls).
  141. Example:
  142. \begin{verbatim}
  143. smacro procedure my_diff(x,y); x-y;
  144. symbolic procedure hugo(a,b); my_diff(a,b);
  145. \end{verbatim}
  146. Here the formal function call {\em my\_diff} in the
  147. procedure literally is replaced by the body of the
  148. {\tt smacro} where $x$ and $y$ are replaced by $a$ and
  149. $b$. Obviously this translation can be done only if
  150. the {\tt smacro} declaration is entered in a {\reduce}
  151. session before the first reference. And later changes
  152. of an {\tt smacro} don't affect previously translated
  153. references.
  154. Sometimes in older {\reduce} sources you will find
  155. the symbol {\tt expr}\ttindex{expr} in front of a procedure declaration.
  156. This is more or less useless as the absence of {\tt macro}
  157. or {\tt smacro} symbols indicates that a procedure is
  158. of type {\tt expr} - the default Standard LISP procedure type.
  159. \subsection{Evaluation model, symbols, and variables}
  160. The main difference between algebraic and symbolic
  161. mode lies in the {\tt evaluation model}\ttindex{evaluation model}:
  162. \begin{itemize}
  163. \item In algebraic mode a symbol stands for itself
  164. as unknown as long as no value is assigned; after
  165. an assignment it plays the role of a representative
  166. for that value just like a variable in a standard
  167. programming language:
  168. \begin{verbatim}
  169. 1: x;
  170. X
  171. 2: x:=y+1$
  172. 3: x;
  173. Y + 1
  174. \end{verbatim}
  175. In symbolic mode there
  176. is a clear barrier between the role of a symbol as
  177. variable of the programming language RLISP,
  178. a named item which represents some variable value,
  179. and the role to be part of an algebraic expression. If you mean
  180. the {\em symbol x} you must write $'x$; without
  181. the quote tag $x$ is considered as {\em variable x}
  182. and it will be asked for its value which is NOT $'x$
  183. initially. Uninitialized variables cause bugs.
  184. \item Consequently all variables {\tt must be
  185. declared}.
  186. \item In algebraic mode $u:=(x+1)^\wedge 2;$
  187. \footnote{In this text the caret symbol ``$^\wedge$" is
  188. used for exponentiation instead of the older
  189. FORTRAN like operator ``**".}
  190. means {it compute a formula by expanding (x+1)*(x+1);
  191. if a value had been assigned to x, substitute the value for x}.
  192. In symbolic mode an algebraic expression is interpreted
  193. as statement to compute a numeric value, just like in {\em C}
  194. or {\em Pascal}.
  195. So $u:=(x+1) ^\wedge 2;$ in symbolic mode means: ``take the
  196. value of variable $x$ which is expected to be number,
  197. add 1, square and assign the resulting number to
  198. the variable $u$".
  199. \item If you want to refer to an
  200. {\tt algebraic expression} as a data object, you
  201. must code it as an {\tt algebraic form}\index{algebraic form}
  202. (see below)
  203. and mark it as {\tt constant}\ttindex{constant}
  204. by a {\tt quote}\ttindex{quote}
  205. character. The only constants which don't need a
  206. {\tt quote} are numbers and strings.
  207. Example:
  208. \begin{verbatim}
  209. u:='(expt (plus x 1) 2);
  210. \end{verbatim}
  211. assigns the (algebraic) expression $(x+1)^\wedge 2$ to the variable $u$.
  212. \item algebraic mode implicitly supports standard arithmetic
  213. and algebraic evaluation
  214. for mathematical expressions of arbitrary complexity and
  215. for numbers from various domains. In symbolic mode,
  216. arithmetic with infix operators $+\,-\,*\, ^\wedge \,/$
  217. is supported only for the basic LISP numbers
  218. (mainly integers). All arithmetic for formulas, even
  219. for domain elements such as rounded numbers, complex
  220. numbers etc. has to be performed by calling explicitly
  221. the functions which can do that job or by calling
  222. explicitly the {\reduce} evaluator {\tt reval}\index{reval}
  223. resp {\tt aeval}\index{aeval} (see below).
  224. \end{itemize}
  225. So symbolic mode programs are much more similar to
  226. programs in conventional programming languages such as
  227. Pascal or C. All algebraic functionality of {\reduce} is
  228. available only as an explicit subroutine interface.
  229. In contrast to algebraic mode nothing is done implicitly
  230. for you.
  231. \subsection{Variable types}
  232. RLISP supports in symbolic mode the following classes of variables:
  233. \begin{itemize}
  234. \item {\tt Local variables}\index{local variables} in a procedure are
  235. those
  236. \begin{itemize}
  237. \item declared in the parameter list,
  238. \item declared in a {\tt scalar}\ttindex{scalar}
  239. or {\tt integer}\ttindex{integer}
  240. statement in a begin-end block,
  241. \item bound in the right-hand side of a {\tt where statement}
  242. \item implicitly introduced in a {\tt for statement}
  243. \ttindex{for statement}.
  244. \end{itemize}
  245. These are
  246. valid only inside their local context. {\tt scalar} variables
  247. are initialized to $nil$, {\tt integer} to 0 unless they
  248. have a special initialization value (property {\tt initvalue*}
  249. \index{initvalue*}).
  250. \begin{verbatim}
  251. symbolic procedure my_adder(x,y);
  252. begin integer r;
  253. r:=x+y;
  254. return r:
  255. end;
  256. \end{verbatim}
  257. In this routine $x$,$y$ and $r$ are local variables.
  258. In algebraic mode the {\tt where} statment is used to activate
  259. one more more rules locally. In symbolic mode mode only rules
  260. of the form \verb+<name>=<value>+ are allowed the the right-hand
  261. side of a {\tt where} statement.
  262. \item {\tt Global}\index{global} variables have to be declared
  263. in a statement $global\, '(v_1\,v_2\,\cdots);$ These
  264. can be accessed from everywhere once they have been
  265. declared. Important: declare them before you use
  266. them for the first time in a session. They are
  267. initially set to $nil$.
  268. \begin{verbatim}
  269. global '(my_support!* my_quotient!*);
  270. \end{verbatim}
  271. It is a common practice to use a trailing asterisk in names
  272. for global and fluid variables such that they easily
  273. can be distinguished from locals. Names of global variables
  274. may not be used as local variables.
  275. \item {\tt Fluid}\ttindex{fluid} variables are similar to global
  276. variables as they can be accessed from everywhere. But
  277. in contrast to globals a {\tt fluid} variable can occur as a local
  278. variable in a procedure. It then has temporarily the value
  279. assigned in the procedure (we say ``it is rebound");
  280. this value will be accessible globally by nested procedures
  281. as long as the rebinding procedure is not yet terminated.
  282. After termination the previous value is reassigned.
  283. Fluid variables are declared in a statement
  284. $fluid\,'(v_1\,v_2\,\cdots);$. Like global variables they
  285. must be declared before use and they are initially set to $nil$.
  286. \begin{verbatim}
  287. fluid '(my_var!*);
  288. my_var!*:='x;
  289. procedure compute(ex,my_var!*);
  290. do_some_work(ex);
  291. \end{verbatim}
  292. In this case the variable $my\_var*$ has been initialized
  293. to the symbol $x$. If then a call $compute('a,'z)$ is
  294. performed, the variable $my\_var*$ will be set to $z$
  295. during the execution of the body of $compute$.
  296. \item A {\tt switch}\ttindex{switch} can be declared using the
  297. {\tt switch} statement $switch\,s_1,s_2\cdots;$ where
  298. $s_1,s_2,\cdots$ are symbols. {\reduce}
  299. automatically connects a fluid variable with each switch
  300. by prefixing an asterisk to the symbol name. This variable
  301. represents the $value$ of the switch, which is either
  302. $nil$ or $t$ and is set by the statements {\tt on}\ttindex{on} and
  303. {\tt off}\ttindex{off}.
  304. E.g.\ the switch $nat$ has the associated global variable
  305. $*nat$.
  306. \item {\tt share}\ttindex{share} variables are also global variables
  307. which are handled specially by the {\reduce} evaluator
  308. such that their symbolic mode values are identical with their
  309. role as symbols in algebraic mode.
  310. \end{itemize}
  311. \subsection{Symbols, numbers and strings}
  312. A {\tt symbol}\ttindex{symbol} or {\tt id}\ttindex{id}
  313. \footnote{``id" is an abbreviation for ``identifier".}
  314. in LISP is a unit which has a name, in the standard
  315. case beginning with a letter and followed by letters and digits.
  316. Special characters in a name or a leading digit have to be
  317. flagged by a preceding exclamation mark. Symbols are the same
  318. entities as in algebraic mode. Symbols
  319. are unique in the system. You may view a symbol as a data
  320. structure with four slots, the {\it name} with is always a string,
  321. the {\it value cell} to store assigned values,
  322. the {\it function cell}
  323. \footnote{There are LISP systems which support only one cell
  324. for value and function -- in such systems a symbol can represent
  325. only a variable or a function exclusively.}
  326. to point to an assigned program structure
  327. and the {\it property cell} as anchor of the property list.
  328. Initially all cells except the name cell are marked empty.
  329. In contrast to algebraic mode in LISP, only integers and
  330. floating point numbers (which don't exist in that form
  331. in algebraic mode) are considered as numbers. All other
  332. numeric quantities from algebraic mode such as rationals, rounded numbers,
  333. Gaussian integers are composite data structures encoded in
  334. the {\reduce} domain structure (see below).
  335. Just as in algebraic mode, a sequence of characters enclosed
  336. in string quotes is a string. Functions for manipulating symbols,
  337. numbers and strings
  338. are\footnote{Read the trailing $p$ in names like ``idp", ``numberp" etc.
  339. as ``predicate", e.g.\ ``numberp" meaning ``number predicate".}:
  340. \begin{center}
  341. \begin{tabular}{|r|l|} \hline
  342. idp(q) & true if q is a symbol \\
  343. numberp(q) & true if q is a number \\
  344. stringp(q) & true if q is a string \\
  345. liter(q) & true if q is a single alphabetic character symbol\\
  346. digit(q) & true if a is a digit character symbol\\
  347. intern(s) & make a symbol from a string \\
  348. explode(a) & decompose a symbol/number/string into its characters \\
  349. explode2(a)& explode, but without escape characters\\
  350. compress(l)& make a symbol/number/string from a list of characters \\
  351. gensym() & generate a new symbol\\
  352. \hline
  353. \end{tabular}
  354. \end{center}
  355. \ttindex{idp}\ttindex{numberp}\ttindex{stringp}
  356. \ttindex{intern}\ttindex{explode}\ttindex{compress}\ttindex{gensym}
  357. \ttindex{liter}\ttindex{digit}
  358. The functions {\tt gensym} and {\tt compress} make symbols which are
  359. not yet ``internal": they are unique, but there may be
  360. other symbols with the same name.
  361. It makes debugging especially hard if you cannot
  362. access the symbol by its name of course. The function {\tt intern}
  363. can be used to convert such a symbol into an internal one -
  364. then every reference to the symbol name guarantees
  365. access to the desired object.
  366. \subsection{Boolean values}
  367. There are two special symbols named $nil$ and $t$. $nil$ is
  368. used at the same time for the empty list and the Boolean
  369. value ``false" \ttindex{false} \ttindex{true} \ttindex{Boolean value}.
  370. Any value other than $nil$ is considered as
  371. ``true" in conditional statements. In order to facilitate programming,
  372. the symbol $nil$ has the preassigned constant value $nil$ such
  373. that a quote here is superfluous. And for the same reason
  374. the symbol $t$ evaluates to itself
  375. - this symbol can be used if the Boolean value ``true"
  376. is needed explicitly, e.g. as a return value. But please keep
  377. in mind that any non-$nil$ value can play this role. In contrast to
  378. algebraic mode the number zero does {\bf not} represent the
  379. Boolean value ``false".
  380. \subsubsection{Pairs, lists}
  381. The central structure of LISP is the {\tt pair}\ttindex{pair}.
  382. The external representation of a pair of two objects
  383. is $( obj_1 . obj_2)$. Here the infix dot is used
  384. as print symbol as well as infix constructor.
  385. It is often useful to use a double box for
  386. representing a pair graphically, e.g.\ for $(10\, . \,20)$:
  387. {\nopagebreak[3]
  388. \begin{verbatim}
  389. .---------.
  390. | 10 | 20 |
  391. `---------'
  392. \end{verbatim}
  393. }
  394. Functions:
  395. \begin{center}
  396. \begin{tabular}{|r|l|} \hline
  397. o1.o2 & (infix) construct pair $(o_1 . o_2)$ \\
  398. cons(o1,o2) & same as 01.02 \\
  399. pairp(q) & true if q is a pair \\
  400. car(q) & extract the first object from a pair \\
  401. cdr(q) & extract the second object from a pair \\ \hline
  402. \end{tabular}
  403. \end{center}
  404. \ttindex{cons}
  405. \ttindex{.}\ttindex{pairp}\ttindex{car}\ttindex{cdr}
  406. The pair is a very general construct - since its objects themselves
  407. can be pairs, arbitrary trees \ttindex{tree} and data structures can be
  408. built. E.g.\ $((a . b) . (c . d))$
  409. {\nopagebreak[3]
  410. \begin{verbatim}
  411. .--------.
  412. | * | * |
  413. `/------\'
  414. / \
  415. / \
  416. .-------. .-------.
  417. | a | b | | c | d |
  418. `-------' `-------'
  419. \end{verbatim}
  420. }
  421. On the other hand, structures with many members
  422. lead to a very complicated representation if printed using
  423. the above notation. Therefore the {\tt list}\ttindex{list} concept has been
  424. introduced which allows one to use a special class of pair trees in a
  425. simplified form:
  426. \begin{itemize}
  427. \item in a pair with second element $nil$ the dot and the nil
  428. are omitted: $(A.nil)$ = $(A)$.
  429. \item for a pair with another pair as second element one bracket
  430. pair and the dot are omitted: $(B.(A))$ = $(B\, A)$, $(C.(B\, A))$ =
  431. $(C\, B\, A)$.
  432. \end{itemize}
  433. So the {\tt list} is a linear sequence of pairs, where
  434. the $car$s contain the ``data" items, while the $cdr$s contain
  435. the reference to the successors. The last successor is $nil$, which
  436. signals the end of the linear list.
  437. For the graphical representation of linear lists horizontally
  438. aligned double boxes are useful, e.g.\ for $(C\, B\, A)$
  439. {\nopagebreak[3]
  440. \begin{verbatim}
  441. .-------. .-------. .-------.
  442. | c | *-+--->| b | *-+--->| a |nil|
  443. `-------' `-------' `-------'
  444. \end{verbatim}
  445. }
  446. or with omitting the final $nil$
  447. {\nopagebreak[3]
  448. \begin{verbatim}
  449. .-------. .-------. .-------.
  450. | c | *-+--->| b | *-+--->| a | / |
  451. `-------' `-------' `-------'
  452. \end{verbatim}
  453. }
  454. The {\tt list notation} \ttindex{list notation} is
  455. much simpler than the {\tt dot notation}\ttindex{dot notation} - unfortunately
  456. the dots cannot be avoided completely because pairs with
  457. id's or numbers in the $cdr$ part occur and they play an
  458. important role.
  459. Lists can be nested; an example is the internal representation of
  460. algebraic forms (see below) which uses linear lists; e.g.\
  461. $(x+1)^2$ would be represented by lists as
  462. \begin{verbatim}
  463. (expt (plus x 1) 2)
  464. \end{verbatim}
  465. Here the top level list has three elements $expt$, $(plus \, x \, 1)$
  466. and $2$ where the second element itself is a linear list of
  467. length 3.
  468. {\nopagebreak[3]
  469. \begin{verbatim}
  470. .-------. .-------. .-------.
  471. |expt| *+--->| * | *-+--->| 2 | / |
  472. `-------' `-|-----' `-------'
  473. |
  474. .-------. .-------. .-------.
  475. |plus| *+--->| x | *-+--->| 1 | / |
  476. `-------' `-------' `-------'
  477. \end{verbatim}
  478. }
  479. In this graph the {\tt car}s contain the symbols or numbers
  480. or they point to substructures (downwards) while the {\tt cdr}s
  481. point to the successors (to the right) until the end is reached.
  482. As mentioned already there can
  483. be mixtures of both forms if one $cdr$ is not $nil$:
  484. $(A (B.C) D.E)$ - here the second element of the list is
  485. a pair $(A.B)$, the third element is $D$ and there is
  486. no fourth element - the list ends with a non $nil$ symbol.
  487. {\nopagebreak[3]
  488. \begin{verbatim}
  489. .-------. .-------. .-------.
  490. | a | *-+--->| * | *-+--->| d | e |
  491. `-------' `-|-----' `-------'
  492. |
  493. .-------.
  494. | b | c |
  495. `-------'
  496. \end{verbatim}
  497. }
  498. \noindent
  499. The empty list $()$ is identical to the symbol ${\tt nil}$.
  500. Note that the {\reduce} {\tt algebraic forms}\index{algebraic forms}
  501. are LISP lists where all lists are terminated by a $nil$.
  502. Functions on lists:
  503. \begin{center}
  504. \begin{tabular}{|r|l|} \hline
  505. \{o1,o2,..on\} & construct list $(o_1\, o_2 \cdots o_n)$ \\
  506. list(o1,o2,..on) & same as \{o1,o2,..on\} \\
  507. o1.l1 & (infix) put $o_1$ in front of list $l_1$ \\
  508. pairp(q) & true if $q$ is a pair (or a list) \\
  509. atom(q) & true if $q$ is NOT a pair/list \\
  510. null(q) & true if $q$ = $nil$ (=empty list) \\
  511. car(q) & extract the first object from a list \\
  512. cdr(q) & extract the part of the list behind 1st element \\
  513. nth(q,n) & extract the n-th element from list $q$\\
  514. length(q) & count the number of elements of list $q$\\
  515. reverse(q) & reverse a list $q$\\
  516. append(a,b)& append $b$ to the end of a copy of $a$\\
  517. member(a,l) & test if $a$ is equal to one member of $l$\\
  518. memq(a,l) & test if $a$ is identical one member of $l$\\
  519. delete(a,l) & delete $a$ from list $l$\\
  520. \hline
  521. \end{tabular}
  522. \end{center}
  523. \ttindex{list}\ttindex{\{}\ttindex{\}}
  524. \ttindex{.}\ttindex{pairp}\ttindex{atom}
  525. \ttindex{null}\ttindex{car}\ttindex{cdr}\ttindex{nth}
  526. \ttindex{length}\ttindex{reverse}\ttindex{append}
  527. \ttindex{member}\ttindex{memq}
  528. Remarks:
  529. \begin{itemize}
  530. \item All of the above functions are non destructive: an
  531. input list remains as it has been before - the value of each
  532. access function is a reference to the corresponding part of the
  533. structure.
  534. \item The access functions can operate only if the desired elements
  535. are really there; e.g.\ if $nth$ with 4 is applied to a 3 element
  536. list produces an error, and $car$ or $cdr$ applied to any symbol
  537. or number (including $nil$) will fail.
  538. \item Nested calls of $car$ and $cdr$ can be abbreviated by
  539. combining the a's and d's between c and r up to four inner a/d letters.
  540. E.g. $cadr(u)$ = $car(cdr(u))$ \ttindex{c...r}
  541. - this is the direct access
  542. to the second element, $caddr$ returns the third element and
  543. $cadddr$ the fourth element.
  544. \item Although the functions $first$, $second$, $third$, $rest$
  545. known from algebraic mode operate in some {\reduce}
  546. implementations in symbolic mode as synonyms of $car$,
  547. $cadr$, $caddr$, $cdr$, they should not be used here as
  548. this is the case in all {\reduce} versions.
  549. \item The functions $member$ and $memq$ not only test the membership:
  550. if $a$ is member of the list $l$, $member$ (or $memq$) returns the (first)
  551. pair which contains $a$ as its $car$. E.g.\ $memq('b,'(a\ b\ c))$
  552. returns $(b\ c)$. This can be used either if you want to replace
  553. this item in the list, or if you want to process the part after
  554. the search item.
  555. The function $memq$ looks for a member of the list which is {\bf eq}
  556. to the object, while $member$ uses {\bf equal} as test (see discussion
  557. of equality below). If applicable, $memq$ is substantially faster than
  558. $member$.
  559. \item $Delete$ produces a copy of the top level pair sequence leaving
  560. out the first occurrence of the search item: the original list is
  561. not changed, and a possible second occurence of the search item
  562. in the list is not removed. $delete('a,'(0\,a\,b\,a))$ will result
  563. in $(0\,b\,a)$ where the part $(b\,a)$ is the original tail of the
  564. input list while the pairs in front of the original first $a$
  565. are new.
  566. \end{itemize}
  567. {\nopagebreak[3]
  568. Examples: let $u$ be a variable with value $(A (B.C) NIL (D))$. Then
  569. \begin{center}
  570. \begin{tabular}{rl}
  571. pairp(u) &=t\\
  572. length(u) &=4\\
  573. null(u) &=nil\\
  574. car(u) & = A\\
  575. cadr(u) &=(B.C)\\
  576. caadr(u) &=B\\
  577. cdadr(u) &=C\\
  578. cdr(u) &=((B.C) NIL (D))\\
  579. length cdr(u)&=3\\
  580. cddr(u) &=(nil (D))\\
  581. null cddr(u) &=nil\\
  582. caddr(u) &=nil\\
  583. null caddr(u)&=t\\
  584. cdddr(u) &=((D))\\
  585. cddddr(u) &=nil\\
  586. null cddddr(u) &= t\\
  587. \end{tabular}
  588. \end{center}
  589. }
  590. All data which are not pairs (or lists) are classified
  591. as {\tt atoms}\ttindex{atom}: symbols, numbers, strings, vectors(see below)
  592. and, just as in real world, they are not very atomic -- there
  593. are tools to crack them.
  594. \subsection{Programming with lists}
  595. There are several methods available to construct a list:
  596. \begin{verbatim}
  597. u := nil;
  598. u :=1 . u;
  599. u :=2 . u;
  600. \end{verbatim}
  601. Starting with an empty list, elements are pushed on its front
  602. one after the other, here giving $(2\,\, 1)$. Please note the
  603. blank between the number and the dot: this is necessary as otherwise
  604. the dot would have been parsed as part of the number representing a
  605. floating point value.
  606. \begin{verbatim}
  607. u := {9,10};
  608. u := 1 .u;
  609. u := 2 .u;
  610. \end{verbatim}
  611. The same, here not starting with the empty list giving $(2\,\, 1\,\, 9\,\, 10)$.
  612. The {\tt for statement} \ttindex{for statement} has special forms
  613. to handle lists:
  614. \begin{itemize}
  615. \item {\tt for each}\ttindex{for each} $x$ {\tt in} $l$ $\cdots$ performs an
  616. action elementwise for the elements in list $l$; the elements
  617. are accessible by the automatically declared local variable $x$
  618. one after the other.
  619. \item the iterator actions {\tt collect}\ttindex{collect} and {\tt join}
  620. \ttindex{join}
  621. allow you to construct lists:
  622. \begin{itemize}
  623. \item {\tt collect} generates a list where each
  624. iteration step produces exactly one element,
  625. \item {\tt join} expects that each iteration step produces a
  626. complete list (or $nil$) and joins them to one long list.
  627. \end{itemize}
  628. \end{itemize}
  629. Examples: let e.g.\ $l$ be a list of numbers
  630. $(1\,\, -2\,\, 3\,\, -4\,\, 5\,\, -6)$:
  631. \begin{verbatim}
  632. m:=for each x in l sum x;
  633. \end{verbatim}
  634. $m$ will be the sum of the elements,
  635. \begin{verbatim}
  636. s:=for each x in l collect x*x;
  637. \end{verbatim}
  638. $s$ is computed as list with the numbers from $x$ squared,
  639. \begin{verbatim}
  640. p:=for each x in l join
  641. if x>0 then {x} else nil;
  642. \end{verbatim}
  643. in this loop the positive numbers produce one element
  644. lists, while the negative numbers are mapped to nil; joined
  645. together the result is a list with only the positive
  646. elements,
  647. \begin{verbatim}
  648. r:=for i:=1:10 collect -r;
  649. \end{verbatim}
  650. here the result is the list with numbers $(-1\,\, -2\,\, -3 \cdots -10)$.
  651. The lists produced by {\em collect} and {\em join} are in ``correct"
  652. order.
  653. {\bf Warning}: In symbolic mode {\em join} links the lists
  654. {\bf in place} for maximum speed
  655. \footnote{In algebraic mode {\em join} operates different: the operatend
  656. are copied before linking them to one result list}:
  657. The last {\em CDR} pointer of the first list is modified to
  658. point to the head of the second list , and so on.
  659. This is no problem if the joined objects are freshly built
  660. structures, or if there are no other references to them.
  661. If the in -- place operation is dangerous for your application,
  662. you must copy the structure before, e.g. by a call to {\em append}
  663. with {\em NIL} as second argument:
  664. \begin{verbatim}
  665. r:=for i:=1:10 join append(my_extract(u,r),nil);
  666. \end{verbatim}
  667. In this example, the top level chain of the results of {\em my\_extract}
  668. is copied such that the original structure is not modified when
  669. joining.
  670. Another very common style for list operations is to use
  671. iterative or recursive programs. The following programs each
  672. sum the elements of the list:
  673. \begin{verbatim}
  674. symbolic procedure sum_1(l);
  675. begin integer n;
  676. while l do <<n:=n+car l; l:=cdr l>>;
  677. return n;
  678. end;
  679. \end{verbatim}
  680. This program picks in each step of the the while loop one
  681. element from the list and sets the variable $l$ to
  682. the successor position; the loop terminates as soon as the
  683. successor $nil$ is found .
  684. \begin{verbatim}
  685. symbolic procedure sum_2(l);
  686. if null l then 0 else car l + sum_2(cdr l);
  687. \end{verbatim}
  688. This program uses recursion for the same task.
  689. The program will go down the list until $nil$ is found,
  690. then set the sum to $0$ and when coming back from the
  691. recursion add the elements to the sum so far.
  692. \begin{verbatim}
  693. symbolic procedure sum_3(l); sum_31(l,0); % initializing
  694. symbolic procedure sum_31(l,n);
  695. if null l then n else sum_31(cdr l,car l+n);
  696. \end{verbatim}
  697. The third example is a bit tricky: it initializes
  698. the sum to 0, and when stepping down in the
  699. recursion the sum is updated and passed to the next
  700. recursion level as a parameter.
  701. It is also very common to produce lists in recursive style,
  702. e.g.\ inverting the signs in a list of numbers could be written as
  703. \begin{verbatim}
  704. symbolic procedure invertsgn(l);
  705. if null l then nil else -car l . invertsgn(cdr l);
  706. \end{verbatim}
  707. and with most LISP compilers this program would as efficient
  708. as the corresponding loop
  709. \begin{verbatim}
  710. for each x in l collect -x;
  711. \end{verbatim}
  712. but produce less code.
  713. Note that as with {\em for each - collect}, the elements in the resulting
  714. list will be in the original order.
  715. The recursive programming style is typical for LISP and it
  716. is used for hundreds of {\reduce} routines.
  717. \subsection{In-place operations}
  718. All list construction described so far except {\bf join}
  719. is of a copying nature:
  720. every construction by the dot or the curly brackets always creates
  721. fresh pairs and an old list is untouched. However, there are operations
  722. to modify elements or the structure of an existing list in place. These should
  723. be used only with greatest care: if there is another reference to the list,
  724. its structure will be modified too, a possibly unwanted side effect.
  725. The functions
  726. are\footnote{Read ``reversip" as ``reverse-in-place" and ``nconc" as
  727. ``concatenate"}:
  728. \begin{center}
  729. \begin{tabular}{|r|l|} \hline
  730. car l := u & replace first element of $l$ by $u$ \\
  731. rplaca(l,u) & old form for car l := u\\
  732. cdr l := u & replace cdr part of $l$ by $u$ \\
  733. rplacd(l,u) & old form for cdr l := u\\
  734. nth(l,j) := u & replace the j-th element of $l$ by $u$\\
  735. nconc(a,b) & insert $b$ as cdr in the last pair of $a$\\
  736. reversip(l) & invert the sequence of $l$ using the same pairs again\\
  737. \hline
  738. \end{tabular}
  739. \end{center}
  740. \ttindex{nth}\ttindex{car}\ttindex{cdr}\ttindex{nconc}\ttindex{reversip}
  741. \subsection{Equal tests: Equality vs.\ Identity}
  742. There are two classes of equality in LISP, $eq$ and $equal$,
  743. \ttindex{eq} \ttindex{equal} \ttindex{=}
  744. in {\reduce} written as the infix operators {\tt eq}, and
  745. equal sign $=$ respectively. As symbols are unique,
  746. both are equivalent for them: if symbols are {\tt equal},
  747. they are {\tt eq}.
  748. $u:='a; v:='a;$ $ u\, eq\, v \Rightarrow t$
  749. \noindent
  750. here the variables $u$ and $v$ represent the same symbol
  751. and consequently they are {\tt eq}.
  752. For lists, things are different. Here we must distinguish
  753. between references to pairs which contain the same contents
  754. (``equal") or references to the same identical pair
  755. instance(``{\tt eq}").
  756. A pair is {\tt eq}
  757. to itself only, but it is {\tt equal} to a different pair if
  758. their $car$s and $cdr$s are {\tt equal} - this is a
  759. recursive definition. Example:
  760. $u:=\{1,2\}; v:=\{1,2\};w:=u;$
  761. $u=v \Rightarrow t$ ,$u=w \Rightarrow t$
  762. $u\,\,eq\,\,v\Rightarrow nil$, $u\,\,eq\,\,w\Rightarrow t$
  763. Here $u$, $v$ and $w$ have as values pairs with same $car$s
  764. and {\tt equal} $cdr$s, but only $u$ and $w$ refer to
  765. the identical pair because for $v$ fresh pairs have
  766. been built.
  767. In some points {\reduce} relies on identity of some structures,
  768. e.g. for composite kernels \index{kernel} of
  769. {\tt standard forms}\index{standard forms}.
  770. \subsection{Properties, Flags}
  771. Another important concept of LISP is the ability to
  772. assign {\tt properties}\ttindex{property} and
  773. {\tt flags}\ttindex{flag} to each
  774. symbol. A {\tt property} is a symbol (a ``name") together
  775. with a value. Both, property name and property value are
  776. completely free. Properties are set by the function {\tt put}
  777. \ttindex{put} and read by the function {\tt get}\ttindex{get}.
  778. \begin{verbatim}
  779. put('hugo,'evaluator,'compute_hugo);
  780. . . .
  781. get('hugo,'evaluator) => compute_hugo
  782. get('otto,'evaluator) => nil
  783. \end{verbatim}
  784. A property-value pair remains assigned for a symbol until the value is
  785. replaced by a different value or until the property is removed
  786. by {\tt remprop}\ttindex{remprop}.
  787. A {\tt flag} is similar to a property, but
  788. it represents only the values ``yes" or ``no" (= flag is
  789. present or absent). The functions for setting and
  790. testing flags are {\tt flag}\ttindex{flag} and {\tt flagp}\index{flagp},
  791. {\tt remflag}\index{remflag} for removal.
  792. As most other LISP programs, {\reduce} makes extensive use of properties.
  793. E.g.\ the algebraic properties of an operator are encoded
  794. in that way. So the symbol $plus$ has among others the {\reduce}
  795. properties $prtch=+$ (the print character),
  796. $infix=26$\footnote{This number may change if additional operators
  797. of lower precedence are introduced}
  798. (the precedence among the infix operators), $simpfn=simpplus$
  799. (the name of the routine responsible for its simplification)
  800. and the flags $symmetric$, $realvalued$, $nary$ and some more.
  801. These allow a data driven programming model which has been used
  802. in the LISP world for decades already: if the simplifier
  803. operates on an expression, it asks the leading operator for
  804. its simplification function; if there is one (and there will be
  805. one for all operators), this function is invoked to do the job.
  806. There are various fields where this type of programming is used
  807. inside {\reduce}, e.g.\ the complete domain arithmetic has been
  808. implemented in that way: any non-integer domain element is encoded
  809. as a list with a leading symbol (the domain mode) which contains
  810. all knowledge about arithmetic, conversion, printing etc.\ for
  811. this domain as properties and flags.
  812. If your {\reduce} system is based on PSL, you can inspect a
  813. property list by calling the function $prop$\ttindex{prop} which
  814. has one argument (the symbol to be inspected) and which returns
  815. the properties and flags as list. E.g.
  816. \begin{verbatim}
  817. a := mat((1,2),(3,4));
  818. prop 'a;
  819. prop 'mat;
  820. prop 'matrix;
  821. \end{verbatim}
  822. \subsection{Alists}
  823. Another frequently used LISP structure is the
  824. {\tt association list}\ttindex{association list}
  825. ({\tt alist}\ttindex{alist}), which is
  826. an associative memory: a list where each element
  827. is a pair with a search item and a value item.
  828. The function {\tt assoc}\ttindex{assoc} picks the pair for
  829. a given search item out of the {\tt alist}.
  830. For example constructing a multiplier with memory:
  831. {\nopagebreak[3]
  832. \begin{verbatim}
  833. fluid '(product_database*);
  834. symbolic procedure multiply(u,v);
  835. begin scalar w,r;
  836. w:=u.v;
  837. r:=assoc(w,product_database*);
  838. if r then return cdr r; % found
  839. r:=u*v;
  840. product_database*:=(w.r).product_database*;
  841. return r;
  842. end;
  843. \end{verbatim}
  844. }
  845. here the pair $u.v$ is used as search item. If an
  846. entry is found in the database, its value part is
  847. returned. Otherwise the product is computed and
  848. the new entry is added to the database. After calling
  849. this function with arguments 2 and 3, and then with 2 and 6 the
  850. structure would be
  851. {\nopagebreak[3]
  852. \begin{verbatim}
  853. .-------. .-------.
  854. | * | *-+--->| * | / |
  855. `-|-----' `-|-----'
  856. | |
  857. .-------. .-------.
  858. | * | 6 | | * | 12|
  859. `-|-----' `-|-----'
  860. | |
  861. .-------. .-------.
  862. | 2 | 3 | | 2 | 6 |
  863. `-------' `-------'
  864. \end{verbatim}
  865. }
  866. Here each element in the top level list points to one
  867. generalized name-value pair, where the name itself is a structure
  868. (here a pair of two numbers). {\reduce} uses association lists
  869. for many different purposes; e.g.\ if an expression is simplified,
  870. the expression and its simplified variant are stored in an
  871. association list such that for a second access to the same expression
  872. its simplified form is immediately accessible.
  873. \subsection{Vectors}
  874. Lists enable access of items of a linear collection by
  875. position number using the function {\tt nth}; however, this
  876. access is inefficient if used frequently because for
  877. every access the sequence of pairs has to be traversed
  878. until the desired object is reached. An alternative
  879. structure for direct access by element number in
  880. symbolic mode is the {\tt vector}\ttindex{vector}. The first element
  881. in a vector has the index $0$. \ttindex{putv}\ttindex{getv}\ttindex{upbv}
  882. \begin{center}
  883. \begin{tabular}{|r|l|} \hline
  884. v:=mkvect(n) & create a vector of length $n$ \\
  885. putv(v,m,u) & put value $u$ into $m$th slot of vector $v$\\
  886. getv(v,m) & extract element $m$ from vector $v$ \\
  887. upbv(v) & returns upper bound for $v$ \\
  888. \hline
  889. \end{tabular}
  890. \end{center}
  891. \ttindex{mkvect}\ttindex{getv}\ttindex{putv}\ttindex{upbv}
  892. Note that {\tt putv} is a ``destructive" operation.
  893. \section{Algebraic data formats and evaluation}
  894. \subsection{Prefix forms}
  895. The basic format for representing mathematical
  896. formulae is the {\tt algebraic form} \ttindex{ algebraic form}: an
  897. expression is internally encoded as a list
  898. with {\tt prefix}\index{ prefix} operators:
  899. \begin{itemize}
  900. \item the first element of a list is an operator,
  901. \item the following elements of a list are the arguments
  902. which can be symbols (unknowns), numbers or
  903. {\tt algebraic forms} in prefix notation.
  904. \end{itemize}
  905. Examples:
  906. $x+1 \Rightarrow (PLUS\,\, X\,\, 1)$
  907. $x+y+1 \Rightarrow (PLUS\,\, X\,\, Y\,\, 1)$
  908. $x+ y*z + 1 \Rightarrow (PLUS\,\, X\,\, (TIMES\,\, Y\,\, Z)\,\, 1)$
  909. $x^\wedge (y+1) \Rightarrow (EXPT\,\, X\,\, (PLUS\,\, Y\,\, 1))$
  910. Algebraic forms are used for many purposes, for data input,
  911. for transferring data between various system components and
  912. for output. To get a feel as to how algebraic forms look
  913. like, you can make {\reduce} display them for you, e.g.\
  914. by the following sequence:
  915. \begin{verbatim}
  916. u:=(x+y)^3/(log z-sqrt 2);
  917. symbolic reval 'u;
  918. \end{verbatim}
  919. The first statement assigns an algebraic expression to a
  920. variable as usual in algebraic mode, and the second statement
  921. forces {\reduce} to print the algebraic form corresponding
  922. to this expression in symbolic mode.
  923. \subsection{*SQ}
  924. {\reduce} uses internally a different
  925. representation for algebraic expressions, the
  926. {\tt standard quotient}\index{standard quotient}({\tt SQ},
  927. see below). As conversion
  928. between algebraic forms and standard quotients is expensive,
  929. {\reduce} tries to keep the data as long in {\tt SQ}
  930. form as possible. For this purpose there is a special
  931. variant of the algebraic form $(*SQ \,\, u \,\, ind)$: here the
  932. internal operator $*SQ$ indicates that the parameter $u$
  933. is not an algebraic form but a standard quotient. If such
  934. expression is evaluated, {\reduce} detects
  935. immediately that it will find the standard quotient
  936. already as the second element of the list and no more
  937. conversion is necessary.
  938. However, if since creation of this
  939. form some values in the system have been changed, the
  940. form $u$ might be no longer the ``correct" standard
  941. quotient; e.g.\ one of its unknowns might have a value
  942. now. For this purpose the third element $ind$ in the list
  943. has been introduced: As long as the form $u$ is the correct
  944. one, it will be $T$. As soon as a significant value in the
  945. system changes which might affect the validity of $u$,
  946. {\reduce} switches all $ind$ elements in the $*SQ$ forms
  947. swimming around to $nil$. So the evaluator decides from the
  948. second parameter whether to use $u$ unchanged or
  949. to re-evaluate.
  950. By the way, the global replacement of the second parameter
  951. in the $*SQ$ forms is a good example of an in-place
  952. list operation with a wanted side effect:
  953. {\reduce} maintains a unique list $*sqvar*=(t)$ and all
  954. $*SQ$ forms are built with this list as last pair.
  955. If the environment changes it is sufficient to replace
  956. this single {\bf $t$} in $*sqvar*$ by $nil$ and all $*SQ$ forms
  957. built with the actual $*sqvar*$-tail inherit this
  958. automatically switching from $t$ to $nil$;
  959. {\reduce} then creates a fresh list $*sqvar*=(t)$
  960. to be used for the next generation of $*SQ$ forms.
  961. \subsection{Composite forms}
  962. \subsubsection{Lists, equations}
  963. For algebraic mode, lists are represented by the prefix
  964. operator $LIST$. From the symbolic mode standpoint it may
  965. appear a bit curious that one has to insert
  966. the symbol $LIST$ into a list in order to make it
  967. a correct algebraic object, but this is necessary
  968. in the prefix algebraic context.
  969. E.g.\ try in algebraic mode
  970. \begin{verbatim}
  971. u:={a,b,{c,d},e};
  972. lisp reval 'u;
  973. \end{verbatim}
  974. you will see the result $(LIST\,\, A\,\, B\,\, (LIST\,\, C\,\, D)\,\, E)$.
  975. Correspondingly {\tt equations}\index{equation} are represented by
  976. the prefix operator $EQUAL$ followed by the right-hand and
  977. the left-hand sides as parameters; e.g.\ $x=sqrt(2)$
  978. is represented as $(EQUAL\,\, X\,\,(SQRT\,\, 2))$;
  979. The result of {\em solve (x$\wedge$ 2=2,x);} is an instructive
  980. mixture of all these forms:
  981. \begin{verbatim}
  982. (LIST (EQUAL X (!*SQ (((((EXPT 2 (QUOTIENT 1 2)). 1). -1)). 1) T))
  983. (EQUAL X (!*SQ (((((EXPT 2 (QUOTIENT 1 2)). 1). 1)). 1) T)))
  984. \end{verbatim}
  985. this form is a list with two equations and the equations
  986. have $*SQ$ forms as right-hand sides.
  987. \subsubsection{Matrices}
  988. A {\tt matrix}\ttindex{matrix} too is represented internally by
  989. a prefix form with operator $MAT$ followed by the rows;
  990. each row is a list containing the elements as algebraic
  991. forms. The elements can be accessed easily using the
  992. access function $nth$. Example: the matrix $mat((1,2),(3,4))$
  993. is encoded as $(MAT\,\,(1\,\, 2)\,\, (3\,\, 4))$.
  994. The form $nth(nth(m,3),2)$ gives access to the element (2,2).
  995. Be careful if you use this form for an assignment:
  996. $nth(nth(m,3),2):=17;$ is an in-place operation.
  997. You can create a matrix easily by a symbolic program, e.g.
  998. a n*n unit matrix
  999. \begin{verbatim}
  1000. symbolic procedure my_unit_matrix(n);
  1001. 'mat . for i:=1:n collect
  1002. for j:=1:n collect if i=j then 1 else 0;
  1003. \end{verbatim}
  1004. \subsection{Algebraic evaluator: reval, aeval, aeval*}
  1005. The main entries to the algebraic evaluator are the
  1006. symbolic mode functions {\tt reval}\ttindex{reval} and
  1007. {\tt aeval}\ttindex{aeval}.
  1008. Both have as input an algebraic expression
  1009. and return the fully evaluated result. Reval always returns
  1010. an algebraic form in full prefix operator form, while
  1011. aeval tries to keep the result in $*SQ$-form whenever
  1012. possible. Almost all algebraic functionality of {\reduce} can be
  1013. invoked by calling these procedures, e.g.
  1014. \begin{verbatim}
  1015. reval '(solve (plus (expt x 2) 3) x);
  1016. \end{verbatim}
  1017. If you turn on the switch {\tt defn} in algebraic mode
  1018. you will see that {\reduce} translates most statements
  1019. into calls for {\tt aeval}.
  1020. Reval and aeval are also adequate tools for accessing
  1021. the values of algebraic quantities and for evaluation of
  1022. unevaluated procedure parameters; they do the complete
  1023. job for you.
  1024. However, there is one exception:
  1025. the left-hand side of an equation in general is not
  1026. evaluated by {\tt reval} and {\tt aeval}. E.g.\
  1027. \begin{verbatim}
  1028. l:= a=b;
  1029. a:=17;b:=4;
  1030. symbolic reval 'l;
  1031. \end{verbatim}
  1032. produces the output $(EQUAL\,\, A\,\, 4)$. If you write
  1033. a program for equations you either should evaluate
  1034. the left-hand sides yourself by calling {\tt reval}
  1035. or rebind the internal switch {\tt *evallhseqp}\ttindex{evallhseqp}
  1036. \footnote{Read ``evallhseqp" as ``evaluate left-hand side
  1037. of equations predicate".}
  1038. locally(!) by $t$ - then {\reduce} will evaluate both sides
  1039. of an equation.
  1040. {\reduce} maintains an internal buffer {\tt alglist*}\ttindex{aglist*}
  1041. where all evaluation results are stored such that a repeated request
  1042. for the same evaluation can be satisfied by a simple and fast table
  1043. lookup\footnote{The use of {\tt alglist*} is controlled by an internal
  1044. switch {\tt *uncached}\ttindex{*uncached}\ttindex{uncached}: if this
  1045. variable has a non-nil value, the caching is suppressed.}.
  1046. As a side effect, {\tt aeval} resets {\tt alglist*}
  1047. empty before starting a
  1048. computation\footnote{Of course, there are many more places where {\tt alglist*}
  1049. needs to be reset; e.g.\ any assignment causes {\tt alglist*} to be
  1050. reset because the assigned value might make one of the stored values
  1051. invalid.}. There is a second function
  1052. {\tt aeval*}\ttindex{aeval*}: this function performs the same
  1053. operation, but in contrast to {\tt aeval} it does not reset
  1054. {\tt alglist*} and can profit from previous results. The {\reduce}
  1055. uses both, {\tt aeval} and {\tt aeval*} depending of the specific
  1056. environment of a translated statement.
  1057. \section{Standard Forms, Standard Quotients}
  1058. \subsection{Introduction}
  1059. On of the most important tasks performed by a computer algebra
  1060. system is the reduction of an algebraic expression to a
  1061. canonical form. A reduction process is canonical if it
  1062. guarantees that two expressions are transformed to the
  1063. same form if and only if they are algebraically identical.
  1064. Unfortunately canonical forms are not known for all algebraic
  1065. objects, e.g.\ for surds. The canonical form of {\reduce}
  1066. is the {\tt standard quotient}\ttindex{standard quotient}
  1067. (``{\tt SQ}") which is
  1068. a quotient of two {\tt standard forms}\ttindex{standard form} (``{\tt SF}").
  1069. An {\tt SF} is a polynomial in internal representation and
  1070. an {\tt SQ} is a quotient of two polynomials, a
  1071. rational function. At the same time {\tt SQ} and
  1072. {\tt SF} are the forms used internally for most arithmetic.
  1073. In this section the structures of {\tt SF} and {\tt SQ}
  1074. are described, followed by a list of operations on these. For
  1075. programming and debugging in symbolic mode it is often
  1076. necessary to decipher an expression of this type.
  1077. However, the knowledge about this part of the internal
  1078. {\reduce} structure should never be used to access
  1079. {\tt SF} of {\tt SQ} directly by LISP primitives. Instead
  1080. use only ``official" primitives supplied by {\reduce}.
  1081. \subsection{Coefficients}
  1082. \ttindex{coefficient domains}
  1083. The coefficients in {\tt SF} and {\tt SQ} are the ``numbers"
  1084. from various algebraic contexts. They are called {\tt domain}\ttindex{domain}
  1085. elements and uniformly represented either
  1086. as integer numbers or pairs where the {\tt car} part contains
  1087. an identifier describing the domain and its arithmetic
  1088. by its {\tt properties}\ttindex{property};
  1089. the {\tt cdr} part describes the value.
  1090. \begin{enumerate}
  1091. \item{Integers}: integer numbers $\in {\bf Z}$ represent integer
  1092. coefficients directly,
  1093. \item{Gaussian integers}: complex numbers with integer real and
  1094. imaginary part {\em (:gi: re . im)} with $re,im \in {\bf Z}$,
  1095. \item{Rational numbers}: quotients of integers
  1096. {\em (:rn: nu . de)} with $nu,de \in {\bf Z}$,
  1097. \item{Modular numbers}: numbers modulo the current prime
  1098. {\em (:mod: . j)} where $0 \leq j < currentmodulus*$
  1099. \footnote{The upper half of the modular numbers are printed as negative
  1100. numbers if the switch {\tt balanced\_mod}\ttindex{balanced\_mod}
  1101. is on; hovever, that does not affect the internal representation
  1102. which uses always integers $\geq 0$}.
  1103. \item{Rounded numbers}: floating point numbers extended in
  1104. precision and magnitude {\em (:rd: . fp)} with LISP floating point number
  1105. $fp$ or {\em (:rd: mant . exp)} with integers $mant$ and $exp$
  1106. representing an extended floating point value,
  1107. \item{Rounded complex numbers}: numbers with rounded real
  1108. and imaginary parts {\em (:gr: fre . fim)} with LISP floating point numbers
  1109. $fre$ and $fim$ or {\em (:gr: (rmant . rexp) . (imant . iexp))} with
  1110. extended real and imaginary parts.
  1111. \end{enumerate}
  1112. The neutral elements {\em zero} and {\em one} for
  1113. addition and multiplication respectively are identical
  1114. for all domains: {\em zero} is represented as $nil$ and {\em one} by the
  1115. integer number 1.
  1116. The list of domains is open ended: if a new coefficient domain
  1117. is required for an application field, this can be created and linked
  1118. to the system at any time. The necessary structure is described
  1119. in the source file for the module $dmodeop$\index{dmodeop module}.
  1120. The tag of the currently active domain is stored in the value of the
  1121. variable {\tt dmode*}\ttindex{dmode*}.
  1122. $nil$ represents the default domain (integers).
  1123. This variable should not be modified directly - instead use
  1124. the function {\tt setdmode}\ttindex{setdmode}:
  1125. \begin{verbatim}
  1126. setdmode(DOM:domain,MODE:bool);
  1127. \end{verbatim}
  1128. where $domain$ is a domain name (e.g. $'rational$) and the Boolean
  1129. second parameter tells whether to activate ($t$) or to deactivate
  1130. ($nil$) the domain. Note that $setdmode$ does not
  1131. set {\tt on} the corresponding switches.
  1132. You {\em must} do that yourself.
  1133. E.g. for a proper activation and deactivation of complex rounded
  1134. call
  1135. \begin{verbatim}
  1136. !*rounded := t;
  1137. setdmode('rounded,t);
  1138. !*complex := t;
  1139. setdmode('complex,t);
  1140. .... % do your computation
  1141. setdmode('complex,nil);
  1142. !*complex := nil;
  1143. setdmode('rounded,nil);
  1144. !*rounded := nil;
  1145. \end{verbatim}
  1146. In order to convert the domain tag into the domain name
  1147. use the property {\tt dname}\ttindex{dname}, e.g.
  1148. \begin{verbatim}
  1149. get(dmode!*,'dname);
  1150. \end{verbatim}
  1151. will result in the name of the current domain.
  1152. \subsection{Generic arithmetic with domain elements}
  1153. There is a complete set of arithmetic functions for performing
  1154. arithmetic operations with domain elements:
  1155. \begin{center}
  1156. \begin{tabular}{|r|l|} \hline
  1157. !:zerop(a) & test $a=0$ \\
  1158. !:plus(a,b) & $a+b$ \\
  1159. !:difference(a,b) & $a-b$ \\
  1160. !:minus(a) & $-a$ \\
  1161. !:minusp(a) & test $a<0$ \\
  1162. !:times(a,b) & $a*b$ \\
  1163. !:quotient(a,b) & $a/b$ \\
  1164. !:recip(a) & $1/b$ \\
  1165. !:expt(a,n) & $a^n$ \\
  1166. !:gcd(a,b) & $greatest\, common\, divisor\, of\,(a,b)$ \\
  1167. \hline
  1168. \end{tabular}
  1169. \end{center}
  1170. \subsection{Kernels, kernel order}
  1171. {\tt Kernels} are the ``unknowns" in a polynomial.
  1172. A \ttindex{kernel}{\tt kernel}
  1173. can be an
  1174. \begin{itemize}
  1175. \item{identifier}: e.g. $x$, $alpha$, represented as LISP symbols
  1176. $X$, $ALPHA$,
  1177. \item{operator form}: e.g. $sin(alpha)$,$sqrt(x+1)$,$bessel(j,x)$,
  1178. represented as algebraic expression $(SIN ALPHA)$,
  1179. $(EXPT\,\,(PLUS\,\, X\,\, 1)\,\, (QUOTIENT\,\, 1\,\, 2))$, $(BESSEL\,\, J\,\, X)$.
  1180. \item{A standard form}, e.g. $(((A\,\,.\,\,1)\,\,.\,\,1)\,\,.\,\,1)$
  1181. This option is used only if the default mode of full expantions is
  1182. turned off (see below: non-expanded standard form).
  1183. \end{itemize}
  1184. It is essential for the operation of {\reduce} that kernels are unique.
  1185. This is no problem for id's as these are unique by LISP definition.
  1186. For composite kernels {\reduce} ensures that these are
  1187. made unique before they enter a {\tt standard form}.
  1188. {\em Never construct a composite kernel by hand}. Instead use
  1189. the function {\tt *a2k}\ttindex{*a2k} for converting an algebraic expression
  1190. into a kernel or use $simp$ (see below). On the other hand,
  1191. the uniqueness of kernels is of big advantage for comparisons:
  1192. the equality can be tested with $eq$ instead of = and faster $memq$ and
  1193. $atsoc$ can be used instead of $member$ and $assoc$.
  1194. The set of all kernels is totally ordered by
  1195. the {\tt kernel order}\ttindex{kernel order}.
  1196. {\reduce} has by default some ordering which is roughly based
  1197. on lexicographic comparison. The ordering can be changed internally
  1198. by calling {\tt setkorder}\ttindex{setkorder}
  1199. (corresponding to the algebraic statement
  1200. {\tt korder}\ttindex{korder}) with a list of kernels as argument.
  1201. These kernels
  1202. precede all other kernels in the given sequence .{\tt Setkorder} returns
  1203. as result the previous order and it is a good policy to restore
  1204. the old order after you have changed it:
  1205. \begin{verbatim}
  1206. begin scalar oldorder, ....;
  1207. oldorder:=setkorder '(x y z);
  1208. ....
  1209. setkorder oldorder;
  1210. ....
  1211. end;
  1212. \end{verbatim}
  1213. The current kernel order list is the value of the variable
  1214. {\tt kord*}\ttindex{kord*}.
  1215. The value $nil$ signals that the default ordering is active.
  1216. To check the system order of two algebraic expressions use the
  1217. function {\tt ordp}\ttindex{ordp} with two arguments,
  1218. which returns true if the
  1219. first argument is lower in the ordering sequence as the second one.
  1220. This check does not consider the actual {\tt kord*}.
  1221. For kernels there is an extended order check function
  1222. {\tt ordop}\ttindex{ordop} which does consider the actual {\tt kord*}.
  1223. However, you need to call these functions only rarely as the
  1224. algebraic engine of {\reduce} maintains a proper order in any
  1225. context.
  1226. \subsection{Standard form structure}
  1227. A {\tt standard form}\ttindex{standard form} is a polynomial in internal recursive
  1228. representation where the kernel order defines the recursive
  1229. structure. E.g.\ with kernel order $(x\,\,y)$ the polynomial
  1230. $x^2y +x^2 + 2xy + y^2 + x + 3$ is represented as a polynomial
  1231. in $x$ with coefficients which are polynomials in $y$ and integer coefficients:
  1232. $x^2*(y*1+1) + x*(y*2+1) +(y^2*1 +3)$; for better correspondence
  1233. with the internal representation here the integer coefficients
  1234. are in the trailing position and the trivial coefficients $1$ are
  1235. included.
  1236. A standard form is
  1237. \begin{itemize}
  1238. \item $<$domain element$>$
  1239. \item $<$mvar$>$\ .** $<$ldeg$>$\ .* $<$lc$>$\ .+ $<$red$>$,
  1240. internally represented as {\em (((mvar.ldeg).lc).red)}
  1241. \end{itemize}
  1242. with the components
  1243. \begin{itemize}
  1244. \item {\em mvar}: the leading kernel,
  1245. \item {\em ldeg}: an integer representing the power of $mvar$ in the leading
  1246. term,
  1247. \item{\em lc}: the leading coefficient is itself a standard form,
  1248. not containing $mvar$ any more,
  1249. \item{\em red}: the reductum too is a standard form, containing $mvar$
  1250. at most in powers below $ldeg$.
  1251. \end{itemize}
  1252. Note that any standard form ends with a domain element which
  1253. is $nil$ if there is no constant term.
  1254. E.g.\ the above polynomial
  1255. will be represented internally by
  1256. \begin{verbatim}
  1257. (((X .2) ((Y. 1). 1). 1) ((X. 1) ((Y. 1). 2)) ((Y. 2). 1). 3)
  1258. \end{verbatim}
  1259. with the components
  1260. \begin{itemize}
  1261. \item{mvar}: \verb+X+
  1262. \item{ldeg}: \verb+2+
  1263. \item{lc}: \verb+((Y. 1). 1). 1)+ = $(y+1)$
  1264. \item{red}: \verb+(((X. 1) ((Y. 1). 2)) ((Y. 2). 1). 3)+ = $xy^2+3$.
  1265. \end{itemize}
  1266. \subsection{Operations on standard forms}
  1267. Arithmetic with standard forms is performed by the
  1268. functions\footnote{Be careful not to intermix
  1269. the names ``minusf" and ``negf".
  1270. And take into account that {\tt minusf} will return a positive result
  1271. only if the value is definitely known to be less that 0.}
  1272. \begin{center}
  1273. \begin{tabular}{|r|l|} \hline
  1274. null(f) & test $f=0$ \\
  1275. minusf(f) & test $f<0$ (formally) \\
  1276. domainp(f) & test if $f$ is a domain element (e.g. number) \\
  1277. addf(f1,f2)& f1 + f2 \\
  1278. negf(f) & -f \\
  1279. addf(f1,negf f2) & f1-f2 \\
  1280. multf(f1,f2) & f1*f2 \\
  1281. mksp**(f1,n) & compute f1**n \\
  1282. quotf(f1,f2) & $f1/f2$ if divisible, else $nil$ \\
  1283. quotfx(f1,f2) & $f1/f2$ divisiblity assumend, no check\\
  1284. qremf(f1,f2) & pair (quotient.remainder) \\
  1285. \hline
  1286. \end{tabular}
  1287. \end{center}
  1288. \ttindex{null}\ttindex{domainp}\ttindex{addf}
  1289. \ttindex{negf}\ttindex{multf}\ttindex{mksp}
  1290. \ttindex{quotf}\ttindex{qremf}
  1291. As standard forms are a superset of domain elements these
  1292. functions also can be used for arithmetic with domain elements
  1293. or for combining standard forms with integer numbers. They
  1294. can even be used to compute with integers as long as these
  1295. are regarded as ``degenerate" polynomials.
  1296. For access of the components of a standard form
  1297. there are functions
  1298. \begin{center}
  1299. \begin{tabular}{|r|l|} \hline
  1300. mvar(f) & extract leading kernel \\
  1301. ldeg(f) & extract leading degree \\
  1302. lc(f) & extract leading coefficient \\
  1303. red(f) & extract reductum f\\ \hline
  1304. \end{tabular}
  1305. \end{center}
  1306. \ttindex{mvar}\ttindex{ldeg}\ttindex{lc}\ttindex{red}
  1307. These functions can be applied only if the form
  1308. is not a domain element. The following example presents
  1309. a typical function evaluating a standard form; it looks for the
  1310. maximum power of a specified kernel $y$ in a standard form $f$:
  1311. \begin{verbatim}
  1312. symbolic procedure my_maxpow(f,y);
  1313. if domainp f then 0 else
  1314. if mvar f eq y then ldeg f else
  1315. max(my_maxpow(lc f,d),my_maxpow(red f,d));
  1316. \end{verbatim}
  1317. This function has a double recursion which is typically
  1318. for functions traversing standard forms: if the top node is
  1319. not trivial ({\tt domainp}) or not a power of $y$
  1320. the procedure branches to the
  1321. coefficient form and to the reductum form - both
  1322. can contain references to the kernel $y$. Kernels are
  1323. unique in the system and therefore the equality test is
  1324. performed by {\tt eq}.
  1325. For the initial construction of a standard form a safe and efficient
  1326. way is to build an algebraic expression first and convert
  1327. it using $simp$ (see below) or to use the arithmetic functions
  1328. above too. For elementary conversions use
  1329. \begin{center}
  1330. \begin{tabular}{|r|l|} \hline
  1331. *k2f(k) & convert unique kernel $k$ to {\ SF} \\
  1332. numr simp(a)& convert algebraic expression $a$ to {\tt SF}\\
  1333. prepf(f)& convert a {\tt SF} $f$ to an algebraic expression\\
  1334. \hline
  1335. \end{tabular}
  1336. \end{center}
  1337. Note that integers are already an {\tt SF} and so need not be converted.
  1338. Although the are infix macros \fbox{.**} , \fbox{.*} , \fbox{.+} to
  1339. construct standard forms, they should be avoided unless
  1340. you are completely sure what you are doing: they construct
  1341. without any consistency checks, and wrong structures may lead
  1342. to inconsistent results; such cases are difficult to debug.
  1343. \subsection{Reordering}
  1344. If you change the {\tt kernel order}\ttindex{kernel order} it is
  1345. necessary to reorder {\tt standard forms} if they
  1346. are processed under the new order by calling
  1347. \begin{center}
  1348. \begin{tabular}{|r|l|} \hline
  1349. reorder(f) & reorders $ f$ to the current order \\ \hline
  1350. \end{tabular}
  1351. \end{center}
  1352. \ttindex{reorder}
  1353. Please ensure that you never use a standard form which does
  1354. not correspond to the actual order - otherwise very
  1355. strange results can occur. Freshly created standard
  1356. forms will always have the current order.
  1357. \subsection{Standard Quotients}
  1358. A {\tt standard quotient}\ttindex{standard quotient} is a pair of
  1359. {\tt standard forms}
  1360. $( numr\,\,./\,\,denr)$, in LISP represented as $(numr\,\,.\,\,denr)$.
  1361. If the denominator is trivial, the standard form $1$ is
  1362. used. The constructor, selector and conversion functions are
  1363. \begin{center}
  1364. \begin{tabular}{|r|l|} \hline
  1365. numr(q) & select the numerator part \\
  1366. denr(q) & select the denominator part \\
  1367. f2q(f) & convert a standard form f to {\tt SQ}\\
  1368. simp(a) & convert algebraic form $a$ to {\tt SQ}\\
  1369. prepsq(q) & convert {\tt SQ} to algebraic form\\
  1370. \hline
  1371. \end{tabular}
  1372. \end{center}
  1373. \ttindex{numr}\ttindex{denr}\ttindex{f2q}
  1374. \ttindex{simp}\ttindex{prepsq}
  1375. Arithmetic with standard quotients is performed by the
  1376. functions
  1377. \begin{center}
  1378. \begin{tabular}{|r|l|} \hline
  1379. addsq(q1,q2)& $q1 + q2 $\\
  1380. negsq(q) & -q \\
  1381. subtrsq(q1,q2) & q1-q2 \\
  1382. multsq(q1,q2) & q1*q2 \\
  1383. quotsq(q1,q2) & $q1/q2$ \\
  1384. \hline
  1385. \end{tabular}
  1386. \end{center}
  1387. \ttindex{addsq}\ttindex{negsq}\ttindex{subtrsq}
  1388. \ttindex{multsq}\ttindex{quotsq}
  1389. Note that there is no zero test for standard quotients; instead
  1390. use the zero test for the numerator $null(numr(q))$.
  1391. When should you use {\tt standard quotients} and when {\tt standard forms}?
  1392. If you are sure that no denominator other
  1393. than one can occur you should use {\tt standard forms}, otherwise
  1394. {\tt standard quotients} are the only possible choice. You can of course
  1395. mix arithmetic with both, however that strategy is
  1396. not recommended unless you keep track carefully;
  1397. debugging is hard. Arithmetic functions have been coded
  1398. for maximum efficiency: none of them test the validity of their
  1399. arguments.
  1400. \subsection{Substitutions}
  1401. For {\tt substituting}\ttindex{substituting} kernels in {\tt standard forms}
  1402. or {\tt standard quotients}
  1403. by other kernels or arbitrary algebraic expressions the
  1404. following functions are available \index{subf}\index{subsq}:
  1405. \begin{center}
  1406. \begin{tabular}{|r|l|} \hline
  1407. subf(f,a)& substitute $a$ in {\tt SF} $f$ \\
  1408. subsq(q,a)& substitute $a$ in {\tt SQ} $q$ \\
  1409. \hline
  1410. \end{tabular}
  1411. \end{center}
  1412. where a is a list of pairs, each with a kernel to be replaced
  1413. in the $car$ and its replacement as algebraic form in the $cdr$
  1414. \footnote{The second argument of {\tt subf} and {\tt subsq}
  1415. is a typical association list structure.},
  1416. e.g.
  1417. \begin{verbatim}
  1418. uhu := simp('(expt(plus x y) 10));
  1419. otto:= subsq(uhu, '((x . 5) (y . (plus a b))));
  1420. \end{verbatim}
  1421. Here $x$ is replaced by 5 while y is replaced by $a+b$.
  1422. Note that
  1423. \begin{itemize}
  1424. \item both {\tt subf} and {\tt subsq} return a {\tt standard quotient}
  1425. (the substitution might have caused a non trivial denominator),
  1426. \item {\tt subf} and {\tt subsq} also introduce substitutions which have been
  1427. coded in rules - so it makes sense to call these routines with
  1428. $nil$ as the second argument if you have introduced a new rule and
  1429. some standard forms or standard quotients need to be re simplified
  1430. under these.
  1431. \end{itemize}
  1432. \subsection{Useful facilities for standard forms}
  1433. \subsubsection{Kernel list}
  1434. The function {\tt kernels}\ttindex{kernel} extracts all kernels
  1435. from a standard form and returns them as list.
  1436. \begin{verbatim}
  1437. kernels numr simp '(plus (expt x 3)(expt y 4));
  1438. \end{verbatim}
  1439. \noindent
  1440. will result in $(x\,y)$.
  1441. \subsubsection{Greatest common divisor}
  1442. The greatest common divisor of two polynomials is computed
  1443. by the function \ttindex{gcdf}{\tt *gcdf}. It takes as arguments
  1444. two standard forms and returns a standard form or a 1
  1445. if there is no non trivial common divisor.
  1446. \subsubsection{Factorization}
  1447. The function {\tt fctrf}\ttindex{fctrf} is the interface for calling the
  1448. {\tt factorizer}\ttindex{factorizer}. It takes a standard form as parameter
  1449. and returns a list which contains
  1450. \begin{itemize}
  1451. \item as first element the content of the polynomial - that is
  1452. the gcd of the coefficients or the ``common numeric factor",
  1453. \item as second and following elements the factors in the
  1454. form $({\tt SF} . m)$ where {\tt SF} is the factor as standard
  1455. form and $m$ is its multiplicity.
  1456. \end{itemize}
  1457. So calling $fctrf$ for $2x^2-2$ will result in
  1458. \begin{verbatim}
  1459. (2 ((((X . 1) . 1) . 1) . 1) ((((X . 1) . 1) . -1) . 1))
  1460. \end{verbatim}
  1461. Here you see the common domain factor 2 and the two factors
  1462. $x+1$ and $x-1$ as standard forms paired with their multiplicity
  1463. $1$.
  1464. \subsection{Variant: non-expanded standard form}
  1465. The standard form structure described so far is used by default
  1466. for the fully expanded expressions with common denominator.
  1467. By setting {\tt on factor}\ttindex{factor},
  1468. {\tt off exp}\ttindex{exp}, or {\tt off mcd}\ttindex{mcd}
  1469. the slots $mvar$ and $ldeg$ may be used in an exended style:
  1470. \begin{itemize}
  1471. \item $ldeg$ can be a negative number to represent a reciprocal factor,
  1472. \begin{verbatim}
  1473. off mcd; (x*a+y*b)/(a*b);
  1474. -1 -1
  1475. a *y + b *x
  1476. lisp ws;
  1477. (!*sq ((((a . -1) ((y . 1) . 1)) ((b . -1) ((x . 1) . 1))) . 1) t)
  1478. \end{verbatim}
  1479. Here the numerator form of the standard quotient is a sum where each
  1480. term is a product of one kernel with a positive and one kernel with
  1481. a neagative exponent.
  1482. \item $mvar$ may be a standard form to represent a factored polynomial,
  1483. \begin{verbatim}
  1484. on factor; (x^2+y)^2*(y+1);
  1485. 2 2
  1486. (x + y) *(y + 1)
  1487. lisp ws;
  1488. (!*sq (((((((x . 2) . 1) ((y . 1) . 1)) . 2) (((((y . 1) . 1) . 1)
  1489. . 1) . 1))) . 1) t)
  1490. \end{verbatim}
  1491. Here the numerator is a standard form in factored form where the inner polynomials
  1492. $(x+y)$ and $(y+1)$ are used as $mvar$s, the first one with the exponent 2
  1493. and the second one with exponent 1.
  1494. \end{itemize}
  1495. Special functions to work with composite standard forms:
  1496. \begin{center}
  1497. \begin{tabular}{|r|l|} \hline
  1498. sfp(m) & test if $m$ is a standard form (T) or a kernes(NIL) \\
  1499. expnd(f) & expand a standard form $f$ \\
  1500. \hline
  1501. \end{tabular}
  1502. \end{center}
  1503. \ttindex{sfp}\ttindex{expnd}
  1504. To distinguish between factored and expanded standard forms, use the
  1505. predicated {\tt sfp}: sfp applied to $mvar$ of a standard form returns T
  1506. if the main variable slot is occupied by a nested standard form.
  1507. To expand a factored standard form you may use the funtion {\tt expnd};
  1508. however, you need to turn the switch $exp$ on
  1509. during that call, e.g.
  1510. \begin{verbatim}
  1511. u:=expnd u where !*exp=t;
  1512. \end{verbatim}
  1513. Don't build non--expanded standard forms yourself -- otherwise you run
  1514. the risk to produce objects with a bad structure (e.g. a wrong term
  1515. order) resulting in wrong computational results. You better rely on the
  1516. standard routines for manipulating these objects -- as soon as
  1517. $*exp$ is off and $*factor$ is on they produce the product forms
  1518. anyway.
  1519. \section{Communication between algebraic and symbolic modes}
  1520. The main aim of programs written in symbolic mode
  1521. is to implement the evaluation steps to be invoked from
  1522. algebraic mode (top level {\reduce}). This section describes
  1523. how to link symbolic routines to algebraic mode
  1524. and how to exchange data between the modes.
  1525. \subsection{Algebraic variables}
  1526. A variable which has been declared {\tt share}\ttindex{share} by the {\reduce}
  1527. $share$ command is accessible from both modes in the
  1528. same style and it represents the same algebraic value.
  1529. A share variable is the easiest way to transfer data
  1530. between the modes. The only restriction is that a
  1531. symbolic program should assign only a legal algebraic
  1532. form to it - otherwise a later access in algebraic mode
  1533. can lead to problems. Example:
  1534. \begin{verbatim}
  1535. share hugo;
  1536. hugo :=(x+y)**2$
  1537. hugo;
  1538. symbolic;
  1539. hugo := reval {'sqrt,hugo};
  1540. algebraic;
  1541. hugo;
  1542. \end{verbatim}
  1543. Variables which have not been declared $share$ have
  1544. different values in symbolic and algebraic mode.
  1545. Nevertheless a symbolic mode program has access to the
  1546. algebraic value of a symbol:
  1547. \begin{itemize}
  1548. \item {\tt reval(x)}\ttindex{reval}: if the value of $x$ is a symbol
  1549. or if the parameter of $reval$ is a directly quoted symbol
  1550. the function returns the algebraic value associated with this
  1551. symbol, e.g. $reval('y)$,
  1552. \item {\tt setk}\ttindex{setk}{\tt (x,y)} sets the algebraic value of the expression
  1553. $x$ which then must be a symbol (or more general:
  1554. a {\tt kernel}\ttindex{kernel})
  1555. to $y$, e.g. $setk('z,reval'(plus\, u\, 17))$
  1556. \footnote{Read ``setk" as ``set kernel value", the {\reduce}
  1557. equivalent to the Standard LISP assignment function ``setq".}
  1558. \end{itemize}
  1559. Of course a clever LISP programmer easily sees how {\reduce}
  1560. organizes the assignment and storage of values to algebraic variables
  1561. in property lists, and he might be attempted
  1562. to use this knowledge for ``easier" access; please resist:
  1563. otherwise your program might not run in a future
  1564. version of {\reduce}.
  1565. \subsection{Calling symbolic routines from algebraic mode}
  1566. {\reduce} offers various ways to use symbolic routines
  1567. in algebraic mode such that they appear on the
  1568. algebraic level as genuine parts of {\reduce}.
  1569. These mainly differ in their strategy of evaluating parameters
  1570. (and results).
  1571. \subsubsection{Common protocol}
  1572. Some general protocol rules apply for {\reduce} symbolic mode
  1573. routines:
  1574. \begin{itemize}
  1575. \item A routine should check its parameters carefully; in
  1576. the case of illegal parameters the {\reduce} error handlers
  1577. should be invoked (see below).
  1578. \item If a routine cannot process its parameters for mathematical
  1579. reasons it best returns the expression which had caused the call
  1580. unchanged.
  1581. \item Evaluators should operate silently; events such as messages needed
  1582. for testing and program development should be carried out in
  1583. dependency of a switch.
  1584. \item A routine should return its result as a value
  1585. rather than printing it; for an isolated call in interactive
  1586. mode a printed result would be sufficient, but for following evaluation
  1587. steps the availability of an algebraic value is essential.
  1588. \end{itemize}
  1589. \subsubsection{Symbolic operator}
  1590. The simplest way to link a symbolic procedure to algebraic
  1591. mode is the {\tt symbolic operator}\ttindex{symbolic operator} declaration.
  1592. In that case the routine can be called by its proper name in algebraic
  1593. mode with {\reduce} first evaluating its parameters to fully
  1594. simplified algebraic forms. Upon return the result
  1595. should also be an algebraic form (or NIL). Example:
  1596. \begin{verbatim}
  1597. symbolic procedure my_plus(a,b);
  1598. begin scalar r;
  1599. print a; print b;
  1600. r := reval{'plus,a,b};
  1601. print r;
  1602. return r;
  1603. end;
  1604. symbolic operator my_plus;
  1605. \end{verbatim}
  1606. This routine receives two algebraic expressions and computes
  1607. their sum by calling the algebraic evaluator.
  1608. The calls the the LISP function {\tt print} have been inserted here
  1609. and in the following examples to show you the forms passed to the routine.
  1610. \subsubsection{Polyfn}
  1611. If the symbolic routine is specialized for computations
  1612. with pure polynomials it can be declared {\tt polyfn}\ttindex{polyfn}.
  1613. {\reduce} will evaluate the arguments for such a routine
  1614. to {\tt standard forms}\ttindex{standard forms} and expects that
  1615. the result also will have that form.
  1616. Example:
  1617. \begin{verbatim}
  1618. symbolic procedure poly_plus(a,b);
  1619. begin scalar r;
  1620. print a; print b;
  1621. r := addf(a,b);
  1622. print r;
  1623. return r;
  1624. end;
  1625. put('poly_plus,'polyfn,'poly_plus);
  1626. \end{verbatim}
  1627. This routine also adds its arguments
  1628. but it is specialized for polynomials. If called with
  1629. a non-polynomial form an error message will be generated.
  1630. In the {\tt put} statement the first argument is the algebraic
  1631. operator name and the third one is the name of the associated
  1632. evaluator function. These may differ.
  1633. \subsubsection{Psopfn}
  1634. The most general type of function is that of a {\tt psopfn}\ttindex{psopfn}.
  1635. {\reduce} will not evaluate the parameters for such a routine,
  1636. instead it passes the unevaluated list of parameters to the
  1637. function. The routine has to evaluate its parameters itself (of course
  1638. using the services of $reval$ and friends). So a {\tt psopfn}
  1639. can handle variable numbers of parameters. The result must
  1640. be an algebraic expression or $nil$. Example:
  1641. \begin{verbatim}
  1642. symbolic procedure multi_plus0 u;
  1643. begin scalar r;
  1644. r:=0;
  1645. for each x in u do
  1646. <<x:=reval x; print x;
  1647. r:=reval{'plus,r,x}
  1648. >>;
  1649. print r;
  1650. return r;
  1651. end;
  1652. put('multi_plus,'psopfn,'multi_plus0);
  1653. \end{verbatim}
  1654. This routine can be called with an arbitrary number of
  1655. parameters; it will evaluate them one after the other,
  1656. add them by calling $reval$ and return the sum as result.
  1657. Note that the name used in algebraic mode is $multi\_plus$
  1658. which is different from the name of the symbolic routine
  1659. doing the work. This is necessary because otherwise
  1660. the argument count check of {\reduce} would complain
  1661. as soon as the routine is called with more than one argument.
  1662. In the next example a {\tt psopfn} implements an operator with a
  1663. fixed number of arguments; it expects two numbers as
  1664. arguments and performs an extensive checking as any such routine
  1665. should do; again the name of the routine and the algebraic mode operator
  1666. are different:
  1667. \begin{verbatim}
  1668. symbolic procedure bin_plus0 u;
  1669. begin scalar p1,p2,r;
  1670. if length u neq 2 then rederr "illegal number of arguments";
  1671. p1:=reval car u; p2:=reval cadr u;
  1672. if not numberp p1 then typerr(p1,"number");
  1673. if not numberp p2 then typerr(p2,"number");
  1674. r:=p1+p2;
  1675. return r;
  1676. end;
  1677. put('bin_plus,'psopfn,'bin_plus0);
  1678. \end{verbatim}
  1679. The functions {\tt typerr}\ttindex{typerr} and {\tt rederr}\ttindex{rederr} are
  1680. explained in the section {\em error management}.
  1681. \subsubsection{Simpfn}
  1682. When you declare a new algebraic operator and want to assign a
  1683. special evaluation mode for it which cannot be written
  1684. in algebraic mode (e.g.\ as a rule set) you can create a
  1685. simplifier which has the task to convert each operator
  1686. expression to a {\tt standard quotient}\ttindex{standard quotient}.
  1687. A simplifier function is linked to the operator by
  1688. the property {\tt simpfn}\ttindex{simpfn}
  1689. and has one argument which is the unevaluated parameter
  1690. list of the operator expression. It will be called
  1691. every time the operator appears in an expression. It
  1692. must return a standard quotient. Example:
  1693. \begin{verbatim}
  1694. algebraic operator op_plus;
  1695. symbolic procedure simp_op_plus u;
  1696. begin scalar r;
  1697. r:=simp 0;
  1698. for each x in u do
  1699. <<x:=simp x; print x;
  1700. r:=addsq(r,x)
  1701. >>;
  1702. return print r;
  1703. end;
  1704. put('op_plus,'simpfn,'simp_op_plus);
  1705. \end{verbatim}
  1706. In many cases the simpfn is the method of choice as it is
  1707. best integrated into the {\reduce} evaluation process: its
  1708. results can immediately be used for subsequent calculations
  1709. while algebraic form results need to be converted to
  1710. standard quotients before combining them with other
  1711. formulae.
  1712. Note that a simpfn which cannot simplify its
  1713. argument must nevertheless return a {\tt standard quotient},
  1714. then with the unevaluable form as kernel. E.g.\ a function
  1715. for supporting the algebraic evaluation of the operator ``$<$":
  1716. \begin{verbatim}
  1717. algebraic operator <;
  1718. symbolic procedure simp_lessp u;
  1719. begin scalar a1,a2,d;
  1720. a1:=simp car u; a2:=simp cadr u;
  1721. d:=subtrsq(a1,a2);
  1722. if domainp denr d and domainp numr d then
  1723. return if !:minusp numr d then simp 1 else simp 0;
  1724. return mksq({'lessp,prepsq a1,prepsq a2},1);
  1725. end;
  1726. put('lessp,'simpfn,'simp_lessp);
  1727. \end{verbatim}
  1728. Here all comparisons with numeric items are reduced to zero or one
  1729. because of the equivalence of zero and ``false" in algebraic mode, while
  1730. in all other cases the non-evaluable expression is returned mapped by
  1731. the function {\tt mksq}\ttindex{mksq} which converts an algebraic
  1732. expression into a standard quotient, ensuring the
  1733. identity of composite kernels (see the section {\tt standard forms})
  1734. \ttindex{standard form}\ttindex{standard quotient}.
  1735. \subsection{Statements, forms}
  1736. An additional way to link symbolic entries to algebraic
  1737. mode is to invent a new syntactical unit. A {\reduce}
  1738. statement is introduced by assigning the
  1739. property {\tt stat}\ttindex{stat} = {\tt rlis}\ttindex{rlis}
  1740. to the leading keyword
  1741. of the new statement. The corresponding function will be called with
  1742. one parameter which is a list of the (unevaluated)
  1743. parameters of the statement. A statement normally
  1744. is called for its side effect rather than for its
  1745. value - so the result will be not interpreted as
  1746. an algebraic quantity ({\tt ws}\ttindex{WS} not set, printed
  1747. as symbolic list etc.). Example:
  1748. \begin{verbatim}
  1749. put('my_add,'stat,'rlis);
  1750. symbolic procedure my_add u;
  1751. begin scalar r;
  1752. r:= 0;
  1753. for each x in u do
  1754. <<x:=reval x;
  1755. r:=reval{'plus,x,r}
  1756. >>;
  1757. return r;
  1758. end;
  1759. \end{verbatim}
  1760. to be called by a statement
  1761. \begin{verbatim}
  1762. my_add x,x^2,x^3;
  1763. \end{verbatim}
  1764. A statement without parameters is introduced by the
  1765. property - value pair
  1766. {\tt stat}\ttindex{stat} = {\tt endstat}\ttindex{endstat}
  1767. because the statement ``end" is the most prominent
  1768. representative of this class.
  1769. For a more complicated syntax you can write a function
  1770. which preprocesses a statement before evaluating
  1771. it. Such preprocessors are linked to the leading
  1772. keyword by the property {\tt formfn}\ttindex{formfn}. However
  1773. writing a formfn is rather difficult as you will
  1774. have to organize the reading of the rest of the
  1775. statement yourself. This approach is not recommended
  1776. as the {\tt formfn} interface is rather delicate
  1777. and might be subject to future changes.
  1778. \subsection{Printing and messages}
  1779. For printing in symbolic mode you can use the Standard LISP
  1780. functions
  1781. \begin{center}
  1782. \begin{tabular}{|r|l|}\hline
  1783. print(u) & print u with LISP syntax and following linefeed\\
  1784. prin1(u) & print u with LISP syntax but without linefeed\\
  1785. prin2(u) & print u without LISP syntax and without linefeed\\
  1786. prin2t(u)& print u without LISP syntax but with linefeed\\
  1787. terpri() & print a single linefeed\\ \hline
  1788. \end{tabular}
  1789. \end{center}
  1790. {\em LISP syntax} here means that a string is surrounded by
  1791. string quotes and special characters in a symbol are
  1792. tagged by an exclamation mark.
  1793. However if you want to print an algebraic expression
  1794. in the same style as the {\reduce} {\tt write}\ttindex{write}
  1795. statement you should use the function {\tt writepri}\ttindex{writepri}.
  1796. This function needs two arguments, the first one
  1797. is the object to be printed which must be a string,
  1798. a number or an algebraic expresssion tagged with
  1799. a dynamic quote, e.g.\ using the function {\tt mkquote}\ttindex{mkquote}.
  1800. The second argument is one of $only$,
  1801. $first$, $nil$, and $last$ and controls linefeeds.
  1802. Example:
  1803. \begin{verbatim}
  1804. <<u:='(expt x 2);
  1805. writepri(" u= ",'first);
  1806. writepri(mkquote u,nil);
  1807. writepri(" printed in algebraic style",'last);
  1808. >>;
  1809. \end{verbatim}
  1810. For printing one single algebraic form you can also use the
  1811. function {\tt mathprint}\ttindex{mathrpint}:
  1812. \begin{verbatim}
  1813. u := '(expt x 3);
  1814. print u;
  1815. mathprint u;
  1816. \end{verbatim}
  1817. \section{Error management}
  1818. \subsection{Issue an error message}
  1819. When programming an application in symbolic mode, it may be
  1820. necessary to report an exception to the user, e.g.\
  1821. if an algebraic prerequisite for applying the algorithm is
  1822. not fulfilled.
  1823. There are several routines for signalling an error in
  1824. symbolic mode:
  1825. \begin{itemize}
  1826. \item The easiest way to complain about a bad algebraic form is
  1827. to call {\tt typerr}\ttindex{typerr}. This function has two parameters
  1828. $typerr(exp,str)$: the first one is an algebraic expression,
  1829. the bad object, and the second one is a string which describes
  1830. what the object should have been. When printed {\reduce}
  1831. will report $exp$ in mathematical notation and insert a string
  1832. ``illegal as". The current program is terminated.
  1833. \begin{verbatim}
  1834. u := '(plus x 1);
  1835. . . .
  1836. if not numberp u then typerr(u,"number");
  1837. \end{verbatim}
  1838. \item A general error can be reported using the function
  1839. {\tt rederr}\ttindex{rederr}; it prints some asterisks
  1840. and then its argument in pure LISP style (no mathematical format);
  1841. the argument can be a list - in that case the surrounding
  1842. brackets are omitted in output. The current program is terminated.
  1843. \begin{verbatim}
  1844. rederr "algorithm not applicable if denominator neq 1";
  1845. rederr {"never call me with ",u," again"};
  1846. \end{verbatim}
  1847. \item Similar to {\em rederr} the routine {\tt rerror}\ttindex{rerror}
  1848. terminates the run with an error message; it has
  1849. been designed for usage in a {\reduce} package enabling
  1850. the error handler to localize the error reason and to
  1851. provide additional information to the end user (e.g.\
  1852. via a {\tt help}\ttindex{help} system). It has 3 parameters:
  1853. $rerror(pack,nbr,mess)$ where $pack$ is the name of
  1854. the package (usually a quoted identifier), $nbr$ is
  1855. an integer error number local to the package, beginning
  1856. with 1 and $mess$ is the error message just like {\em rederr}.
  1857. \begin{verbatim}
  1858. rerror('asys,13,"remainder not zero");
  1859. \end{verbatim}
  1860. Wherever possible {\tt rerror} should be used instead of
  1861. {\tt rederr}.
  1862. \end{itemize}
  1863. \subsection{Catching errors}
  1864. On the other hand a symbolic program might want to react
  1865. to an exception which occurred in a calculation branch.
  1866. {\reduce} supports this by encapsulation with the routines
  1867. {\tt errorset*}\ttindex{errorset*} and {\tt errorset}
  1868. \ttindex{errorset}. You have to
  1869. construct the action to be encapsulated as a subroutine
  1870. call in prefix LISP syntax which is identical to
  1871. algebraic form syntax: a list where the first element
  1872. is the name of the function (usually a
  1873. quoted symbol) followed by the arguments; these
  1874. must be tagged by quote, best using the function
  1875. {\tt mkquote}\ttindex{mkquote}.
  1876. The second parameter describes the error mode: if $t$, an eventual
  1877. error during the evaluation will be reported to the user,
  1878. if $nil$ the error message will be suppressed. {\tt errorset}
  1879. additionally has a third parameter which tells the
  1880. error manager whether to print a backtrace or not in an
  1881. error case. The result of these functions will be
  1882. \begin{itemize}
  1883. \item in the case of an error an error code (its form depends
  1884. on the underlying LISP system),
  1885. \item otherwise the result of the computed value as {\tt car} of a list.
  1886. \end{itemize}
  1887. You should use the function {\tt errorp}\ttindex{errorp} for testing
  1888. whether the call failed or not; in the positive case
  1889. pick out the result by a $car$
  1890. access. Example:
  1891. \begin{verbatim}
  1892. begin scalar u,v;
  1893. . . .
  1894. q := errorset!*({'quotsq,mkquote(u),mkquote(v)},nil);
  1895. if errorp q then rederr "division failed" else
  1896. q:=car q;
  1897. . . .
  1898. \end{verbatim}
  1899. Note that you cannot write the expression to be
  1900. encapsulated in {\reduce} syntax here. And also $'(quotsq\,\, u\,\, v)$
  1901. would be incorrect because then $u$ and $v$ were
  1902. constants and not references to the local
  1903. variables $u$ and $v$. Only the $mkquote$ expressions
  1904. guarantee that at run time a list is generated where
  1905. the values of $u$ and $v$ are inserted as parameters for
  1906. the call.
  1907. \section{Compiling, modules, packages}
  1908. \subsection{Program modules}
  1909. It is a good practice to design a complex program
  1910. group in separate modules each residing in a
  1911. separate source file. You can use the {\reduce}
  1912. statement pair {\tt module}\ttindex{module} -
  1913. {\tt endmodule}\ttindex{endmodule}
  1914. to reflect this structure. A module has a name
  1915. which often will be identical with its source file
  1916. (without extension, of course). This correspondence
  1917. is not essential, but is very practical for the daily
  1918. work. As a side effect {\tt module} switches automatically
  1919. to symbolic mode during input and {\tt endmodule} switches
  1920. back to the original mode. A typical module in a file
  1921. would look like
  1922. \begin{verbatim}
  1923. module alggeo1; % Primitives for algebraic geometry.
  1924. % Author: Hugo Nobody, Nirwanatown, Utopia.
  1925. ....... the symbolic mode code
  1926. endmodule;
  1927. end;
  1928. \end{verbatim}
  1929. If this module resides in a file $alggeo1.red$ it can
  1930. either be read into a {\reduce} session by
  1931. \begin{verbatim}
  1932. in "alggeo1.red"$
  1933. \end{verbatim}
  1934. or it can be compiled to a fast loadable binary by
  1935. \begin{verbatim}
  1936. faslout "alggeo1";
  1937. in "alggeo1.red"$
  1938. faslend;
  1939. \end{verbatim}
  1940. You then can load this module by {load alggeo}.
  1941. Although {\reduce} currently does not yet rely exclusively on
  1942. declarations {\tt exports}\ttindex{exports} and {\tt imports}
  1943. \ttindex{imports}, these should be used in order to be
  1944. safe for the future. {\tt exports} should name all
  1945. entry points which the module offers for external access
  1946. and {\tt imports} is the list of modules
  1947. or packages which the module needs at run time or
  1948. during compilation.
  1949. \subsection{Packages}
  1950. If your application consists of several modules you can
  1951. design it as a {\tt package}\index{package}. A package is a
  1952. collection of modules which form a unit but allow you an individual
  1953. management, e.g.\ updating and recompilation. A package
  1954. is defined by a header module which should have the
  1955. name of the package as the module name. This module
  1956. then contains a declaration for the package by the
  1957. function {\tt create-package}\index{create-package}, which expects as
  1958. first parameter a list of the modules which belong to the package
  1959. (this list must begin with the header package) and
  1960. a second dummy parameter to be set to $nil$ (this
  1961. parameter is meaningful only for modules in the
  1962. {\reduce} kernel). Additionally the header
  1963. module should contain all global declarations
  1964. for the complete package, e.g. {\tt fluid, global}
  1965. declarations and {\tt exports} and {\tt imports}
  1966. statements.
  1967. Also, all macros, smacros used in more than one module
  1968. in the package should be defined in the header module.
  1969. As long as you develop your
  1970. application and frequently recompile single modules
  1971. it would be practical to replace the function
  1972. {\tt create-package} by a loop calling {\tt load\_package} (please
  1973. note the underscore: {\tt load-package} is a different
  1974. function not usable here). You then can load the complete package
  1975. by one call to {\tt load\_package} for the header
  1976. module. Example:
  1977. \begin{verbatim}
  1978. module alggeo; % Algebraic geometry support.
  1979. % Author: Hugo Nobody, Nirwanatown, Utopia.
  1980. % create_package('(alggeo alggeo1 alggeo2 alggeo3));
  1981. for each x in '(alggeo1 alggeo2 alggeo3) do load x;
  1982. fluid '(alggeo_vars!* ......);
  1983. exports ...
  1984. ... and so on
  1985. endmodule;
  1986. end;
  1987. \end{verbatim}
  1988. Later you can replace the load loop {\tt load} by a correct
  1989. {\tt create-package} expression - you will then have to compile the
  1990. object as one big binary with the header module as the first
  1991. entry.
  1992. For compiling you use the function {\tt faslout} which creates
  1993. a fast loading file - see the corresponding section in the User's
  1994. manual.
  1995. \section{Coding suggestions}
  1996. In order to guarantee that your program is as portable
  1997. and version independent as possible
  1998. the following rules may be useful. Note that these are recommendations
  1999. only - your program may do a good job for you even if
  2000. you ignore all of them.
  2001. \begin{itemize}
  2002. \item Don't use functions from the underlying LISP which are
  2003. not explicitly part of {\reduce} or {\tt standard lisp}
  2004. - they will probably be missing in other support systems.
  2005. \item Don't rely on character case.
  2006. Some implementations support upper case
  2007. output, others prefer lower case. As the tendency goes
  2008. towards lower case, the best policy is to use lower
  2009. case characters only, except in strings or comments.
  2010. \item Use proper indentation. Take the {\reduce}
  2011. sources as example. If the indentation corresponds
  2012. to the block structure your programs will be better
  2013. readable.
  2014. \item Don't produce lines with more than 72 characters.
  2015. There are still computers and networks around which
  2016. have problem if the size of the good old punched card
  2017. is exceeded.
  2018. \item Write comments. The major entry point routines of your
  2019. symbolic code should have one comment line following the
  2020. procedure declaration; this comment should be one or more
  2021. complete English sentences, beginning with an upper case
  2022. character and ending with a dot.
  2023. \item Try to avoid name conflicts. It is a common policy to
  2024. name global and fluid variables with a trailing asterisk
  2025. and to use a common name prefix for the procedure names.
  2026. \item If you produce a large piece of software, organize it as
  2027. a {\reduce} package.
  2028. \end{itemize}
  2029. \section{Appendix: Standard LISP extensions}
  2030. The following typical LISP functions are defined in the {\tt support}
  2031. module of the {\tt rlisp} package.
  2032. \vspace{5mm}
  2033. {\tt atsoc}($u$:any,$p$:alist)
  2034. \noindent
  2035. Same as {\tt assoc}, but using the operator $eq$ instead of $equal$
  2036. for the search. $atsoc$ can be applied only if the identity
  2037. of the object to be searched for is guaranteed, e.g.\ for symbols.
  2038. It is substantially faster than {\tt assoc}.
  2039. \vspace{5mm}
  2040. {\tt copyd}($u$:id,$v$:id)
  2041. \noindent
  2042. Copies the procedure definition of $v$ to the symbol $u$. Afterwards
  2043. the procedure can be called by using the name $u$. Frequently
  2044. used for embedding a function, e.g.\ for implementing a private
  2045. trace:
  2046. \begin{verbatim}
  2047. if null getd 'myprog_old then copyd('myprog_old,'myprog);
  2048. symbolic procedure myprog(u);
  2049. <<print {"calling myprog with parameter ",u};
  2050. myprog_old(u)>>
  2051. \end{verbatim}
  2052. \vspace{5mm}
  2053. {\tt eqcar}($u$:any,$v$:any)
  2054. \noindent
  2055. Implements the frequently needed test {\em pairp u and car u eq v}.
  2056. \vspace{5mm}
  2057. {\tt listp}($u$:any)
  2058. \noindent
  2059. Returns t if $u$ is a top level list ending with a $nil$.
  2060. \vspace{5mm}
  2061. {\tt mkquote}($u$:any)
  2062. \noindent
  2063. tags $u$ with a quote. This function is useful for cases where
  2064. a LISP eval situation is given, e.g.\ for coding for an $errorset$
  2065. or for $writepri$.
  2066. \vspace{5mm}
  2067. {\tt reversip}($u$:list)
  2068. \noindent
  2069. Reverses the elements of $l$ in place - faster than $reverse$, but
  2070. desctroys the input list.
  2071. \vspace{5mm}
  2072. {\tt smember}($u$:any,$v$:any)
  2073. \noindent
  2074. Similar to $member$ this routine tests whether $u$ occurs in
  2075. the structure $v$, however in an arbitrarily deep nesting.
  2076. While $member$ tests only the top level
  2077. list, $smember$ descends down all branches of the tree.
  2078. \vspace{5mm}
  2079. {\tt smemq}($u$:any,$v$:any)
  2080. \noindent
  2081. Same as $smember$, however using $eq$ as test instead of $equal$.
  2082. \vspace{5mm}
  2083. \noindent
  2084. The following routines handle lists as sets (every element
  2085. at most once):
  2086. {\tt union}($u$:any,$v$:any)
  2087. {\tt intersection}($u$:any,$v$:any)
  2088. {\tt setdiff}($u$:any,$v$:any) % set difference
  2089. \vspace{5mm}
  2090. \noindent
  2091. The Standard LISP {\tt apply} function requires that the parameters
  2092. for the function to be applied are encoded as a list. For standard
  2093. cases of 1,2 or 3 parameters the following variants allow an easier
  2094. encoding:
  2095. {\tt apply1}($u$:id,$u$:any)
  2096. {\tt apply2}($u$:id,$u$:any,$v$:any)
  2097. {\tt apply3}($u$:id,$u$:any,$v$:any,$w$:any)
  2098. \printindex
  2099. \end{document}