count-leaves as an accumulation:
(define (count-leaves t)
(accumulate + 0 (map (lambda (x)
(if (pair? x)
(count-leaves x)
1))
t)))
And for reference, accumulate is:
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
Also an alternative map function from one of the other exercises:
(define (map p sequence)
(accumulate (lambda (x y) (cons (p x) y)) nil sequence))
Mind-bending, but fun stuff.
Edit: well, I was going to sleep, but the next exercise looked interesting too, so I figured it out much quicker(finally getting the hang of using lambda?!)
sicp exercise 3.36:
(define (accumulate-n op init seqs)
(if (null? (car seqs))
null
(cons (accumulate op init (accumulate (lambda (x y) (cons (car x) y)) null seqs))
(accumulate-n op init (accumulate (lambda (x y) (cons (cdr x) y)) null seqs)))))
No comments:
Post a Comment