title: Count of atoms on the each level, Scheme
body: <p>Please, help me with one simple exercise on the Scheme.</p>
  
  <blockquote>
    <p>Write  function, that return count of atoms on the each level in the
    list. For example:</p>
    
    <p>(a (b (c (d e (f) k 1 5) e))) –> ((1 1) (2 1) (3 2) (4 5) (5 1))</p>
  </blockquote>
  
  <p>My Solution:</p>
  
  <pre><code>(define (atom? x)
    (and (not (pair? x)) (not (null? x))))
  (define (count L)
    (cond ((null? L) 0)
          ((pair? (car L))
           (count (cdr L)))
          (else
           (+ 1 (count (cdr L))))))
  (define (fun L level)
    (cons 
     (list level (count L))
     (ololo L level)))
  (define (ololo L level)
    (if (null? L)
        '()
        (if (atom? (car L))
            (ololo (cdr L) level)            
            (fun (car L) (+ level 1)))))
  (fun '(a (b (c (d e (f) k 1 5) e))) 1)
  </code></pre>
  
  <p>It's work fine, but give not correctly answer for this list:</p>
  
  <pre><code>(a (b (c (d e (f) (k) 1 5) e)))
  </code></pre>
  
  <p>is:</p>
  
  <pre><code>((1 1) (2 1) (3 2) (4 4) (5 1))
  </code></pre>
  
  <p>But we assume that 'f' and 'k' on the one level, and answer must be:</p>
  
  <pre><code>((1 1) (2 1) (3 2) (4 4) (5 2))
  </code></pre>
  
  <p>How should I edit the code to make it work right?</p>
  
  <hr>
  
  <p>UPD (29.10.12):
  My final solution:</p>
  
  <pre><code>(define A '(a (b (c (d e (f) k 1 5) e))))
  
  (define (atom? x)
    (and (not (pair? x)) (not (null? x))))
  
  (define (unite L res)
    (if (null? L) (reverse res)
        (unite (cdr L) (cons (car L) res))))
  
  (define (count-atoms L answ)
    (cond ((null? L) answ)
          ((pair? (car L))
           (count-atoms (cdr L) answ))
          (else
           (count-atoms (cdr L) (+ answ 1)))))
  
  (define (del-atoms L answ)   
    (cond ((null? L) answ)
          ((list? (car L))
           (begin
           (del-atoms (cdr L) (unite (car L) answ))))
          (else
           (del-atoms (cdr L) answ))))
  
  (define (count L)
  (define (countme L level answ)
    (if (null? L)  (reverse answ)
        (countme (del-atoms L '()) (+ level 1) (cons (cons level (cons (count-atoms L 0) '())) answ))))
    (countme L 1 '()))
  
  (count A)
  </code></pre>
  
  <p>What can you say about this?</p>