factors.cpp 826 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Push expression factors onto the stack. For example...
  2. //
  3. // Input
  4. //
  5. // 2
  6. // 3x + 2x + 1
  7. //
  8. // Output on stack
  9. //
  10. // [ 3 ]
  11. // [ x^2 ]
  12. // [ 2 ]
  13. // [ x ]
  14. // [ 1 ]
  15. //
  16. // but not necessarily in that order. Returns the number of factors.
  17. #include "stdafx.h"
  18. #include "defs.h"
  19. // Local U *p is OK here because no functional path to garbage collector.
  20. int
  21. factors(U *p)
  22. {
  23. int h = tos;
  24. if (car(p) == symbol(ADD)) {
  25. p = cdr(p);
  26. while (iscons(p)) {
  27. push_term_factors(car(p));
  28. p = cdr(p);
  29. }
  30. } else
  31. push_term_factors(p);
  32. return tos - h;
  33. }
  34. // Local U *p is OK here because no functional path to garbage collector.
  35. void
  36. push_term_factors(U *p)
  37. {
  38. if (car(p) == symbol(MULTIPLY)) {
  39. p = cdr(p);
  40. while (iscons(p)) {
  41. push(car(p));
  42. p = cdr(p);
  43. }
  44. } else
  45. push(p);
  46. }