Saturday, 17 November 2012

DrRacket recursive definition - Week of November 12th

I never did have much time to think of a way to take the sum of the areas of the pyramid levels, not yet anyways.  I did figure out how to make drracket do it 'the long way' however.  I used the recursive definitions we learned in class to make racket take the sum of the bottom layer of a pyramid then work its way up. It was pretty straight forward and looked like this

(require picturing-programs)
(define (sum n) (/ (* n (+ n 1)) 2))
(define (vol n)
  (cond
    [(equal? n 1) 1]
    [else (+ (sum n) (vol (- n 1)))]))

It does feel a bit like cheating and I do still plan on trying to think of a single expression for the volume. It is neat to see so easily that the 'volume' of one of these pyramids with a bottom side of n=200 is 1,353,400 bottle caps. 

Theo

1 comment:

  1. Very cool. You have really "got" recursion when you can apply it to new problems yourself.

    By the way, your sum function could be written recursively, if you didn't know the closed form...

    ReplyDelete