home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume24 / gnucalc / part48 < prev    next >
Encoding:
Text File  |  1991-11-01  |  55.5 KB  |  1,349 lines

  1. Newsgroups: comp.sources.misc
  2. From: daveg@synaptics.com (David Gillespie)
  3. Subject:  v24i096:  gnucalc - GNU Emacs Calculator, v2.00, Part48/56
  4. Message-ID: <1991Nov1.183926.21293@sparky.imd.sterling.com>
  5. X-Md4-Signature: eb45f40d4c9bff375844f727facb0400
  6. Date: Fri, 1 Nov 1991 18:39:26 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8.  
  9. Submitted-by: daveg@synaptics.com (David Gillespie)
  10. Posting-number: Volume 24, Issue 96
  11. Archive-name: gnucalc/part48
  12. Environment: Emacs
  13. Supersedes: gmcalc: Volume 13, Issue 27-45
  14.  
  15. ---- Cut Here and unpack ----
  16. #!/bin/sh
  17. # do not concatenate these parts, unpack them in order with /bin/sh
  18. # file calc.texinfo continued
  19. #
  20. if test ! -r _shar_seq_.tmp; then
  21.     echo 'Please unpack part 1 first!'
  22.     exit 1
  23. fi
  24. (read Scheck
  25.  if test "$Scheck" != 48; then
  26.     echo Please unpack part "$Scheck" next!
  27.     exit 1
  28.  else
  29.     exit 0
  30.  fi
  31. ) < _shar_seq_.tmp || exit 1
  32. if test ! -f _shar_wnt_.tmp; then
  33.     echo 'x - still skipping calc.texinfo'
  34. else
  35. echo 'x - continuing file calc.texinfo'
  36. sed 's/^X//' << 'SHAR_EOF' >> 'calc.texinfo' &&
  37. but @samp{linnt(2,x)} and @samp{linnt(y,x)} are left unevaluated
  38. (in other words, these formulas are considered to be only ``trivially''
  39. linear in @cite{x}).
  40. X
  41. All four linearity-testing functions allow you to omit the second
  42. argument, in which case the input may be linear in any non-constant
  43. formula.  Here, the @cite{a=0}, @cite{b=1} case is also considered
  44. trivial, and only constant values for @cite{a} and @cite{b} are
  45. recognized.  Thus, @samp{lin(2 x y)} returns @cite{[0, 2, x y]},
  46. @samp{lin(2 - x y)} returns @cite{[2, -1, x y]}, and @samp{lin(x y)}
  47. returns@cite{[0, 1, x y]}.  The @code{linnt} function would allow the
  48. first two cases but not the third.  Also, neither @code{lin} nor
  49. @code{linnt} accept plain constants as linear in the one-argument
  50. case: @samp{islin(2,x)} is true, but @samp{islin(2)} is false.
  51. X
  52. @tindex istrue
  53. The @samp{istrue(a)} function returns 1 if @cite{a} is a nonzero
  54. number, or 0 if @cite{a} is anything else.  Calls to @code{istrue}
  55. can only be entered or manipulated if @kbd{m O} mode is used to
  56. make sure they are not evaluated prematurely.
  57. X
  58. @node Rewrite Rules, , Logical Operations, Algebra
  59. @section Rewrite Rules
  60. X
  61. @noindent
  62. @cindex Rewrite rules
  63. @cindex Transformations
  64. @cindex Pattern matching
  65. @kindex a r
  66. @pindex calc-rewrite
  67. @tindex rewrite
  68. The @kbd{a r} (@code{calc-rewrite}) [@code{rewrite}] command makes
  69. substitutions in a formula according to a specified pattern or patterns
  70. known as @dfn{rewrite rules}.  Whereas @kbd{a b} (@code{calc-substitute})
  71. matches literally, so that substituting @samp{sin(x)} with @samp{cos(x)}
  72. matches only the @code{sin} function applied to the variable @code{x},
  73. rewrite rules match general kinds of formulas; rewriting using the rule
  74. @samp{sin(x) := cos(x)} matches @code{sin} of any argument and replaces
  75. it with @code{cos} of that same argument.  The only significance of the
  76. name @code{x} is that the same name is used on both sides of the rule.
  77. X
  78. @menu
  79. * Entering Rewrite Rules::
  80. * Basic Rewrite Rules::
  81. * Conditional Rewrite Rules::
  82. * Algebraic Properties of Rewrite Rules::
  83. * Other Features of Rewrite Rules::
  84. * Composing Patterns in Rewrite Rules::
  85. * Nested Formulas with Rewrite Rules::
  86. * Multi-Phase Rewrite Rules::
  87. * Selections with Rewrite Rules::
  88. * Matching Commands::
  89. * Automatic Rewrites::
  90. * Debugging Rewrites::
  91. * Examples of Rewrite Rules::
  92. @end menu
  93. X
  94. @node Entering Rewrite Rules, Basic Rewrite Rules, Rewrite Rules, Rewrite Rules
  95. @subsection Entering Rewrite Rules
  96. X
  97. @noindent
  98. Rewrite rules normally use the ``assignment'' operator @samp{old := new}.
  99. This operator is equivalent to the function call @samp{assign(old, new)}.
  100. The @code{assign} function is undefined by itself in Calc, so an
  101. assignment formula like a rewrite rule will be left alone by ordinary
  102. Calc commands.  But certain commands, like the rewrite system, interpret
  103. assignments in special ways.
  104. X
  105. For example, the rule @samp{sin(x)^2 := 1-cos(x)^2} says to replace
  106. every occurrence of the sine of something, squared, with one minus the
  107. square of the cosine of that same thing.  All by itself it does nothing,
  108. but when given to the @kbd{a r} command it turns that command into
  109. a sine-squared-to-cosine-squared converter.
  110. X
  111. To specify a set of rules, make a vector of rules.
  112. X
  113. When @kbd{a r} prompts you to enter the rewrite rules, you can answer
  114. in several ways:
  115. X
  116. @enumerate
  117. @item
  118. With a rule:  @kbd{f(x) := g(x) RET}.
  119. @item
  120. With a vector of rules:  @kbd{[f1(x) := g1(x), f2(x) := g2(x)] RET}.
  121. (You can omit the enclosing square brackets if you wish.)
  122. @item
  123. With the name of a variable that contains the rule or rules vector:
  124. @kbd{myrules RET}.
  125. @item
  126. With any formula except a rule, a vector, or a variable name; this
  127. will be interpreted as the @samp{old} half of a rewrite rule,
  128. and you will be prompted a second time for the @samp{new} half:
  129. @kbd{f(x) @key{RET} g(x) @key{RET}}.
  130. @item
  131. With a blank line, in which case the rule, rules vector, or variable
  132. will be taken from the top of the stack (and the formula to be
  133. rewritten will come from the second-to-top position).
  134. @end enumerate
  135. X
  136. If you enter the rules directly (as opposed to using rules stored
  137. in a variable), those rules will be put into the Trail so that you
  138. can retrieve them later.  @xref{Trail Commands}.
  139. X
  140. It is most convenient to store rules you use often in a variable and
  141. invoke them by naming the variable.  The @kbd{s e} (@code{calc-edit-variable})
  142. command is an easy way to create or edit a rule set stored in a variable.
  143. You may also wish to use @kbd{s p} (@code{calc-permanent-variable}) to
  144. save your rules permanently; @pxref{Operations on Variables}.@refill
  145. X
  146. Rewrite rules are compiled into a special internal form for faster
  147. matching.  If you enter a rule set directly it must be recompiled
  148. for every @kbd{a r} command.  If you store the rules in a variable
  149. and refer to them through that variable, they will be compiled
  150. once and saved away along with the variable for later reference.
  151. This is another good reason to store your rules in a variable.
  152. X
  153. Calc also accepts an obsolete notation for rules, as vectors
  154. @samp{[old, new]}.  But because it is easily confused with a vector
  155. of two rules, the use of this notation is no longer recommended.
  156. X
  157. @node Basic Rewrite Rules, Conditional Rewrite Rules, Entering Rewrite Rules, Rewrite Rules
  158. @subsection Basic Rewrite Rules
  159. X
  160. @noindent
  161. To match a particular formula @cite{x} with a particular rewrite rule
  162. @samp{old := new}, Calc compares the structure of @cite{x} with the
  163. structure of @samp{old}.  Variables that appear in @samp{old} are
  164. treated as @dfn{meta-variables}; the corresponding positions in @cite{x}
  165. may contain any sub-formulas.  For example, the pattern @samp{f(x,y)}
  166. would match the expression @samp{f(12, a+1)} with the meta-variable
  167. @samp{x} corresponding to 12 and with @samp{y} corresponding to
  168. @samp{a+1}.  However, this pattern would not match @samp{f(12)} or
  169. @samp{g(12, a+1)}, since there is no assignment of the meta-variables
  170. that will make the pattern match these expressions.  Notice that if
  171. the pattern is a single meta-variable, it will match any expression.
  172. X
  173. If a given meta-variable appears more than once in @samp{old}, the
  174. corresponding sub-formulas of @cite{x} must be identical.  Thus
  175. the pattern @samp{f(x,x)} would match @samp{f(12, 12)} and
  176. @samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(x+y, y+x)}.
  177. X
  178. Things other than variables must match exactly between the pattern
  179. and the target formula.  To match a particular variable exactly, use
  180. the pseudo-function @samp{quote(v)} in the pattern.  For example, the
  181. pattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or
  182. @samp{sin(a)+y}.
  183. X
  184. The special variable names @samp{e}, @samp{pi}, @samp{i}, @samp{phi},
  185. @samp{gamma}, @samp{inf}, @samp{uinf}, and @samp{nan} always match
  186. literally.  Thus the pattern @samp{sin(d + e + f)} acts exactly like
  187. @samp{sin(d + quote(e) + f)}.
  188. X
  189. If the @samp{old} pattern is found to match a given formula, that
  190. formula is replaced by @samp{new}, where any occurrences in @samp{new}
  191. of meta-variables from the pattern are replaced with the sub-formulas
  192. that they matched.  Thus, applying the rule @samp{f(x,y) := g(y+x,x)}
  193. to @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}.
  194. X
  195. The normal @kbd{a r} command applies rewrite rules over and over
  196. throughout the target formula until no further changes are possible.
  197. Use @kbd{C-u 1 a r} to make only one change at a time.
  198. X
  199. @node Conditional Rewrite Rules, Algebraic Properties of Rewrite Rules, Basic Rewrite Rules, Rewrite Rules
  200. @subsection Conditional Rewrite Rules
  201. X
  202. @noindent
  203. A rewrite rule can also be @dfn{conditional}, written in the form
  204. @samp{old := new :: cond}.  (There is also the obsolete form
  205. @samp{[old, new, cond]}.)  If a @samp{cond} part is present in the
  206. rule, this is an additional condition that must be satisfied before
  207. the rule is accepted.  Once @samp{old} has been successfully matched
  208. to the target expression, @samp{cond} is evaluated (with all the
  209. meta-variables substituted for the values they matched) and simplified
  210. with @kbd{a s} (@code{calc-simplify}).  If the result is a nonzero
  211. number or any other object known to be nonzero (@pxref{Declarations}),
  212. the rule is accepted.  If the result is zero or if it is a symbolic
  213. formula that is not known to be nonzero, the rule is rejected.
  214. @xref{Logical Operations}, for a number of functions that return
  215. 1 or 0 according to the results of various tests.
  216. X
  217. For example, the formula @samp{n > 0} simplifies to 1 or 0 if @cite{n}
  218. is replaced by a positive or nonpositive number, respectively (or if
  219. @cite{n} has been declared to be positive or nonpositive).  Thus,
  220. the rule @samp{f(x,y) := g(y+x,x) :: x+y > 0} would apply to
  221. @samp{f(0, 4)} but not to @samp{f(-3, 2)} or @samp{f(12, a+1)}
  222. (assuming no outstanding declarations for @cite{a}).  In the case of
  223. @samp{f(-3, 2)}, the condition can be shown not to be satisfied; in
  224. the case of @samp{f(12, a+1)}, the condition merely cannot be shown
  225. to be satisfied, but that is enough to reject the rule.
  226. X
  227. While Calc will use declarations to reason about variables in the
  228. formula being rewritten, declarations do not apply to meta-variables.
  229. For example, the rule @samp{[f(a), g(a+1)]} will match for any values
  230. of @samp{a}, such as complex numbers, vectors, or formulas, even if
  231. @samp{a} has been declared to be real or scalar.  If you want the
  232. meta-variable @samp{a} to match only literal real numbers, use
  233. @samp{f(a) := g(a+1) :: real(a)}.  If you want @samp{a} to match only
  234. reals and formulas which are provably real, use @samp{dreal(a)} as
  235. the condition.
  236. X
  237. The @samp{::} operator is a shorthand for the @code{condition}
  238. function; @samp{old := new :: cond} is equivalent to the formula
  239. @samp{condition(assign(old, new), cond)}.
  240. X
  241. If you have several conditions, you can use @samp{... :: c1 :: c2 :: c3}
  242. or @samp{... :: c1 && c2 && c3}.  The two are entirely equivalent.
  243. X
  244. It is also possible to embed conditions inside the pattern:
  245. @samp{f(x :: x>0, y) := g(y+x, x)}.  This is purely a notational
  246. convenience, though; where a condition appears in a rule has no
  247. effect on when it is tested.  The rewrite-rule compiler automatically
  248. decides when it is best to test each condition while a rule is being
  249. matched.
  250. X
  251. Certain conditions are handled as special cases by the rewrite rule
  252. system and are tested very efficiently:  Where @cite{x} is any
  253. meta-variable, these conditions are @samp{integer(x)}, @samp{real(x)},
  254. @samp{constant(x)}, @samp{negative(x)}, @samp{x >= y} where @cite{y}
  255. is either a constant or another meta-variable and @samp{>=} may be
  256. replaced by any of the six relational operators, and @samp{x % a = b}
  257. where @cite{a} and @cite{b} are constants.  Other conditions, like
  258. @samp{x >= y+1} or @samp{dreal(x)}, will be less efficient to check
  259. since Calc must bring the whole evaluator and simplifier into play.
  260. X
  261. An interesting property of @samp{::} is that neither of its arguments
  262. will be touched by Calc's default simplifications.  This is important
  263. because conditions often are expressions that cannot safely be
  264. evaluated early.  For example, the @code{typeof} function never
  265. remains in symbolic form; entering @samp{typeof(a)} will put the
  266. number 100 (the type code for variables like @samp{a}) on the stack.
  267. But putting the condition @samp{... :: typeof(a) = 6} on the stack
  268. is safe since @samp{::} prevents the @code{typeof} from being
  269. evaluated until the condition is actually used by the rewrite system.
  270. X
  271. Since @samp{::} protects its lefthand side, too, you can use a dummy
  272. condition to protect a rule that itself must not evaluate early.
  273. For example, it's not safe to put @samp{a(f,x) := apply(f, [x])} on
  274. the stack because it will immediately evaluate to @samp{a(f,x) := f(x)},
  275. where the meta-variable-ness of @code{f} on the righthand side has been
  276. lost.  But @samp{a(f,x) := apply(f, [x]) :: 1} is safe, and of course
  277. the condition @samp{1} is always true (nonzero) so it has no effect on
  278. the functioning of the rule.  (The rewrite compiler will ensure that
  279. it doesn't even impact the speed of matching the rule.)
  280. X
  281. @node Algebraic Properties of Rewrite Rules, Other Features of Rewrite Rules, Conditional Rewrite Rules, Rewrite Rules
  282. @subsection Algebraic Properties of Rewrite Rules
  283. X
  284. @noindent
  285. The rewrite mechanism understands the algebraic properties of functions
  286. like @samp{+} and @samp{*}.  In particular, pattern matching takes
  287. the associativity and commutativity of the following functions into
  288. account:
  289. X
  290. @smallexample
  291. + - *  = !=  && ||  and or xor  vint vunion vxor  gcd lcm  max min  beta
  292. @end smallexample
  293. X
  294. For example, the rewrite rule:
  295. X
  296. @example
  297. a x + b x  :=  (a + b) x
  298. @end example
  299. X
  300. @noindent
  301. will match formulas of the form,
  302. X
  303. @example
  304. a x + b x,  x a + x b,  a x + x b,  x a + b x
  305. @end example
  306. X
  307. Rewrites also understand the relationship between the @samp{+} and @samp{-}
  308. operators.  The above rewrite rule will also match the formulas,
  309. X
  310. @example
  311. a x - b x,  x a - x b,  a x - x b,  x a - b x
  312. @end example
  313. X
  314. @noindent
  315. by matching @samp{b} in the pattern to @samp{-b} from the formula.
  316. X
  317. Applied to a sum of many terms like @samp{r + a x + s + b x + t}, this
  318. pattern will check all pairs of terms for possible matches.  The rewrite
  319. will take whichever suitable pair it discovers first.
  320. X
  321. In general, a pattern using an associative operator like @samp{a + b}
  322. will try @i{2 n} different ways to match a sum of @i{n} terms
  323. like @samp{x + y + z - w}.  First, @samp{a} is matched against each
  324. of @samp{x}, @samp{y}, @samp{z}, and @samp{-w} in turn, with @samp{b}
  325. being matched to the remainders @samp{y + z - w}, @samp{x + z - w}, etc.
  326. If none of these succeed, then @samp{b} is matched against each of the
  327. four terms with @samp{a} matching the remainder.  Half-and-half matches,
  328. like @samp{(x + y) + (z - w)}, are not tried.
  329. X
  330. Note that @samp{*} is not commutative when applied to matrices, but
  331. rewrite rules pretend that it is.  If you type @kbd{m v} to enable
  332. matrix mode (@pxref{Matrix Mode}), rewrite rules will match @samp{*}
  333. literally, ignoring its usual commutativity property.  (In the
  334. current implementation, the associativity also vanishes---it is as
  335. if the pattern had been enclosed in a @code{plain} marker; see below.)
  336. If you are applying rewrites to formulas with matrices, it's best to
  337. enable matrix mode first to prevent algebraically incorrect rewrites
  338. from occurring.
  339. X
  340. The pattern @samp{-x} will actually match any expression.  For example,
  341. the rule
  342. X
  343. @example
  344. f(-x)  :=  -f(x)
  345. @end example
  346. X
  347. @noindent
  348. will rewrite @samp{f(a)} to @samp{-f(-a)}.  To avoid this, either use
  349. a @code{plain} marker as described below, or add a @samp{negative(x)}
  350. condition.  The @code{negative} function is true if its argument
  351. ``looks'' negative, for example, because it is a negative number or
  352. because it is a formula like @samp{-x}.  The new rule using this
  353. condition is:
  354. X
  355. @example
  356. f(x)  :=  -f(-x)  :: negative(x)    @r{or, equivalently,}
  357. f(-x)  :=  -f(x)  :: negative(-x)
  358. @end example
  359. X
  360. In the same way, the pattern @samp{x - y} will match the sum @samp{a + b}
  361. by matching @samp{y} to @samp{-b}.
  362. X
  363. The pattern @samp{a b} will also match the formula @samp{x/y} if
  364. @samp{y} is a number.  Thus the rule @samp{a x + b x := (a+b) x}
  365. will also convert @samp{a x + x / 2} to @samp{(a + 0.5) x} (or
  366. @samp{(a + 1:2) x}, depending on the current fraction mode).
  367. X
  368. Calc will @emph{not} take other liberties with @samp{*}, @samp{/}, and
  369. @samp{^}.  For example, the pattern @samp{f(a b)} will not match
  370. @samp{f(x^2)}, and @samp{f(a + b)} will not match @samp{f(2 x)}, even
  371. though conceivably these patterns could match with @samp{a = b = x}.
  372. Nor will @samp{f(a b)} match @samp{f(x / y)} if @samp{y} is not a
  373. constant, even though it could be considered to match with @samp{a = x}
  374. and @samp{b = 1/y}.  The reasons are partly for efficiency, and partly
  375. because while few mathematical operations are substantively different
  376. for addition and subtraction, often it is preferable to treat the cases
  377. of multiplication, division, and integer powers separately.
  378. X
  379. Even more subtle is the rule set
  380. X
  381. @example
  382. [ f(a) + f(b) := f(a + b),  -f(a) := f(-a) ]
  383. @end example
  384. X
  385. @noindent
  386. attempting to match @samp{f(x) - f(y)}.  You might think that Calc
  387. will view this subtraction as @samp{f(x) + (-f(y))} and then apply
  388. the above two rules in turn, but actually this will not work because
  389. Calc only does this when considering rules for @samp{+} (like the
  390. first rule in this set).  So it will see first that @samp{f(x) + (-f(y))}
  391. does not match @samp{f(a) + f(b)} for any assignments of the
  392. meta-variables, and then it will see that @samp{f(x) - f(y)} does
  393. not match @samp{-f(a)} for any assignment of @samp{a}.  Because Calc
  394. tries only one rule at a time, it will not be able to rewrite
  395. @samp{f(x) - f(y)} with this rule set.  An explicit @samp{f(a) - f(b)}
  396. rule will have to be added.
  397. X
  398. Another thing patterns will @emph{not} do is break up complex numbers.
  399. The pattern @samp{myconj(a + b i) := a - b i} will work for formulas
  400. involving the special constant @samp{i} (such as @samp{3 - 4 i}), but
  401. it will not match actual complex numbers like @samp{(3, -4)}.  A version
  402. of the above rule for complex numbers would be
  403. X
  404. @example
  405. myconj(a)  :=  re(a) - im(a) (0,1)  :: im(a) != 0
  406. @end example
  407. X
  408. @noindent
  409. (Because the @code{re} and @code{im} functions understand the properties
  410. of the special constant @samp{i}, this rule will also work for
  411. @samp{3 - 4 i}.  In fact, this particular rule would probably be better
  412. without the @samp{im(a) != 0} condition, since if @samp{im(a) = 0} the
  413. righthand side of the rule will still give the correct answer for the
  414. conjugate of a real number.)
  415. X
  416. It is also possible to specify optional arguments in patterns.  The rule
  417. X
  418. @example
  419. opt(a) x + opt(b) (x^opt(c) + opt(d))  :=  f(a, b, c, d)
  420. @end example
  421. X
  422. @noindent
  423. will match the formula
  424. X
  425. @example
  426. 5 (x^2 - 4) + 3 x
  427. @end example
  428. X
  429. @noindent
  430. in a fairly straightforward manner, but it will also match reduced
  431. formulas like
  432. X
  433. @example
  434. x + x^2,    2(x + 1) - x,    x + x
  435. @end example
  436. X
  437. @noindent
  438. producing, respectively,
  439. X
  440. @example
  441. f(1, 1, 2, 0),   f(-1, 2, 1, 1),   f(1, 1, 1, 0)
  442. @end example
  443. X
  444. (The latter two formulas can be entered only if default simplifications
  445. have been turned off with @kbd{m O}.)
  446. X
  447. The default value for a term of a sum is zero.  The default value
  448. for a part of a product, for a power, or for the denominator of a
  449. quotient, is one.  Also, @samp{-x} matches the pattern @samp{opt(a) b}
  450. with @samp{a = -1}.
  451. X
  452. In particular, the distributive-law rule can be refined to
  453. X
  454. @example
  455. opt(a) x + opt(b) x  :=  (a + b) x
  456. @end example
  457. X
  458. @noindent
  459. so that it will convert, e.g., @samp{a x - x}, to @samp{(a - 1) x}.
  460. X
  461. The pattern @samp{opt(a) + opt(b) x} matches any formula which is
  462. linear in @samp{x}.  You can also use the @code{lin} and @code{islin}
  463. functions with rewrite conditions to test for this; @pxref{Logical
  464. Operations}.  These functions are not as convenient to use in rewrite
  465. rules, but they recognize more kinds of formulas as linear:
  466. @samp{x/z} is considered linear with @cite{b = 1/z} by @code{lin},
  467. but it will not match the above pattern because that pattern calls
  468. for a multiplication, not a division.
  469. X
  470. As another example, the obvious rule to replace @samp{sin(x)^2 + cos(x)^2}
  471. by 1,
  472. X
  473. @example
  474. sin(x)^2 + cos(x)^2  :=  1
  475. @end example
  476. X
  477. @noindent
  478. misses many cases because the sine and cosine may both be multiplied by
  479. an equal factor.  Here's a more successful rule:
  480. X
  481. @example
  482. opt(a) sin(x)^2 + opt(a) cos(x)^2  :=  a
  483. @end example
  484. X
  485. Note that this rule will @emph{not} match @samp{sin(x)^2 + 6 cos(x)^2}
  486. because one @cite{a} would have ``matched'' 1 while the other matched 6.
  487. X
  488. Calc automatically converts a rule like
  489. X
  490. @example
  491. f(x-1, x)  :=  g(x)
  492. @end example
  493. X
  494. @noindent
  495. into the form
  496. X
  497. @example
  498. f(temp, x)  :=  g(x)  :: temp = x-1
  499. @end example
  500. X
  501. @noindent
  502. (where @code{temp} stands for a new, invented meta-variable that
  503. doesn't actually have a name).  This modified rule will successfully
  504. match @samp{f(6, 7)}, binding @samp{temp} and @samp{x} to 6 and 7,
  505. respectively, then verifying that they differ by one even though
  506. @samp{6} does not superficially look like @samp{x-1}.
  507. X
  508. However, Calc does not solve equations to interpret a rule.  The
  509. following rule,
  510. X
  511. @example
  512. f(x-1, x+1)  :=  g(x)
  513. @end example
  514. X
  515. @noindent
  516. will not work.  That is, it will match @samp{f(a - 1 + b, a + 1 + b)}
  517. but not @samp{f(6, 8)}.  Calc always interprets at least one occurrence
  518. of a variable by literal matching.  If the variable appears ``isolated''
  519. then Calc is smart enough to use it for literal matching.  But in this
  520. last example, Calc is forced to rewrite the rule to @samp{f(x-1, temp)
  521. := g(x) :: temp = x+1} where the @samp{x-1} term must correspond to an
  522. actual ``something-minus-one'' in the target formula.
  523. X
  524. A successful way to write this would be @samp{f(x, x+2) := g(x+1)}.
  525. You could make this resemble the original form more closely by using
  526. @code{let} notation, which is described in the next section:
  527. X
  528. @example
  529. f(xm1, x+1)  :=  g(x)  :: let(x := xm1+1)
  530. @end example
  531. X
  532. Calc does this rewriting or ``conditionalizing'' for any sub-pattern
  533. which involves only the functions in the following list, operating
  534. only on constants and meta-variables which have already been matched
  535. elsewhere in the pattern.  When matching a function call, Calc is
  536. careful to match arguments which are plain variables before arguments
  537. which are calls to any of the functions below, so that a pattern like
  538. @samp{f(x-1, x)} can be conditionalized even though the isolated
  539. @samp{x} comes after the @samp{x-1}.
  540. X
  541. @smallexample
  542. + - * / \ % ^  abs sign  round rounde roundu trunc floor ceil
  543. max min  re im conj arg
  544. @end smallexample
  545. X
  546. You can suppress all of the special treatments described in this
  547. section by surrounding a function call with a @code{plain} marker.
  548. This marker causes the function call which is its argument to be
  549. matched literally, without regard to commutativity, associativity,
  550. negation, or conditionalization.  When you use @code{plain}, the
  551. ``deep structure'' of the formula being matched can show through.
  552. For example,
  553. X
  554. @example
  555. plain(a - a b)  :=  f(a, b)
  556. @end example
  557. X
  558. @noindent
  559. will match only literal subtractions.  However, the @code{plain}
  560. marker does not affect its arguments' arguments.  In this case,
  561. commutativity and associativity is still considered while matching
  562. the @samp{a b} sub-pattern, so the whole pattern will match
  563. @samp{x - y x} as well as @samp{x - x y}.  We could go still
  564. further and use
  565. X
  566. @example
  567. plain(a - plain(a b))  :=  f(a, b)
  568. @end example
  569. X
  570. @noindent
  571. which would do a completely strict match for the pattern.
  572. X
  573. By contrast, the @code{quote} marker means that not only the
  574. function name but also the arguments must be literally the same.
  575. The above pattern will match @samp{x - x y} but
  576. X
  577. @example
  578. quote(a - a b)  :=  f(a, b)
  579. @end example
  580. X
  581. @noindent
  582. will match only the single formula @samp{a - a b}.  Also,
  583. X
  584. @example
  585. quote(a - quote(a b))  :=  f(a, b)
  586. @end example
  587. X
  588. @noindent
  589. will match only @samp{a - quote(a b)}---probably not the desired
  590. effect!
  591. X
  592. A certain amount of algebra is also done when substituting the
  593. meta-variables on the righthand side of a rule.  For example,
  594. in the rule
  595. X
  596. @example
  597. a + f(b)  :=  f(a + b)
  598. @end example
  599. X
  600. @noindent
  601. matching @samp{f(x) - y} would produce @samp{f((-y) + x)} if
  602. taken literally, but the rewrite mechanism will simplify the
  603. righthand side to @samp{f(x - y)} automatically.  (Of course,
  604. the default simplifications would do this anyway, so this
  605. special simplification is only noticeable if you have turned the
  606. default simplifications off.)  This rewriting is done only when
  607. a meta-variable expands to a ``negative-looking'' expression.
  608. If this simplification is not desirable, you can use a @code{plain}
  609. marker on the righthand side:
  610. X
  611. @example
  612. a + f(b)  :=  f(plain(a + b))
  613. @end example
  614. X
  615. @noindent
  616. In this example, we are still allowing the pattern-matcher to
  617. use all the algebra it can muster, but the righthand side will
  618. always simplify to a literal addition like @samp{f((-y) + x)}.
  619. X
  620. @node Other Features of Rewrite Rules, Composing Patterns in Rewrite Rules, Algebraic Properties of Rewrite Rules, Rewrite Rules
  621. @subsection Other Features of Rewrite Rules
  622. X
  623. @noindent
  624. Certain ``function names'' serve as markers in rewrite rules.
  625. Here is a complete list of these markers.  First are listed the
  626. markers that work inside a pattern; then come the markers that
  627. work in the righthand side of a rule.
  628. X
  629. @tindex import
  630. One kind of marker, @samp{import(x)}, takes the place of a whole
  631. rule.  Here @cite{x} is the name of a variable containing another
  632. rule set; those rules are ``spliced into'' the rule set that
  633. imports them.  For example, if @samp{[f(a+b) := f(a) + f(b),
  634. f(a b) := a f(b) :: real(a)]} is stored in variable @samp{linearF},
  635. then the rule set @samp{[f(0) := 0, import(linearF)]} will apply
  636. all three rules.  It is possible to modify the imported rules
  637. slightly:  @samp{import(x, v1, x1, v2, x2, @dots{})} imports
  638. the rule set @cite{x} with all occurrences of @cite{v1}, as either
  639. a variable name or a function name, replaced with @cite{x1} and
  640. so on.  (If @cite{v1} is used as a function name, then @cite{x1}
  641. must be either a function name itself or a @samp{< >} nameless
  642. function @pxref{Specifying Operators}.)  For example, @samp{[g(0) := 0,
  643. import(linearF, f, g)]} applies the linearity rules to the function
  644. @samp{g} instead of @samp{f}.  Imports can be nested, but the
  645. import-with-renaming feature may not properly rename sub-imports.
  646. X
  647. The special functions allowed in patterns are:
  648. X
  649. @table @samp
  650. @item quote(x)
  651. @tindex quote
  652. This pattern matches exactly @cite{x}; variable names in @cite{x} are
  653. not interpreted as meta-variables.  The only flexibility is that
  654. numbers are compared for numeric equality, so that the pattern
  655. @samp{f(quote(12))} will match both @samp{f(12)} and @samp{f(12.0)}.
  656. (Numbers are always treated this way by the rewrite mechanism:
  657. The rule @samp{f(x,x) := g(x)} will match @samp{f(12, 12.0)}.
  658. The rewrite may produce either @samp{g(12)} or @samp{g(12.0)}
  659. as a result in this case.)
  660. X
  661. @item plain(x)
  662. @tindex plain
  663. Here @cite{x} must be a function call @samp{f(x1,x2,@dots{})}.  This
  664. pattern matches a call to function @cite{f} with the specified
  665. argument patterns.  No special knowledge of the properties of the
  666. function @cite{f} is used in this case; @samp{+} is not commutative or
  667. associative.  Unlike @code{quote}, the arguments @samp{x1,x2,@dots{}}
  668. are treated as patterns.  If you wish them to be treated ``plainly''
  669. as well, you must enclose them with more @code{plain} markers:
  670. @samp{plain(plain(-a) + plain(b c))}.
  671. X
  672. @item opt(x,def)
  673. @tindex opt
  674. Here @cite{x} must be a variable name.  This must appear as an
  675. argument to a function or an element of a vector; it specifies that
  676. the argument or element is optional.
  677. As an argument to @samp{+}, @samp{-}, @samp{*}, @samp{&&}, or @samp{||},
  678. or as the second argument to @samp{/} or @samp{^}, the value @var{def}
  679. may be omitted.  The pattern @samp{x + opt(y)} matches a sum by
  680. binding one summand to @cite{x} and the other to @cite{y}, and it
  681. matches anything else by binding the whole expression to @cite{x} and
  682. zero to @cite{y}.  The other operators above work similarly.@refill
  683. X
  684. For general miscellanous functions, the default value @code{def}
  685. must be specified.  Optional arguments are dropped starting with
  686. the rightmost one during matching.  For example, the pattern
  687. @samp{f(opt(a,0), b, opt(c,b))} will match @samp{f(b)}, @samp{f(a,b)},
  688. or @samp{f(a,b,c)}.  Default values of zero and @cite{b} are
  689. supplied in this example for the omitted arguments.  Note that
  690. the literal variable @cite{b} will be the default in the latter
  691. case, @emph{not} the value that matched the meta-variable @cite{b}.
  692. In other words, the default @var{def} is effectively quoted.
  693. X
  694. @item condition(x,c)
  695. @tindex condition
  696. @tindex ::
  697. This matches the pattern @cite{x}, with the attached condition
  698. @cite{c}.  It is the same as @samp{x :: c}.
  699. X
  700. @item pand(x,y)
  701. @tindex pand
  702. @tindex &&&
  703. This matches anything that matches both pattern @cite{x} and
  704. pattern @cite{y}.  It is the same as @samp{x &&& y}.
  705. @pxref{Composing Patterns in Rewrite Rules}.
  706. X
  707. @item por(x,y)
  708. @tindex por
  709. @tindex |||
  710. This matches anything that matches either pattern @cite{x} or
  711. pattern @cite{y}.  It is the same as @samp{x ||| y}.
  712. X
  713. @item pnot(x)
  714. @tindex pnot
  715. @tindex !!!
  716. This matches anything that does not match pattern @cite{x}.
  717. It is the same as @samp{!!! x}.
  718. X
  719. @item cons(h,t)
  720. @tindex cons (rewrites)
  721. This matches any vector of one or more elements.  The first
  722. element is matched to @cite{h}; a vector of the remaining
  723. elements is matched to @cite{t}.  Note that vectors of fixed
  724. length can also be matched as actual vectors:  The rule
  725. @samp{cons(a,cons(b,[])) := cons(a+b,[])} is equivalent
  726. to the rule @samp{[a,b] := [a+b]}.
  727. X
  728. @item rcons(t,h)
  729. @tindex rcons (rewrites)
  730. This is like @code{cons}, except that the @emph{last} element
  731. is matched to @cite{h}, with the remaining elements matched
  732. to @cite{t}.
  733. X
  734. @item apply(f,args)
  735. @tindex apply (rewrites)
  736. This matches any function call.  The name of the function, in
  737. the form of a variable, is matched to @cite{f}.  The arguments
  738. of the function, as a vector of zero or more objects, are
  739. matched to @samp{args}.  Constants, variables, and vectors
  740. do @emph{not} match an @code{apply} pattern.  For example,
  741. @samp{apply(f,x)} matches any function call, @samp{apply(quote(f),x)}
  742. matches any call to the function @samp{f}, @samp{apply(f,[a,b])}
  743. matches any function call with exactly two arguments, and
  744. @samp{apply(quote(f), cons(a,cons(b,x)))} matches any call
  745. to the function @samp{f} with two or more arguments.  Another
  746. way to implement the latter, if the rest of the rule does not
  747. need to refer to the first two arguments of @samp{f} by name,
  748. would be @samp{apply(quote(f), x :: vlen(x) >= 2)}.
  749. Here's a more interesting sample use of @code{apply}:
  750. X
  751. @example
  752. apply(f,[x+n])  :=  n + apply(f,[x])
  753. X   :: in(f, [floor,ceil]) :: integer(n)
  754. @end example
  755. X
  756. Note, however, that this will be slower to match than a rule
  757. set with two separate rules.  The reason is that Calc sorts
  758. the rules of a rule set according to top-level function name;
  759. if the top-level function is @code{apply}, Calc must try the
  760. rule for every single formula and sub-formula.  If the top-level
  761. function in the pattern is, say, @code{floor}, then Calc invokes
  762. the rule only for sub-formulas which are calls to @code{floor}.
  763. X
  764. You must use @code{apply} for meta-variables with function names
  765. on both sides of a rewrite rule:  @samp{apply(f, [x]) := f(x+1)}
  766. is @emph{not} correct, because it rewrites @samp{spam(6)} into
  767. @samp{f(7)}.  The righthand side should be @samp{apply(f, [x+1])}.
  768. Also note that you will have to use no-simplify (@kbd{m O})
  769. mode when entering this rule so that the @code{apply} isn't
  770. evaluated immediately to get the new rule @samp{f(x) := f(x+1)}.
  771. Or, use @kbd{s e} to enter the rule without going through the stack,
  772. or enter the rule as @samp{apply(f, [x]) := apply(f, [x+1]) :: 1}.
  773. @xref{Conditional Rewrite Rules}.
  774. X
  775. @item select(x)
  776. @tindex select
  777. This is used for applying rules to formulas with selections;
  778. @pxref{Selections with Rewrite Rules}.
  779. @end table
  780. X
  781. Special functions for the righthand sides of rules are:
  782. X
  783. @table @samp
  784. @item quote(x)
  785. The notation @samp{quote(x)} is changed to @samp{x} when the
  786. righthand side is used.  As far as the rewrite rule is concerned,
  787. @code{quote} is invisible.  However, @code{quote} has the special
  788. property in Calc that its argument is not evaluated.  Thus,
  789. while it will not work to put the rule @samp{t(a) := typeof(a)}
  790. on the stack because @samp{typeof(a)} is evaluated immediately
  791. to produce @samp{t(a) := 100}, you can use @code{quote} to
  792. protect the righthand side:  @samp{t(a) := quote(typeof(a))}.
  793. (@xref{Conditional Rewrite Rules}, for another trick for
  794. protecting rules from evaluation.)
  795. X
  796. @item plain(x)
  797. Special properties of and simplifications for the function call
  798. @cite{x} are not used.  One interesting case where @code{plain}
  799. is useful is the rule, @samp{q(x) := quote(x)}, trying to expand a
  800. shorthand notation for the @code{quote} function.  This rule will
  801. not work as shown; instead of replacing @samp{q(foo)} with
  802. @samp{quote(foo)}, it will replace it with @samp{foo}!  The correct
  803. rule would be @samp{q(x) := plain(quote(x))}.
  804. X
  805. @item cons(h,t)
  806. Where @cite{t} is a vector, this is converted into an expanded
  807. vector during rewrite processing.  Note that @code{cons} is a regular
  808. Calc function which normally does this anyway; the only way @code{cons}
  809. is treated specially by rewrites is that @code{cons} on the righthand
  810. side of a rule will be evaluated even if default simplifications
  811. have been turned off.
  812. X
  813. @item rcons(t,h)
  814. Analogous to @code{cons} except putting @cite{h} at the @emph{end} of
  815. the vector @cite{t}.
  816. X
  817. @item apply(f,args)
  818. Where @cite{f} is a variable and @samp{args} is a vector, this
  819. is converted to a function call.  Once again, note that @code{apply}
  820. is also a regular Calc function.
  821. X
  822. @item eval(x)
  823. @tindex eval
  824. The formula @cite{x} is handled in the usual way, then the
  825. default simplifications are applied to it even if they have
  826. been turned off normally.  This allows you to treat any function
  827. similarly to the way @code{cons} and @code{apply} are always
  828. treated.  However, there is a slight difference:  @samp{cons(2+3, [])}
  829. with default simplifications off will be converted to @samp{[2+3]},
  830. whereas @samp{eval(cons(2+3, []))} will be converted to @samp{[5]}.
  831. X
  832. @item evalsimp(x)
  833. @tindex evalsimp
  834. The formula @cite{x} has meta-variables substituted in the usual
  835. way, then algebraically simplified as if by the @kbd{a s} command.
  836. X
  837. @item evalextsimp(x)
  838. @tindex evalextsimp
  839. The formula @cite{x} has meta-variables substituted in the normal
  840. way, then ``extendedly'' simplified as if by the @kbd{a e} command.
  841. X
  842. @item select(x)
  843. @xref{Selections with Rewrite Rules}.
  844. @end table
  845. X
  846. There are also some special functions you can use in conditions.
  847. X
  848. @table @samp
  849. @item let(v := x)
  850. @tindex let
  851. The expression @cite{x} is evaluated with meta-variables substituted.
  852. The @kbd{a s} command's simplifications are @emph{not} applied by
  853. default, but @cite{x} can include calls to @code{evalsimp} or
  854. @code{evalextsimp} as described above to invoke higher levels
  855. of simplification.  The
  856. result of @cite{x} is then bound to the meta-variable @cite{v}.  As
  857. usual, if this meta-variable has already been matched to something
  858. else the two values must be equal; if the meta-variable is new then
  859. it is bound to the result of the expression.  This variable can then
  860. appear in later conditions, and on the righthand side of the rule.
  861. In fact, @cite{v} may be any pattern in which case the result of
  862. evaluating @cite{x} is matched to that pattern, binding any
  863. meta-variables that appear in that pattern.  Note that @code{let}
  864. can only appear by itself as a condition, or as one term of an
  865. @samp{&&} which is a whole condition:  It cannot be inside
  866. an @samp{||} term or otherwise buried.@refill
  867. X
  868. The alternate, equivalent form @samp{let(v, x)} is also recognized.
  869. Note that the use of @samp{:=} by @code{let}, while still being
  870. assignment-like in character, is unrelated to the use of @samp{:=}
  871. in the main part of a rewrite rule.
  872. X
  873. As an example, @samp{f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)}
  874. replaces @samp{f(a)} with @samp{g} of the inverse of @samp{a}, if
  875. that inverse exists and is constant.  For example, if @samp{a} is a
  876. singular matrix the operation @samp{1/a} is left unsimplified and
  877. @samp{constant(ia)} fails, but if @samp{a} is an invertible matrix
  878. then the rule succeeds.  Without @code{let} there would be no way
  879. to implement this rule that didn't have to invert the matrix twice.
  880. Note that, because the meta-variable @samp{ia} is otherwise unbound
  881. in this rule, the @code{let} condition itself always ``succeeds''
  882. because no matter what @samp{1/a} evaluates to, it can successfully
  883. be bound to @code{ia}.@refill
  884. X
  885. As another example, here is a rule for integrating cosines of linear
  886. terms:  @samp{myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))}.
  887. The @code{lin} function returns a 3-vector if its argument is linear,
  888. or leaves itself unevaluated if not.  But an unevaluated @code{lin}
  889. call will not match the 3-vector on the lefthand side of the @code{let},
  890. so this @code{let} both verifies that @code{y} is linear, and binds
  891. the coefficients @code{a} and @code{b} for use elsewhere in the rule.
  892. (It would have been possible to use @samp{sin(a x + b)/b} for the
  893. righthand side instead, but using @samp{sin(y)/b} avoids gratuitous
  894. rearrangement of the argument of the sine.)@refill
  895. X
  896. Similarly, here is a rule that implements an inverse-@code{erf}
  897. function.  It uses @code{root} to search for a solution.  If
  898. @code{root} succeeds, it will return a vector of two numbers
  899. where the first number is the desired solution.  If no solution
  900. is found, @code{root} remains in symbolic form.  So we use
  901. @code{let} to check that the result was indeed a vector.
  902. X
  903. @tindex ierf
  904. @example
  905. ierf(x)  :=  y  :: let([y,z] := root(erf(a) = x, a, .5))
  906. @end example
  907. X
  908. @item matches(v,p)
  909. The meta-variable @var{v}, which must already have been matched
  910. to something elsewhere in the rule, is compared against pattern
  911. @var{p}.  Since @code{matches} is a standard Calc function, it
  912. can appear anywhere in a condition.  But if it appears alone or
  913. as a term of a top-level @samp{&&}, then you get the special
  914. extra feature that meta-variables which are bound to things
  915. inside @var{p} can be used elsewhere in the surrounding rewrite
  916. rule.
  917. X
  918. The only real difference between @samp{let(p := v)} and
  919. @samp{matches(v, p)} is that the former evaluates @samp{v} using
  920. the default simplifications, while the latter does not.
  921. X
  922. @item remember
  923. @vindex remember
  924. This is actually a variable, not a function.  If @code{remember}
  925. appears as a condition in a rule, then when that rule succeeds
  926. the original expression and rewritten expression are added to the
  927. front of the rule set that contained the rule.  If the rule set
  928. was not stored in a variable, @code{remember} is ignored.  The
  929. lefthand side is enclosed in @code{quote} in the added rule if it
  930. contains any variables.
  931. X
  932. For example, the rule @samp{f(n) := n f(n-1) :: remember} applied
  933. to @samp{f(7)} will add the rule @samp{f(7) := 7 f(6)} to the front
  934. of the rule set.  The rule set @code{EvalRules} works slightly
  935. differently:  There, the evaluation of @samp{f(6)} will complete before
  936. the result is added to the rule set, in this case as @samp{f(7) := 5040}.
  937. Thus @code{remember} is most useful inside @code{EvalRules}.
  938. X
  939. It is up to you to ensure that the optimization performed by
  940. @code{remember} is safe.  For example, the rule @samp{foo(n) := n
  941. :: evalv(eatfoo) > 0 :: remember} is a bad idea (@code{evalv} is
  942. the function equivalent of the @kbd{=} command); if the variable
  943. @code{eatfoo} ever contains 1, rules like @samp{foo(7) := 7} will
  944. be added to the rule set and will continue to operate even if
  945. @code{eatfoo} is later changed to 0.
  946. X
  947. @item remember(c)
  948. @tindex remember
  949. Remember the match as described above, but only if condition @cite{c}
  950. is true.  For example, @samp{remember(n % 4 = 0)} in the above factorial
  951. rule remembers only every fourth result.  Note that @samp{remember(1)}
  952. is equivalent to @samp{remember}, and @samp{remember(0)} has no effect.
  953. @end table
  954. X
  955. @node Composing Patterns in Rewrite Rules, Nested Formulas with Rewrite Rules, Other Features of Rewrite Rules, Rewrite Rules
  956. @subsection Composing Patterns in Rewrite Rules
  957. X
  958. @noindent
  959. There are three operators, @samp{&&&}, @samp{|||}, and @samp{!!!},
  960. that combine rewrite patterns to make larger patterns.  The
  961. combinations are ``and,'' ``or,'' and ``not,'' respectively, and
  962. these operators are the pattern equivalents of @samp{&&}, @samp{||}
  963. and @samp{!} (which operate on zero-or-nonzero logical values).
  964. X
  965. Note that @samp{&&&}, @samp{|||}, and @samp{!!!} are left in symbolic
  966. form by all regular Calc features; they have special meaning only in
  967. the context of rewrite rule patterns.
  968. X
  969. The pattern @samp{@var{p1} &&& @var{p2}} matches anything that
  970. matches both @var{p1} and @var{p2}.  One especially useful case is
  971. when one of @var{p1} or @var{p2} is a meta-variable.  For example,
  972. here is a rule that operates on error forms:
  973. X
  974. @example
  975. f(x &&& a +/- b, x)  :=  g(x)
  976. @end example
  977. X
  978. This does the same thing, but is arguably simpler than, the rule
  979. X
  980. @example
  981. f(a +/- b, a +/- b)  :=  g(a +/- b)
  982. @end example
  983. X
  984. Here's another interesting example:
  985. X
  986. @tindex ends
  987. @example
  988. ends(cons(a, x) &&& rcons(y, b))  :=  [a, b]
  989. @end example
  990. X
  991. @noindent
  992. which effectively clips out the middle of a vector leaving just
  993. the first and last elements.  This rule will change a one-element
  994. vector @samp{[a]} to @samp{[a, a]}.  The similar rule
  995. X
  996. @example
  997. ends(cons(a, rcons(y, b)))  :=  [a, b]
  998. @end example
  999. X
  1000. @noindent
  1001. would do the same thing except that it would fail to match a
  1002. one-element vector.
  1003. X
  1004. @tex
  1005. \bigskip
  1006. @end tex
  1007. X
  1008. The pattern @samp{@var{p1} ||| @var{p2}} matches anything that
  1009. matches either @var{p1} or @var{p2}.  Calc first tries matching
  1010. against @var{p1}; if that fails, it goes on to try @var{p2}.
  1011. X
  1012. A simple example of @samp{|||} is
  1013. X
  1014. @tindex curve
  1015. @example
  1016. curve(inf ||| -inf)  :=  0
  1017. @end example
  1018. X
  1019. @noindent
  1020. which converts both @samp{curve(inf)} and @samp{curve(-inf)} to zero.
  1021. X
  1022. Here is a larger example:
  1023. X
  1024. @example
  1025. log(a, b) ||| (ln(a) :: let(b := e))  :=  mylog(a, b)
  1026. @end example
  1027. X
  1028. This matches both generalized and natural logarithms in a single rule.
  1029. Note that the @samp{::} term must be enclosed in parentheses because
  1030. that operator has lower precedence than @samp{|||} or @samp{:=}.
  1031. X
  1032. (In practice this rule would probably include a third alternative,
  1033. omitted here for brevity, to take care of @code{log10}.)
  1034. X
  1035. While Calc generally treats interior conditions exactly the same as
  1036. conditions on the outside of a rule, it does guarantee that if all the
  1037. variables in the condition are special names like @code{e}, or already
  1038. bound in the pattern to which the condition is attached (say, if
  1039. @samp{a} had appeared in this condition), then Calc will process this
  1040. condition right after matching the pattern to the left of the @samp{::}.
  1041. Thus, we know that @samp{b} will be bound to @samp{e} only if the
  1042. @code{ln} branch of the @samp{|||} was taken.
  1043. X
  1044. Note that this rule was careful to bind the same set of meta-variables
  1045. on both sides of the @samp{|||}.  Calc does not check this, but if
  1046. you bind a certain meta-variable only in one branch and then use that
  1047. meta-variable elsewhere in the rule, results are unpredictable:
  1048. X
  1049. @example
  1050. f(a,b) ||| g(b)  :=  h(a,b)
  1051. @end example
  1052. X
  1053. Here if the pattern matches @samp{g(17)}, Calc makes no promises about
  1054. the value that will be substituted for @samp{a} on the righthand side.
  1055. X
  1056. @tex
  1057. \bigskip
  1058. @end tex
  1059. X
  1060. The pattern @samp{!!! @var{pat}} matches anything that does not
  1061. match @var{pat}.  Any meta-variables that are bound while matching
  1062. @var{pat} remain unbound outside of @var{pat}.
  1063. X
  1064. For example,
  1065. X
  1066. @example
  1067. f(x &&& !!! a +/- b, !!![])  :=  g(x)
  1068. @end example
  1069. X
  1070. @noindent
  1071. converts @code{f} whose first argument is anything @emph{except} an
  1072. error form, and whose second argument is not the empty vector, into
  1073. a similar call to @code{g} (but without the vector).
  1074. X
  1075. If we know that the second argument will be a vector (empty or not),
  1076. then an equivalent rule would be:
  1077. X
  1078. @example
  1079. f(x, y)  :=  g(x)  :: typeof(x) != 7 :: vlen(y) > 0
  1080. @end example
  1081. X
  1082. @noindent
  1083. where of course 7 is the @code{typeof} code for error forms.
  1084. Another final condition, that works for any kind of @samp{y},
  1085. would be @samp{!istrue(y == [])}.  (The @code{istrue} function
  1086. returns an explicit 0 if its argument was left in symbolic form;
  1087. plain @samp{!(y == [])} or @samp{y != []} would not work to replace
  1088. @samp{!!![]} since these would be left unsimplified, and thus cause
  1089. the rule to fail, if @samp{y} was something like a variable name.)
  1090. X
  1091. It is possible for a @samp{!!!} to refer to meta-variables bound
  1092. elsewhere in the pattern.  For example,
  1093. X
  1094. @example
  1095. f(a, !!!a)  :=  g(a)
  1096. @end example
  1097. X
  1098. @noindent
  1099. matches any call to @code{f} with different arguments, changing
  1100. this to @code{g} with only the first argument.
  1101. X
  1102. If a function call is to be matched and one of the argument patterns
  1103. contains a @samp{|||} somewhere inside it, that argument will be
  1104. matched last.  Thus
  1105. X
  1106. @example
  1107. f(!!!a, a)  :=  g(a)
  1108. @end example
  1109. X
  1110. @noindent
  1111. will be careful to bind @samp{a} to the second argument of @code{f}
  1112. before testing the first argument.  If Calc had tried to match the
  1113. first argument of @code{f} first, the results would have been
  1114. disasterous:  Since @code{a} was unbound so far, the pattern @samp{a}
  1115. would have matched anything at all, and the pattern @samp{!!!a}
  1116. therefore would @emph{not} have matched anything at all!
  1117. X
  1118. @node Nested Formulas with Rewrite Rules, Multi-Phase Rewrite Rules, Composing Patterns in Rewrite Rules, Rewrite Rules
  1119. @subsection Nested Formulas with Rewrite Rules
  1120. X
  1121. @noindent
  1122. When @kbd{a r} (@code{calc-rewrite}) is used, it takes an expression from
  1123. the top of the stack and attempts to match any of the specified rules
  1124. to any part of the expression, starting with the whole expression
  1125. and then, if that fails, trying deeper and deeper sub-expressions.
  1126. For each part of the expression, the rules are tried in the order
  1127. they appear in the rules vector.  The first rule to match the first
  1128. sub-expression wins; it replaces the matched sub-expression according
  1129. to the @samp{new} part of the rule.
  1130. X
  1131. Often, the rule set will match and change the formula several times.
  1132. The top-level formula is first matched and substituted repeatedly until
  1133. it no longer matches the pattern; then, sub-formulas are tried, and
  1134. so on.  Once each part of the formula has gotten its chance, the
  1135. rewrite mechanism starts over again with the top-level formula
  1136. (in case a substitution of one of its arguments has caused it again
  1137. to match).  This continues until no further matches can be made
  1138. anywhere in the formula.
  1139. X
  1140. It is possible for a rule set to get into an infinite loop.  The
  1141. most obvious case, replacing a formula with itself, is not a problem
  1142. because a rule is not considered to ``succeed'' unless the righthand
  1143. side actually comes out to something different than the original
  1144. formula or sub-formula that was matched.  But if you accidentally
  1145. had both @samp{ln(a b) := ln(a) + ln(b)} and the reverse
  1146. @samp{ln(a) + ln(b) := ln(a b)} in your rule set, Calc would
  1147. run forever switching a formula back and forth between the two
  1148. forms.
  1149. X
  1150. To avoid disaster, Calc normally stops after 100 changes have been
  1151. made to the formula.  This will be enough for most multiple rewrites,
  1152. but will keep an endless loop of rewrites from locking up the
  1153. computer forever.  (On most systems, you can also type @kbd{C-g} to
  1154. halt any Emacs command prematurely.)
  1155. X
  1156. To change this limit, give a positive numeric prefix argument.
  1157. In particular, @kbd{M-1 a r} applies only one rewrite at a time,
  1158. useful when you are first testing your rule (or just if repeated
  1159. rewriting is not what is called for by your application).
  1160. X
  1161. @tindex iterations
  1162. You can also put a ``function call'' @samp{iterations(@var{n})}
  1163. in place of a rule anywhere in your rules vector (but usually at
  1164. the top).  Then, @var{n} will be used instead of 100 as the default
  1165. number of iterations for this rule set.  You can use
  1166. @samp{iterations(inf)} if you want no iteration limit by default.
  1167. A prefix argument will override the @code{iterations} limit in the
  1168. rule set.
  1169. X
  1170. @example
  1171. [ iterations(1),
  1172. X  f(x) := f(x+1) ]
  1173. @end example
  1174. X
  1175. More precisely, the limit controls the number of ``iterations,''
  1176. where each iteration is a successful matching of a rule pattern whose
  1177. righthand side, after substituting meta-variables and applying the
  1178. default simplifications, is different from the original sub-formula
  1179. that was matched.
  1180. X
  1181. A prefix argument of zero sets the limit to infinity.  Use with caution!
  1182. X
  1183. Given a negative numeric prefix argument, @kbd{a r} will match and
  1184. substitute the top-level expression up to that many times, but
  1185. will not attempt to match the rules to any sub-expressions.
  1186. X
  1187. In a formula, @code{rewrite(@var{expr}, @var{rules}, @var{n})}
  1188. does a rewriting operation.  Here @var{expr} is the expression
  1189. being rewritten, @var{rules} is the rule, vector of rules, or
  1190. variable containing the rules, and @var{n} is the optional
  1191. iteration limit, which may be a positive integer, a negative
  1192. integer, or @samp{inf} or @samp{-inf}.  If @var{n} is omitted
  1193. the @code{iterations} value from the rule set is used; if both
  1194. are omitted, 100 is used.
  1195. X
  1196. @node Multi-Phase Rewrite Rules, Selections with Rewrite Rules, Nested Formulas with Rewrite Rules, Rewrite Rules
  1197. @subsection Multi-Phase Rewrite Rules
  1198. X
  1199. @noindent
  1200. It is possible to separate a rewrite rule set into several @dfn{phases}.
  1201. During each phase, certain rules will be enabled while certain others
  1202. will be disabled.  A @dfn{phase schedule} controls the order in which
  1203. phases occur during the rewriting process.
  1204. X
  1205. @tindex phase
  1206. @vindex all
  1207. If a call to the marker function @code{phase} appears in the rules
  1208. vector in place of a rule, all rules following that point will be
  1209. members of the phase(s) identified in the arguments to @code{phase}.
  1210. Phases are given integer numbers.  The markers @samp{phase()} and
  1211. @samp{phase(all)} both mean the following rules belong to all phases;
  1212. this is the default at the start of the rule set.
  1213. X
  1214. If you do not explicitly schedule the phases, Calc sorts all phase
  1215. numbers that appear in the rule set and executes the phases in
  1216. ascending order.  For example, the rule set
  1217. X
  1218. @group
  1219. @example
  1220. [ f0(x) := g0(x),
  1221. X  phase(1),
  1222. X  f1(x) := g1(x),
  1223. X  phase(2),
  1224. X  f2(x) := g2(x),
  1225. X  phase(3),
  1226. X  f3(x) := g3(x),
  1227. X  phase(1,2),
  1228. X  f4(x) := g4(x) ]
  1229. @end example
  1230. @end group
  1231. X
  1232. @noindent
  1233. has three phases, 1 through 3.  Phase 1 consists of the @code{f0},
  1234. @code{f1}, and @code{f4} rules (in that order).  Phase 2 consists of
  1235. @code{f0}, @code{f2}, and @code{f4}.  Phase 3 consists of @code{f0}
  1236. and @code{f3}.
  1237. X
  1238. When Calc rewrites a formula using this rule set, it first rewrites
  1239. the formula using only the phase 1 rules until no further changes are
  1240. possible.  Then it switches to the phase 2 rule set and continues
  1241. until no further changes occur, then finally rewrites with phase 3.
  1242. When no more phase 3 rules apply, rewriting finishes.  (This is
  1243. assuming @kbd{a r} with a large enough prefix argument to allow the
  1244. rewriting to run to completion; the sequence just described stops
  1245. early if the number of iterations specified in the prefix argument,
  1246. 100 by default, is reached.)
  1247. X
  1248. During each phase, Calc descends through the nested levels of the
  1249. formula as described previously.  (@xref{Nested Formulas with Rewrite
  1250. Rules}.)  Rewriting starts at the top of the formula, then works its
  1251. way down to the parts, then goes back to the top and works down again.
  1252. The phase 2 rules do not begin until no phase 1 rules apply anywhere
  1253. in the formula.
  1254. X
  1255. @tindex schedule
  1256. A @code{schedule} marker appearing in the rule set (anywhere, but
  1257. conventionally at the top) changes the default schedule of phases.
  1258. In the simplest case, @code{schedule} has a sequence of phase numbers
  1259. for arguments; each phase number is invoked in turn until the
  1260. arguments to @code{schedule} are exhausted.  Thus adding
  1261. @samp{schedule(3,2,1)} at the top of the above rule set would
  1262. reverse the order of the phases; @samp{schedule(1,2,3)} would have
  1263. no effect since this is the default schedule; and @samp{schedule(1,2,1,3)}
  1264. would give phase 1 a second chance after phase 2 has completed, before
  1265. moving on to phase 3.
  1266. X
  1267. Any argument to @code{schedule} can instead be a vector of phase
  1268. numbers (or even of sub-vectors).  Then the sub-sequence of phases
  1269. described by the vector are tried repeatedly until no change occurs
  1270. in any phase in the sequence.  For example, @samp{schedule([1, 2], 3)}
  1271. tries phase 1, then phase 2, then, if either phase made any changes
  1272. to the formula, repeats these two phases until they can make no
  1273. further progress.  Finally, it goes on to phase 3 for finishing
  1274. touches.
  1275. X
  1276. Also, items in @code{schedule} can be variable names as well as
  1277. numbers.  A variable name is interpreted as the name of a function
  1278. to call on the whole formula.  For example, @samp{schedule(1, simplify)}
  1279. says to apply the phase-1 rules (presumably, all of them), then to
  1280. call @code{simplify} which is the function name equivalent of @kbd{a s}.
  1281. Likewise, @samp{schedule([1, simplify])} says to alternate between
  1282. phase 1 and @kbd{a s} until no further changes occur.
  1283. X
  1284. Phases can be used purely to improve efficiency; if it is known that
  1285. a certain group of rules will apply only at the beginning of rewriting,
  1286. and a certain other group will apply only at the end, then rewriting
  1287. will be faster if these groups are identified as separate phases.
  1288. Once the phase 1 rules are done, Calc can put them aside and no longer
  1289. spend any time on them while it works on phase 2.
  1290. X
  1291. There are also some problems that can only be solved with several
  1292. rewrite phases.  For a real-world example of a multi-phase rule set,
  1293. examine the set @code{FitRules}, which is used by the curve-fitting
  1294. command to convert a model expression to linear form.
  1295. @xref{Curve Fitting Details}.  This set is divided into four phases.
  1296. The first phase rewrites certain kinds of expressions to be more
  1297. easily linearizable, but less computationally efficient.  After the
  1298. linear components have been picked out, the final phase includes the
  1299. opposite rewrites to put each component back into an efficient form.
  1300. If both sets of rules were included in one big phase, Calc could get
  1301. into an infinite loop going back and forth between the two forms.
  1302. X
  1303. Elsewhere in @code{FitRules}, the components are first isolated,
  1304. then recombined where possible to reduce the complexity of the linear
  1305. fit, then finally packaged one component at a time into vectors.
  1306. If the packaging rules were allowed to begin before the recombining
  1307. rules were finished, some components might be put away into vectors
  1308. before they had a chance to recombine.  By putting these rules in
  1309. two separate phases, this problem is neatly avoided.
  1310. X
  1311. @node Selections with Rewrite Rules, Matching Commands, Multi-Phase Rewrite Rules, Rewrite Rules
  1312. @subsection Selections with Rewrite Rules
  1313. X
  1314. @noindent
  1315. If a sub-formula of the current formula is selected (as by @kbd{j s};
  1316. @pxref{Selecting Subformulas}), the @kbd{a r} (@code{calc-rewrite})
  1317. command applies only to that sub-formula.  Together with a negative
  1318. prefix argument, you can use this fact to apply a rewrite to one
  1319. specific part of a formula without affecting any other parts.
  1320. X
  1321. @kindex j r
  1322. @pindex calc-rewrite-selection
  1323. The @kbd{j r} (@code{calc-rewrite-selection}) command allows more
  1324. sophisticated operations on selections.  This command prompts for
  1325. the rules in the same way as @kbd{a r}, but it then applies those
  1326. rules to the whole formula in question even though a sub-formula
  1327. of it has been selected.  However, the selected sub-formula will
  1328. first have been surrounded by a @samp{select( )} function call.
  1329. (Calc's evaluator does not understand the function name @code{select};
  1330. this is only a tag used by the @kbd{j r} command.)
  1331. X
  1332. For example, suppose the formula on the stack is @samp{2 (a + b)^2}
  1333. and the sub-formula @samp{a + b} is selected.  This formula will
  1334. be rewritten to @samp{2 select(a + b)^2} and then the rewrite
  1335. rules will be applied in the usual way.  The rewrite rules can
  1336. SHAR_EOF
  1337. true || echo 'restore of calc.texinfo failed'
  1338. fi
  1339. echo 'End of  part 48'
  1340. echo 'File calc.texinfo is continued in part 49'
  1341. echo 49 > _shar_seq_.tmp
  1342. exit 0
  1343. exit 0 # Just in case...
  1344. -- 
  1345. Kent Landfield                   INTERNET: kent@sparky.IMD.Sterling.COM
  1346. Sterling Software, IMD           UUCP:     uunet!sparky!kent
  1347. Phone:    (402) 291-8300         FAX:      (402) 291-4362
  1348. Please send comp.sources.misc-related mail to kent@uunet.uu.net.
  1349.