fork download
  1. ; Can you abstract accumulators into a single function?
  2. ; ------------------------------
  3. ; The Little Lisper 3rd Edition
  4. ; Chapter 9
  5. ; Exercise 7
  6. ; Common Lisp
  7. ; http://t...content-available-to-author-only...r.com/thelittlelisper
  8. ; http://t...content-available-to-author-only...t.com/2010/06/little-lisper-chapter-9-lamdba-ultimate.html
  9. ; http://t...content-available-to-author-only...t.com/2010/06/little-lisper.html
  10. ; ------------------------------
  11.  
  12. (defun operator (aexp_)
  13. (car (cdr aexp_)))
  14.  
  15. (print (operator '(1 + 2)))
  16. ; +
  17.  
  18. (defun isoperator (a)
  19. (cond
  20. ((null a) NIL)
  21. ((eq a '+) t)
  22. ((eq a '*) t)
  23. ((eq a '^) t)
  24. (t NIL)))
  25.  
  26. (print (isoperator '^))
  27. ; T
  28.  
  29. (print (isoperator (operator '(1 + 2))))
  30. ; T
  31.  
  32. (defun 1st-sub-expr (aexp_)
  33. (car aexp_))
  34.  
  35. (print (1st-sub-expr '(1 + 2)))
  36. ; 1
  37.  
  38. (defun 2nd-sub-expr (aexp_)
  39. (car (cdr (cdr aexp_))))
  40.  
  41. (print (2nd-sub-expr '(1 + 2)))
  42. ; 2
  43.  
  44. (defun sub1 (n)
  45. (- n 1))
  46.  
  47. (defun notatom (lat)
  48. (not (atom lat)))
  49.  
  50. (defun number__ (n)
  51. (cond
  52. ((null n) nil)
  53. ((notatom n) nil)
  54. ((= 0 n) t)
  55. (t (number__ (sub1 n)))))
  56.  
  57. (print (number__ 10))
  58. ;T
  59.  
  60. (defun count-op (aexp_)
  61. (cond
  62. ((null aexp_) 0)
  63. ((number__ aexp_) 0)
  64. ((isoperator (operator aexp_))
  65. (+
  66. (+ 1 (count-op (1st-sub-expr aexp_)))
  67. (count-op (2nd-sub-expr aexp_)))
  68. )
  69. (t 0)))
  70.  
  71. (print (count-op '(3 * (4 * (5 * 6)))))
  72.  
  73.  
  74. (defun count-op-f (aexp_ op-function)
  75. (cond
  76. ((null aexp_) 0)
  77. ((number__ aexp_) 0)
  78. ((eq (operator aexp_) op-function)
  79. (+
  80. (+ 1
  81. (count-op-f (1st-sub-expr aexp_) op-function))
  82. (count-op-f (2nd-sub-expr aexp_) op-function))
  83. )
  84. (t 0)))
  85.  
  86. (print (count-op-f '(1 + 1) '+))
  87. ; 1
  88.  
  89. (print (count-op-f '(1 + (1 + 1)) '+))
  90. ; 2
  91.  
  92. (print (count-op-f '(3 * (4 * (5 * 6))) '*))
  93. ; 3
  94.  
  95. (print (count-op-f '(1 - 1) '+))
  96. ; 0
  97.  
Success #stdin #stdout 0.01s 10600KB
stdin
Standard input is empty
stdout
+ 
T 
T 
1 
2 
T 
3 
1 
2 
3 
0