; Count the operands in your DSL
; ------------------------------
; The Little Lisper 3rd Edition
; Chapter 7
; Exercise 4
; Common Lisp
; http://t...content-available-to-author-only...r.com/thelittlelisper
; http://t...content-available-to-author-only...t.com/2010/06/little-lisper-chapter-7-shadows.html
; http://t...content-available-to-author-only...t.com/2010/06/little-lisper.html
; ------------------------------
(setf l1 '())
(setf l2 '(3 + (66 6)))
(setf aexp1 '(1 + (3 * 4)))
(setf aexp2 '((3 ^ 4) + 5))
(setf aexp3 '(3 * (4 * (5 * 6))))
(setf aexp4 5)
; ------------------------------

(defun sub1 (n)
  (- n 1))

(defun operator (aexp_)
  (car (cdr aexp_)))

(print (operator '(1 + 2)))
;+

(defun isoperator (a)
  (cond
   ((null a) NIL)
   ((eq a '+) t)
   ((eq a '*) t)
   ((eq a '^) t)
   (t NIL)))


(print (isoperator '^))
;T

(defun 1st-sub-expr (aexp_)
  (car aexp_))

(print (1st-sub-expr '(1 + 2)))
;1

(defun 2nd-sub-expr (aexp_)
  (car (cdr (cdr aexp_))))

(print (2nd-sub-expr '(1 + 2)))
;2

(defun number_ (n)
  (cond
   ((null n) t)
   (t (and
       (null (car n))
       (number_ (cdr n))))))
       
(defun notatom (lat)
  (not (atom lat)))

(defun number__ (n)
  (cond
   ((null n) nil)
   ((notatom n) nil)
  ((= 0 n) t)
   (t (number__ (sub1 n)))))       


(defun count-numbers (aexp_)
  (cond
   ((null aexp_) 0)
   ((number__ aexp_) 1)
   ((isoperator (operator aexp_))
    (+ 
    (count-numbers (1st-sub-expr aexp_))
    (count-numbers (2nd-sub-expr aexp_))))
   (t 0))) 

(print (count-numbers '(1 + 2)))
;2

(print (count-numbers aexp1))
;3

(print (count-numbers aexp3))
;4

(print (count-numbers aexp4))
;1

