请帮我做一个关于该计划的简单练习。
编写函数,返回列表中每个级别的原子数。例如:
(a (b (c (de (f) k 1 5) e))) –> ((1 1) (2 1) (3 2) (4 5) (5 1))
我的解决方案:
(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)
它工作正常,但没有给出这个列表的正确答案:
(a (b (c (d e (f) (k) 1 5) e)))
是:
((1 1) (2 1) (3 2) (4 4) (5 1))
但是我们假设“f”和“k”在一个层次上,答案必须是:
((1 1) (2 1) (3 2) (4 4) (5 2))
我应该如何编辑代码以使其正常工作?
UPD(29.10.12):我的最终解决方案:
(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)
对此你能说什么?