Saturday, November 24, 2012

Recursives

This weeks examples of DrRacket generated pretty cool images. But then Prof. Heap also uploaded another DrRacket file and inside were codes that he never taught, so I decided to mess around with those and see what the did/

The first thing I did was apply the function like so:
(spiral 4) 

DrRacket then told me that it didn't past the check-expects. I was taken aback at first, but then I looked at the code closely and I noticed, the code was never finished! 
Lesson 1: read carefully before taking action 

To finish the definition, I examined the check-expects:
(check-expect (spiral 0) (vertical-line 10))
(check-expect (spiral 20)
              (beside/align
               "bottom"
               (vertical-line (+ 10 (* 2 20)))
               (rotate 90 (spiral 19))))
(check-expect (spiral 2)
              (beside/align
               "bottom"
               (vertical-line (+ 10 (* 2 2)))
               (rotate 90 (spiral 1))))

Then I modified the definition like so:
(define (spiral n)
     (cond
    [(zero? n) (vertical-line 10)]
    [else
     (beside/align
      "bottom"
      (vertical-line (+ 10 (* 2 20)))
      (rotate 90 (spiral (sub1 n))))]))

...which didn't work out.
So I went back to comparing the two check-expects, then I realized that the last number line should be 'n' instead of '20' after comparing the differences between the two check-expects
After modification
(define (spiral n)
     (cond
    [(zero? n) (vertical-line 10)]
    [else
     (beside/align
      "bottom"
      (vertical-line (+ 10 (* 2 n)))
      (rotate 90 (spiral (sub1 n))))]))

I tested it out and it worked!

No comments:

Post a Comment