fork download
  1. ; Count the operands in your DSL
  2. ; ------------------------------
  3. ; The Little Lisper 3rd Edition
  4. ; Chapter 7
  5. ; Exercise 4
  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-7-shadows.html
  9. ; http://t...content-available-to-author-only...t.com/2010/06/little-lisper.html
  10. ; ------------------------------
  11. (setf l1 '())
  12. (setf l2 '(3 + (66 6)))
  13. (setf aexp1 '(1 + (3 * 4)))
  14. (setf aexp2 '((3 ^ 4) + 5))
  15. (setf aexp3 '(3 * (4 * (5 * 6))))
  16. (setf aexp4 5)
  17. ; ------------------------------
  18.  
  19. (defun sub1 (n)
  20. (- n 1))
  21.  
  22. (defun operator (aexp_)
  23. (car (cdr aexp_)))
  24.  
  25. (print (operator '(1 + 2)))
  26. ;+
  27.  
  28. (defun isoperator (a)
  29. (cond
  30. ((null a) NIL)
  31. ((eq a '+) t)
  32. ((eq a '*) t)
  33. ((eq a '^) t)
  34. (t NIL)))
  35.  
  36.  
  37. (print (isoperator '^))
  38. ;T
  39.  
  40. (defun 1st-sub-expr (aexp_)
  41. (car aexp_))
  42.  
  43. (print (1st-sub-expr '(1 + 2)))
  44. ;1
  45.  
  46. (defun 2nd-sub-expr (aexp_)
  47. (car (cdr (cdr aexp_))))
  48.  
  49. (print (2nd-sub-expr '(1 + 2)))
  50. ;2
  51.  
  52. (defun number_ (n)
  53. (cond
  54. ((null n) t)
  55. (t (and
  56. (null (car n))
  57. (number_ (cdr n))))))
  58.  
  59. (defun notatom (lat)
  60. (not (atom lat)))
  61.  
  62. (defun number__ (n)
  63. (cond
  64. ((null n) nil)
  65. ((notatom n) nil)
  66. ((= 0 n) t)
  67. (t (number__ (sub1 n)))))
  68.  
  69.  
  70. (defun count-numbers (aexp_)
  71. (cond
  72. ((null aexp_) 0)
  73. ((number__ aexp_) 1)
  74. ((isoperator (operator aexp_))
  75. (+
  76. (count-numbers (1st-sub-expr aexp_))
  77. (count-numbers (2nd-sub-expr aexp_))))
  78. (t 0)))
  79.  
  80. (print (count-numbers '(1 + 2)))
  81. ;2
  82.  
  83. (print (count-numbers aexp1))
  84. ;3
  85.  
  86. (print (count-numbers aexp3))
  87. ;4
  88.  
  89. (print (count-numbers aexp4))
  90. ;1
  91.  
  92.  
Success #stdin #stdout 0.02s 10552KB
stdin
Standard input is empty
stdout
+ 
T 
1 
2 
2 
3 
4 
1