Compositional Programming
CS251 Programming Languages
Fall 2016, Lyn Turbak
Department of Computer Science Wellesley College
Mo#va#ng problem: ssm35
(sum-of-squares-of-multiples-of-3-or-5 n) Return the sum of the squares of the all the mul#ples of 3 and 5 between 1 and n, inclusive. Since sum-of-squares-of-multiples-of-3-or-5 is a very long name, we’ll abbreviate it to ssm35. For example, what should (ssm35 10) return?
2 Composition
A monolithic recursive solu#on
3 Composition
(define (ssm35-monolithic-count-down n) (if (= n 0) (if (or (divisible-by? n 3) (divisible-by? n 5)) (+ (* n n) (ssm35-monolithic-count-down (- n 1))) (ssm35-monolithic-count-down (- n 1)))))
> (ssm35-monolithic-count-down 10) 251
This starts at n, counts down to 0, and then sums up the squares of the multiples of 3 and 5
- n the way out of the recursion.
A monolithic solu#on that counts up
4 Composition
(define (ssm35-monolithic-count-up n) (define (helper num) (if (> num n) (if (or (divisible-by? num 3) (divisible-by? num 5)) (+ (* num num) (helper (+ num 1))) (helper (+ num 1))))) (helper 1))