distill.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. #include "stdafx.h"
  2. #include "defs.h"
  3. static void _distill(void);
  4. // take expr and push all constant subexpr
  5. // p1 expr
  6. // p2 independent variable (like x)
  7. void
  8. distill(void)
  9. {
  10. save();
  11. _distill();
  12. restore();
  13. }
  14. static void
  15. _distill(void)
  16. {
  17. p2 = pop();
  18. p1 = pop();
  19. // is the entire expression constant?
  20. if (find(p1, p2) == 0) {
  21. push(p1);
  22. //push(p1); // may need later for pushing both +a, -a
  23. //negate();
  24. return;
  25. }
  26. // sum?
  27. if (isadd(p1)) {
  28. distill_sum();
  29. return;
  30. }
  31. // product?
  32. if (car(p1) == symbol(MULTIPLY)) {
  33. distill_product();
  34. return;
  35. }
  36. // naive distill if not sum or product
  37. p3 = cdr(p1);
  38. while (iscons(p3)) {
  39. push(car(p3));
  40. push(p2);
  41. distill();
  42. p3 = cdr(p3);
  43. }
  44. }
  45. void
  46. distill_sum(void)
  47. {
  48. int h;
  49. // distill terms involving x
  50. p3 = cdr(p1);
  51. while (iscons(p3)) {
  52. if (find(car(p3), p2)) {
  53. push(car(p3));
  54. push(p2);
  55. distill();
  56. }
  57. p3 = cdr(p3);
  58. }
  59. // add together all constant terms
  60. h = tos;
  61. p3 = cdr(p1);
  62. while (iscons(p3)) {
  63. if (find(car(p3), p2) == 0)
  64. push(car(p3));
  65. p3 = cdr(p3);
  66. }
  67. if (tos - h) {
  68. add_all(tos - h);
  69. p3 = pop();
  70. push(p3);
  71. push(p3);
  72. negate(); // need both +a, -a for some integrals
  73. }
  74. }
  75. void
  76. distill_product(void)
  77. {
  78. int h;
  79. // distill factors involving x
  80. p3 = cdr(p1);
  81. while (iscons(p3)) {
  82. if (find(car(p3), p2)) {
  83. push(car(p3));
  84. push(p2);
  85. distill();
  86. }
  87. p3 = cdr(p3);
  88. }
  89. // multiply together all constant factors
  90. h = tos;
  91. p3 = cdr(p1);
  92. while (iscons(p3)) {
  93. if (find(car(p3), p2) == 0)
  94. push(car(p3));
  95. p3 = cdr(p3);
  96. }
  97. if (tos - h) {
  98. multiply_all(tos - h);
  99. //p3 = pop(); // may need later for pushing both +a, -a
  100. //push(p3);
  101. //push(p3);
  102. //negate();
  103. }
  104. }