## SICP – cap. 2 – Sequenze come interfacce convenzionali – 44 – esercizi

Continuo da qui, copio qui.

Exercise 2.35: Redefine `count-leaves` from 2.2.2 [qui] as an accumulation:

``````(define (count-leaves t)
(accumulate ⟨??⟩ ⟨??⟩ (map ⟨??⟩ ⟨??⟩)))``````

La definizione di `count-leaves`:

``````(define (count-leaves x)
(cond ((null? x) 0)
((not (pair? x)) 1)
(else (+ (count-leaves (car x))
(count-leaves (cdr x))))))``````

e quella di `accumulate` [qui]:

``````(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op
initial
(cdr sequence)))))``````

Quindi, seguendo Bill the Lizard: The `enumerate-tree` procedure “flattens out” a tree into a sequence of its leaves. Once we have the tree in the form of a sequence, we just need to define a function for the first argument of `map`. This function should simply return a `1` for any input. Here’s the complete (but very short) solution.

``````(define (count-leaves t)
(accumulate + 0 (map (lambda (x) 1)
(enumerate-tree t))))``````

Al solito una volta vista è semplice e bella. Ma da solo non ci sono arrivato 😡

OK ma senza spiegazione sicp-ex.
Post sintetico anche per Drewiki.

Annunci
Posta un commento o usa questo indirizzo per il trackback.