HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Redefine count-leaves as an accumulation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
redefinecountaccumulationleaves

Problem

Exercise 2.35. Redefine count-leaves
from section 2.2.2 as an accumulation:

(define (count-leaves t) (accumulate   (map  )))


I wrote the following:

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

(define (count-leaves t)
  (accumulate +
              0
              (map (lambda (subtree)
                     (if (pair? subtree) 
                         (count-leaves subtree)
                         1))
                   t)))

(define a (list 1 2 (list 1) (list 1 2 (list 2 (list 1 2)))))


What do you think?

Solution

The code doesn't handle the case of only a single leaf, i.e.

(count-leaves 'leaf)


but I guess that's a side-effect of the original problem formulation. A cleaner solution would be

(define (count-leaves t)
  (if (pair? t)
      (accumulate + 0 (map count-leaves t))
      1)))


also because it's shorter but this doesn't fit the pattern of the original exercise.

Incidentally, in this case the standard Scheme procedure apply would be enough because the Scheme + routine takes in an arbitrary number of arguments, and you could write just:

(define (count-leaves t)
  (if (pair? t)
      (apply + (map count-leaves t))
      1)))

Code Snippets

(count-leaves 'leaf)
(define (count-leaves t)
  (if (pair? t)
      (accumulate + 0 (map count-leaves t))
      1)))
(define (count-leaves t)
  (if (pair? t)
      (apply + (map count-leaves t))
      1)))

Context

StackExchange Code Review Q#1775, answer score: 2

Revisions (0)

No revisions yet.