スキームに関する簡単な演習を1つ手伝ってください。
リスト内の各レベルのアトムの数を返す関数を記述します。例えば:
(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))
ただし、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)
これについてあなたは何を言うことができますか?