Archive for the ‘recursion’ Tag

SICP Section 2.3.4   Leave a comment

This section puts what we’ve learned about sets into practice implementing a method of encoding and decoding messages encoded with huffman code trees, and also a method of generating the trees.

;;Exercise 2.67
> (decode sample-message sample-tree)
(A D A B B C A)

;;Exercise 2.68
The encode-symbol procedure I wrote is straightforward, but takes a rather large number of steps to encode a symbol, because we have to search the set of symbols at each node for the correct branch to take. I’m not sure if there’s a better way to do this…

(define (encode-symbol symbol tree)
  (cond ((leaf? tree) '())
        ((element-of-set? symbol (symbols (left-branch tree)))
         (cons 0 (encode-symbol symbol (left-branch tree))))
        ((element-of-set? symbol (symbols (right-branch tree)))
         (cons 1 (encode-symbol symbol (right-branch tree))))
        (else (error "symbol not in tree - ENCODE-SYMBOL" symbol))))

;;Exercise 2.69
Successive-merge was actually fairly straightforward to code, however, when I first attempted to do this, I did not fully understand the actual tree generation procedure! Perhaps this is what the authors were warning about when they said it was tricky, I was certainly tricked initially :D

(define (successive-merge leaf-set)
  (if (= (length leaf-set) 1)
      (car leaf-set)
      (successive-merge
       (adjoin-set (make-code-tree (car leaf-set)
                                   (cadr leaf-set))
                   (cddr leaf-set)))))

;;Exercise 2.70
I never knew 50s rock was so repetitive ;)
Probably better than the junk that gets put out these days though…

(define freq-pairs (list (list 'A 2) (list 'BOOM 1) (list 'GET 2) (list 'JOB 2) (list 'NA 16) (list 'SHA 3) (list 'YIP 9) (list 'WAH 1)))

(define message '(GET A JOB
                  SHA NA NA NA NA NA NA NA NA
                  GET A JOB
                  SHA NA NA NA NA NA NA NA NA
                  WAH YIP YIP YIP YIP YIP YIP YIP YIP YIP
                  SHA BOOM))

(define rock50s-tree (generate-huffman-tree freq-pairs))

(define encoded-message (encode message rock50s-tree))
(define huffman-length (length encoded-message))

(define logbase2-of-8 3)
(define fixed-length (* (length message) logbase2-of-8))

fixed-length turns out to be 108 bits long, whereas the huffman-length is only 84 bits long. That’s a pretty fair length saving.

;;Exercise 2.71
I’m not really a fan of drawing large trees, so I’ll just give the code to generate it.

(define freq-pairs-5 (list (list '1 1) (list '2 2) (list '3 4) (list '4 8) (list '5 16)))
(define freq-pairs-tree-5 (generate-huffman-tree freq-pairs-5))

(define freq-pairs-10 (list (list '1 1) (list '2 2) (list '3 4) (list '4 8) (list '5 16) (list '6 32) (list '7 64) (list '8 128) (list '9 256) (list '10 512)))
(define freq-pairs-tree-10 (generate-huffman-tree freq-pairs-10))

The number of bits required for n=5 code are
Largest frequency: 1
Lowest frequency: 4
For n=10
Largest frequency: 1
Lowest frequency 9

It’s fairly obvious that the largest frequency will always have 1 bit, and the lowest frequency will have (n-1) bits.

;;Exercise 2.72
As we descend the tree we have to search the list of symbols at the node we are on, which is of the order O(n). We will need to descend n levels worst case, therefore n searches n deep is O(n2)

Advertisements

SICP – Section 2.3.1-2.3.2   Leave a comment

This section introduces the idea of “symbolic data”, and demonstrates how we can abstract our code with it. I found it to be really enjoyable, the questions were very challenging at the end. I notice I seem to say that I find each section enjoyable, and I do! I cannot recommend this book enough, not only for the knowledge and ideas you gain from it, but for the fun you’ll have solving the problems.

;;Exercise 2.53

As usual, just a check to make sure we understand how to manipulate symbolic data.
>(list '(a b c))
(a b c)
>(list (list 'george))
((george))
>(cdr '((x1 x2) (y1 y2)))
(y1 y2)
>(cadr '((x1 x2) (y1 y2)))
y1
>(pair? (car '(a short list)))
#f
>(memq 'red '((red shoes) (blue socks)))
#f
>(memq 'red '(red shoes blue socks))
(red shoes blue socks)

;;Exercise 2.54

A fairly straightforward implementation of the recursive description they gave.

(define (my-equal? a b)
  (cond ((and (eq? a '()) (eq? b '())) true)
        ((and (symbol? a) (symbol? b))
         (eq? a b))
        ((and (pair? a) (pair? b))
         (and (my-equal? (car a) (car b))
              (my-equal? (cdr a) (cdr b))))
        (else false)))

;;Exercise 2.55

The first challenging question. Had me stumped for a while, even when I typed the code in at my interpreter I didn’t get it, however, if you notice the footnote no. 34, it explains that the interpreter replaces each use of ' with a quote. So ''abracadabra is '(quote abracadabra), and the car of that list is the symbol quote!

;;Exercise 2.56

We’ve been introduced to the differentiation program, a very nice example of abstraction. The key to this exercise is pretty much to copy what happens for the other rules, just supplying different selectors and constructors, and a bit more code in the deriv function. I’m a bit of a rebel ;) I chose to use the ‘^ symbol instead of ‘**, as ‘^ seems more intuitive to me :)

Here are the selectors, predicate, and constructors:

;;'(^ b a)
(define (exponentiation? x)
  (and (pair? x) (eq? (car x) '^)))

(define (base x)
  (cadr x))

(define (exponent x)
  (caddr x))

(define (make-exponentiation base exponent)
  (cond ((and (number? base) (number? exponent))
         (expt base exponent))
        ((=number? exponent 0) 1)
        ((=number? exponent 1) base)
        (else (list '^ base exponent))))

And here is the modified deriv function:

(define (deriv expr var)
  (cond ((number? expr) 0)
        ((variable? expr)
         (if (same-variable? expr var) 1 0))
        ((exponentiation? expr) ;;EXPONENTIATION RULE
         (make-product
           (make-product (exponent expr)
                         (make-exponentiation (base expr)
                                              (- (exponent expr) 1)))
           (deriv (base expr) var)))
        ((sum? expr)
         (make-sum (deriv (addend expr) var)
                   (deriv (augend expr) var)))
        ((product? expr)
         (make-sum
           (make-product (multiplier expr)
                         (deriv (multiplicand expr) var))
           (make-product (deriv (multiplier expr) var)
                         (multiplicand expr))))
        (else
         (error "unknown expression type -- DERIV" expr))))

And a test,
>(deriv '(^ x 4) 'x)
(* 4 (^ x 3))

;;Exercise 2.57

I had some initial difficulties with this question, I understood what I was attempting to do in the selectors, but the constructors were a little trickier. With the selectors, the only interesting bit is in the augend selector. When we get the augend, we must remember if there is a list, we need to return it as the sum of the rest of the items in the list, not a a list of two or more numbers. eg. (augend ‘(+ 1 2 3)) is (+ 2 3) not (2 3).

(define (addend s) (cadr s))

(define (augend s)
  (let ((aug (cddr s)))
    (if (eq? (cdr aug) '())
        (car aug)
        (make-sum (car aug)
                  (cdr aug)))))

The constructor also held me up for a little while, as I had a bit of a hiccup in my code.
I was not combining the augend a2 into the list (‘+ a1 a2) correctly. This is best shown with some code…
>(make-sum x (2 (* 5 y)))
(+ x (2 (* 5 y)))

As you can see, instead of combining the 2 at the same level as x, it is a separate list, (2 (* 5 y)) which the program does not know how to parse. It should of course be (+ x 2 (* 5 y)). How do we combine the lists? Using append! Here is the constructor then:

(define (make-sum a1 a2)
  (cond ((=number? a1 0) a2)
        ((=number? a2 0) a1)
        ((and (number? a1) (number? a2)) (+ a1 a2))
        (else (append (list '+ a1) a2))))

Note that we can leave all the simplification code in, it will still work even in the new format. The changes to product are almost exactly the same as the changes to sum, I feel as though there’s an underlying abstraction somewhere ;)

Here’s the full code, including the product as well as sum, remember that this is all available on my sicp github repo.

;;(+ x y z)
(define (addend s) (cadr s))

(define (augend s)
  (let ((aug (cddr s)))
    (if (eq? (cdr aug) '())
        (car aug)
        (make-sum (car aug)
                  (cdr aug)))))

(define (make-sum a1 a2)
  (cond ((=number? a1 0) a2)
        ((=number? a2 0) a1)
        ((and (number? a1) (number? a2)) (+ a1 a2))
        (else (append (list '+ a1) a2))))

;;'(* x y z)
(define (multiplier p) (cadr p))

(define (multiplicand p)
  (let ((mult (cddr p)))
    (if (eq? (cdr mult) '())
        (car mult)
        (make-product (car mult)
                      (cdr mult)))))

(define (make-product m1 m2)
  (cond ((or (=number? m1 0) (=number? m2 0)) 0)
        ((=number? m1 1) m2)
        ((=number? m2 1) m1)
        ((and (number? m1) (number? m2)) (* m1 m2))
        (else (append (list '* m1) m2))))

;;Exercise 2.58
;;Part A

Things are getting interesting, we are now getting out of the safe world of polish notation, and into the rather complex one of parsing infix expressions. However, part a is very easy to implement, it simply requires swapping the parsing of the operator and the first operand, the change is exactly the same for multiplication.

(define (sum? x)
  (and (pair? x) (eq? (cadr x) '+)))

(define (addend s) (car s))

(define (augend s) (caddr s))

(define (make-sum a1 a2)
  (cond ((=number? a1 0) a2)
        ((=number? a2 0) a1)
        ((and (number? a1) (number? a2)) (+ a1 a2))
        (else (list a1 '+ a2))))

;;Part B

Part b is simply put, a beast of a question. It most certainly is quite a difficult problem, but it’s definitely possible! In fact, I suggest you stop reading now, so that you can have the same exhiliration that I got upon solving it! We are now required to parse infix expressions with any or no parenthization. I mulled over this one for a couple days, and spent more than a few nights writing attempts to solve it in my note book. I finally hit epiphany at badminton on Thursday (6/5/10) night.

Before we do anything, we should state what we are attempting to accomplish with our code. This is a bit trickier than it sounds, so let’s go through a couple examples and see if we can find anything interesting.

(x * (6 + y) + 5) is equivalent to
((x * (6 + y)) + 5) (note the extra parenthesis before x)

So one thing we need to do is replace parentheses to make it easier to parse.

(x * (6 + y) + 5)
can be reduced like so:

addend: x * (6 + y)
      multiplier: x
      multiplicand: (6 + y)
                 addend: 6
                 augend: y
augend:

This looks like a job for recursion to me, and it also looks like we’ll need to worry about putting sums in the right place before the products. For example, if we tried to grab the multiplicand of (3 * 6 + 5) we would obtain 6 + 5 instead of 6.

We can come up with a simple recursive definition for this:

If the augend of expr is a sum, then the augend of expr is the sum of everything after the sum operator in expr (y + 3* z). If the augend of expr is a product, then the augend of expr is the product of everything after the product operator in expr. If the augend of expr is a single variable then the augend of expr is the first item after the sum operator. Finally if the augend of expr is a single number, then the augend of expr is the first item after the sum operator.

So we can see that there are four rules to apply here which will eventually filter down to the base case of the single variable or number. So, the first thing we will implement is the definition of a sum and product. An expression is a sum if it has the ‘+ operator in it, and an expression is a product if it has only the ‘* operator in it. This gives us the proper operator precedence. The in? predicate here tells whether a given symbol is in a list.

(define (sum? x)
  (and (pair? x) (in? '+ x)))

(define (product? x)
  (and (pair? x) (not (in? '+ x)) (in? '* x)))

Now that we have our definitions of what constitutes a sum, we need to give the definitions of addend and augend. The addend is everything before the first ‘+ operator, but we also need to process the addend (remember the recursive definition) to correctly resolve operator precedence in it. We will do this with the recursive process stated above as a procedure named process-expr which I will leave unspecified. Remember that black box abstraction, and wishful thinking are very important. Anyway, here’s the definition of addend and augend, split-on is a function which gives a cons where the car is everything before the symbol, and the cdr is everything after the symbol.

>(split-on '+ (1* x + 2 * y))
((1 * x) 2 y)

(define (addend s)
  (process-expr (car (split-on '+ s))))

(define (augend s)
  (process-expr (cdr (split-on '+ s))))

Now it’s almost all in place, there’s one more definition left, how do we construct a sum? This is very easy, and stays the same as what we implemented for part A, (list a1 '+ a2).

Now, to implement the process-expr procedure. Since we have already defined all the selectors and constructors, this will be very easy.

(define (process-expr expr)
  (cond ((if (= (length expr) 1) (variable? (car expr)) false) (car expr))
        ((if (= (length expr) 1) (number? (car expr)) false) (car expr))
        ((sum? expr) (make-sum (addend expr)
                               (augend expr)))
        ((product? expr) (make-product (multiplier expr)
                                       (multiplicand expr))))))

This is a beautiful example of mutual recursion, and the great thing is, that it works! I first wrote this while waiting to play at badminton, and when I tranferred it from paper, it worked first try, with just a couple hiccups. One of those hiccups was the parsing of a parenthized expression such as (3 * (5 + 4)). The augend of this expression is ((5 + 4)), which is (list (list 5 + 4)). When process-expr encounters this, it checks if it is a variable, but while the length of (list (list 5 ‘+ 4)) is 1, it will not satisfy either the variable? or the number? predicate. It will then check if it is a sum, but there is no ‘+ in (list (list 5 + 4)), and it will also check if it is a product, but it won’t satisfy that either, so the cond expression will return #void! This is a bit of a bug, but it is fairly easy to fix. Let’s think of a parenthized-expression as another type of expression. It must satisfy these requirements to be considered parethized:

  • Must have a length of 1
  • Must not be a variable
  • Must not be a number
  • It’s car must be either a sum or a product

This is readily expressed as a procedure.

(define (parenthized-expression? expr)
  (and (not (variable? expr))
       (not (number? expr))
       (= (length expr) 1)
       (or (sum? (car expr))
           (product? (car expr)))))

;;Selector
(define (deparenthize expr) (car expr))

Now, we just need to add a rule for handling parenthized-expressions to process-expr. This is accomplished by adding a let expression, which will bind expr correctly:

(define (process-expr expr)
  (let ((expr (if (parenthized-expression? expr) (deparenthize expr) expr)))
    (cond ((if (= (length expr) 1) (variable? (car expr)) false) (car expr))
          ((if (= (length expr) 1) (number? (car expr)) false) (car expr))
          ((sum? expr) (make-sum (addend expr)
                                 (augend expr)))
          ((product? expr) (make-product (multiplier expr)
                                         (multiplicand expr))))))

We’re done! We have now created a fairly useful symbolic differentiator, which can handle (almost) arbitrary expressions. There is nothing as exhilirating as solving a really tough problem, and this can definitely be ranked as one of them! Here is all the code, and remember, this code is on my sicp github repo.

Happy Hacking!

;;Split an expr on symb
(define (split-on symb expr)
  (define (iter r l)
    (cond ((eq? l '()) r)
          ((eq? symb (car l)) (cons r (cdr l)))
          (else (iter (append r (list (car l))) (cdr l)))))
  (iter '() expr))

;;Is symb in expr?
(define (in? symb expr)
  (cond ((eq? expr '()) false)
        ((eq? symb (car expr)) true)
        (else (in? symb (cdr expr)))))

;; representing algebraic expressions
(define (variable? x) (symbol? x))

(define (same-variable? v1 v2)
  (and (variable? v1) (variable? v2) (eq? v1 v2)))

(define (=number? exp num)
  (and (number? exp) (= exp num)))

;;Is expr a parenthized expression? eg. ((1 + 2))
(define (parenthized-expression? expr)
  (and (not (variable? expr))
       (not (number? expr))
       (= (length expr) 1)
       (or (sum? (car expr))
           (product? (car expr)))))

(define (process-expr expr)
  (let ((expr (if (parenthized-expression? expr) (deparenthize expr) expr)))
    (cond ((if (= (length expr) 1) (variable? (car expr)) false) (car expr))
          ((if (= (length expr) 1) (number? (car expr)) false) (car expr))
          ((sum? expr) (make-sum (addend expr)
                                 (augend expr)))
          ((product? expr) (make-product (multiplier expr)
                                         (multiplicand expr))))))

(define (deparenthize expr) (car expr))

;;'(+ x y)
(define (sum? x)
  (and (pair? x) (in? '+ x)))

(define (addend s)
  (process-expr (car (split-on '+ s))))

(define (augend s)
  (process-expr (cdr (split-on '+ s))))

(define (make-sum a1 a2)
  (cond ((=number? a1 0) a2)
        ((=number? a2 0) a1)
        ((and (number? a1) (number? a2)) (+ a1 a2))
        (else (list a1 '+ a2))))

;;'(* x y)
(define (product? x)
  (and (pair? x) (not (in? '+ x)) (in? '* x)))

(define (multiplier p)
  (process-expr (car (split-on '* p))))

(define (multiplicand p)
  (process-expr (cdr (split-on '* p))))

(define (make-product m1 m2)
  (cond ((or (=number? m1 0) (=number? m2 0)) 0)
        ((=number? m1 1) m2)
        ((=number? m2 1) m1)
        ((and (number? m1) (number? m2)) (* m1 m2))
        (else (list m1 '* m2))))

(define (deriv expr var)
  (cond ((number? expr) 0)
        ((variable? expr)
         (if (same-variable? expr var) 1 0))
        ((sum? expr)
         (make-sum (deriv (addend expr) var)
                   (deriv (augend expr) var)))
        ((product? expr)
         (make-sum
           (make-product (multiplier expr)
                         (deriv (multiplicand expr) var))
           (make-product (deriv (multiplier expr) var)
                         (multiplicand expr))))
        (else
         (error "unknown expression type -- DERIV" expr))))

>(deriv '(x + 3 * (x + y + 2)) 'x)
4

Posted 09/05/2010 by Emmanuel Jacyna in SICP

Tagged with , , , , , ,

SICP – Section 2.2.4   Leave a comment

This section is a powerful demonstration of abstraction, using a “picture language”. For this section I used the sicp package from the PLaneT repository in DrScheme. Normally, I just use mzscheme and vim, but apparently you need DrScheme open to use that particular (graphical) package. Anyway, I found it pretty enjoyable, and even made some fractals with it.

;;Exercise 2.44

They could have made this one a little tougher ;)
Telling us to flip the arguments to right-split took any challenge out of it…

(define (up-split painter n)
  (if (= n 0)
      painter
      (let ((smaller (up-split painter (- n 1))))
        (below painter (beside smaller smaller)))))

;;Exercise 2.45

We follow the usual patter of making abstractions.

(define (split op1 op2)
  (define (rec painter n)
    (if (= n 0)
        painter
        (let ((smaller (rec painter (- n 1))))
          (op1 painter (op2 smaller smaller)))))
  rec)

(define up-split (split below beside))
(define right-split (split beside below))

;;Exercise 2.46

Not much to it, I used a list, but a cons would do fine too, however, I decided on list, because perhaps we’ll want to add a z coordinate for 3D vectors.

(define (make-myvect x y)
  (list x y))
(define (xcor-myvect vect)
  (car vect))
(define (ycor-myvect vect)
  (cadr vect))

(define (add-myvect a b)
  (make-myvect (+ (xcor-myvect a) (xcor-myvect b))
             (+ (ycor-myvect a) (ycor-myvect b))))

(define (sub-myvect a b)
  (make-myvect (- (xcor-myvect a) (xcor-myvect b))
             (- (ycor-myvect a) (ycor-myvect b))))

(define (scale-myvect s v)
  (make-myvect (* s (xcor-myvect v))
             (* s (ycor-myvect v))))

;;Exercise 2.47

First definition

(define (make-myframe origin edge1 edge2)
  (list origin edge1 edge2))

(define (origin-myframe f) (car f))

(define (edge1-myframe f) (cadr f))

(define (edge2-myframe f) (caddr f))

Second definition

(define (make-myframe origin edge1 edge2)
  (cons origin (cons edge1 edge2)))

(define (origin-myframe f) (car f))

(define (edge1-myframe f) (cadr f))

(define (edge2-myframe f) (cddr f))

;;Exercise 2.48

(define (make-mysegment start end) (cons start end))

(define (start-mysegment seg) (car seg))

(define (end-mysegment seg) (cdr seg))

;;Exercise 2.49


;;a.  The painter that draws the outline of the designated frame.
(define outline (segments->painter (list
  (make-segment (make-vect 0 0)
                (make-vect 0 1))
  (make-segment (make-vect 0 0)
                (make-vect 1 0))
  (make-segment (make-vect .99 0)
                (make-vect .99 1))
  (make-segment (make-vect 0 .99)
                (make-vect 1 .99)))))

;;b.  The painter that draws an ``X'' by connecting opposite corners of the frame.
(define X (segments->painter (list
  (make-segment (make-vect 0 0)
                (make-vect 1 1))
  (make-segment (make-vect 1 0)
                (make-vect 0 1)))))

;;c.  The painter that draws a diamond shape by connecting the midpoints of the sides of the frame.
(define diamond (segments->painter (list
  (make-segment (make-vect 0 .5)
                (make-vect .5 0))
  (make-segment (make-vect .5 0)
                (make-vect 1 .5))
  (make-segment (make-vect 1 .5)
                (make-vect .5 1))
  (make-segment (make-vect .5 1)
                (make-vect 0 .5)))))

;;d.  The wave painter.
(define wave (segments->painter (list
  (make-segment (make-vect 0 .84) (make-vect .13 .6))
  (make-segment (make-vect .13 .6) (make-vect .3 .66))
  (make-segment (make-vect .3 .66) (make-vect .4 .66))
  (make-segment (make-vect .4 .66) (make-vect .36 .84))
  (make-segment (make-vect .36 .84) (make-vect .4 1))
  (make-segment (make-vect .6 1) (make-vect .64 .84))
  (make-segment (make-vect .64 .84) (make-vect .6 .66))
  (make-segment (make-vect .6 .66) (make-vect .71 .66))
  (make-segment (make-vect .71 .66) (make-vect 1 .34))
  (make-segment (make-vect 1 .16) (make-vect .6 .44))
  (make-segment (make-vect .6 .44) (make-vect .74 0))
  (make-segment (make-vect .6 0) (make-vect .5 .3))
  (make-segment (make-vect .5 .3) (make-vect .4 0))
  (make-segment (make-vect .24 0) (make-vect .34 .5))
  (make-segment (make-vect .34 .5) (make-vect .3 .6))
  (make-segment (make-vect .3 .6) (make-vect .14 .4))
  (make-segment (make-vect .14 .4) (make-vect 0 .64)))))

;;Exercise 2.50
The key to figuring these out is to draw a diagram of the unit square, draw the original picture, and then draw the rotated one, and note the coordinates of the origin, edge1, and edge2.

(define (myflip-horiz painter)
  ((transform-painter (make-vect 1 0)
                      (make-vect 0 0)
                      (make-vect 1 1)) painter))

(define (rotate-90 painter)
  ((transform-painter (make-vect 1 0)
                     (make-vect 1 1)
                     (make-vect 0 0)) painter))

(define (rotate-180 painter)
  ((transform-painter (make-vect 1 1)
                      (make-vect 0 1)
                      (make-vect 1 0)) painter))

(define (rotate-270 painter)
  ((transform-painter (make-vect 0 1)
                      (make-vect 0 0)
                      (make-vect 1 1)) painter))

;;Exercise 2.51

(define (my-below painter1 painter2)
  (let ((split-point (make-vect 0 .5)))
    (let ((paint-top
           ((transform-painter split-point
                               (make-vect 1 .5)
                               (make-vect 0 1)) painter1))
          (paint-bottom
           ((transform-painter (make-vect 0 0)
                               (make-vect 1 0)
                               split-point) painter2)))
      (lambda (frame)
        (paint-top frame)
        (paint-bottom frame)))))

(define (my-below2 painter1 painter2)
  (rotate-90 (beside (rotate-270 painter1) (rotate-270 painter2))))

Okay, this has been a pretty boring article… lack of pictures, &c. However, I do have a couple pictures of some nice fractals that I generated with some functions I wrote in this picture language.

The sierpinski painter generates a sierpinski triangle with n iterations using an MRCM (Multiple Reduction Copy Machine) process. This is based on the idea from the book, Computational Beauty of Nature.

(define (sierpinski painter n)
  (if (= n 0)
      painter
            (let ((top ((transform-painter (make-vect .25 0)
                      (make-vect .75 0)
                      (make-vect .25 1))
                      painter)))
        (sierpinski (below (beside painter painter) top) (- n 1))))) 

And here it is generating it with the einstein painter.

There’s also another neat fractal, which is defined as

(define (crystal painter n)
  (if (= n 0)
      painter
            (let ((top ((transform-painter (make-vect .25 0)
                      (make-vect .75 0)
                      (make-vect .25 1))
                      painter)))
        (crystal (below (beside (rotate-90 painter)
                                   (rotate-270 painter))
                           top)
                    (- n 1))))) 

And looks like

As you can see, it’s pretty easy to define MRCM fractals using this picture language.

Posted 24/04/2010 by Emmanuel Jacyna in Code, Scheme, SICP

Tagged with , , , ,

A new project   Leave a comment

I’ve started work on a new project, pyafg (pyafg is an affine fractal generator). It’s a little python program that generates affine fractals using the iterated function system algorithm. I was inspired to start it whilst reading the computational beauty of nature; I’ll write a post up about my experiences hacking it later. For now, download it, play around with it, and enjoy!

(Note, I did only hack this up in 2 days. It’s nowhere near complete, but I’ve made a very good start to it. Expect more features!)

Computer Generated Fern

A Fern I generated

Posted 08/04/2010 by Emmanuel Jacyna in Code, pyafg, Python

Tagged with , , , ,

SICP – Section 2.2.2   Leave a comment

Phew, finished another section of chapter 2! This one was pretty fun, mucking around with tree structures :)

P.S. For people who don’t have a hardcopy of the book, you can check out these exercises online.

;;Exercise 2.24

When doing these by hand (which I did) remember that we simply expand like so:
(list 1 (list 2 (list 3 4)))
(cons 1 (cons (cons 2 (cons (cons 3 (cons 4 nil)) nil)) nil))

Thus, the interpreter spits out:
(1 (2 (3 4)))
Here’s the box & pointer diagram:

Box and Pointer diagram for (1 (2 (3 4)))

Box and Pointer diagram for (1 (2 (3 4)))

And the Tree Diagram:

Tree Diagram for (1 (2 (3 4)))

Tree Diagram for (1 (2 (3 4)))

;;Exercise 2.25

> (define a (list 1 3 (list 5 7) 9))
> (display (car (cdr (car (cdr (cdr a))))))
7
> (define b (list (list 7)))
> (display (car (car b)))
7
> (define c (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7)))))))
> (display (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr c)))))))))))))
7

;;Exercise 2.26

> (display (append x y))
(1 2 3 4 5 6)
> (display (cons x y)
((1 2 3) 4 5 6)
> (display (list x y))
((1 2 3) (4 5 6))

;;Exercise 2.27

This was an interesting exercise in thinking recursively. One of my favourite things about recursion is that so long as you define a base case, the function works almost magically. We are indeed controlling the spirits in the machine :)

(define (deep-reverse l)
  (define (iter l r)
    (cond ((null? l) r)
             ((pair? (car l)) (iter (cdr l) (cons (deep-reverse (car l)) r)))
             (else (iter (cdr l) (cons (car l) r)))))
  (iter l '()))

;;Exercise 2.28

This one I did last night, with good old pen & paper, and the trusty human evaluator, the brain :)
One of the things I love about lisp is its really easy syntax which makes it possible for me to parse it logically. Anyway, the first time I did this, I was using cons in place of append, which was preserving the original structure of the lists. After a bit of head scratching, I realized that what I actually wanted to be done was to merge the lists. Hence the use of append and only returning lists in this function.

(define (fringe l)
  (cond ((null? l) '())
        ((not (pair? l)) (cons l '()))
        (else (append (fringe (car l)) (fringe (cdr l))))))

;;Exercise 2.29
;;Part A
The selectors just have to take into account that we are dealing with lists not conses. That is the structure is:

a = (cons 'left-branch (cons 'right-branch nil))

So to access right-branch we do:

(car (cdr a))
Code follows:

(define (left-branch mobile)

  (car mobile))

(define (right-branch mobile)
  (car (cdr mobile)))

(define (branch-length branch)
  (car branch))

(define (branch-structure branch)
  (car (cdr branch)))

;;Part B
This procedure is best defined by referring to a branch weight, as well as a mobile weight. This way we do not use extraneous code (abstraction, remember!), and it just flows better in the mind.


(define (branch-weight branch)
  (if (number? (branch-structure branch))
      (branch-structure branch)
      (total-weight (branch-structure branch))))

(define (total-weight mobile)
  (+ (branch-weight (left-branch mobile))
     (branch-weight (right-branch mobile))))

;;Part C
This one had me confused for a while, but again, to achieve enlightenment, we must talk about a branch being able to be balanced, as well as an actual mobile.


(define (torque branch)
  (* (branch-length branch) (branch-weight branch)))

(define (branch-balanced? branch)
  (if (number? (branch-structure branch))
      true
      (balanced? (branch-structure branch))))

(define (balanced? mobile)
  (and (= (torque (right-branch mobile)) (torque (left-branch mobile)))
       (and (branch-balanced? (right-branch mobile))
            (branch-balanced? (left-branch mobile)))))

;;Part D
Because of our wonderful abstraction, the only thing we need change are the selectors!

(define (left-branch mobile)
  (car mobile))

(define (right-branch mobile)
  (cdr mobile))

(define (branch-length branch)
  (car branch))

(define (branch-structure branch)
  (cdr branch))

;;Exercise 2.30

This one’s pretty easy, I think they just want to make sure we see the possibility to abstract.

(define (square-tree tree)
  (cond ((null? tree) '())
        ((not (pair? tree)) (square tree))
        (else (cons (square-tree (car tree)) (square-tree (cdr tree))))))

;;Exercise 2.31

And here is the abstraction :)

(define (tree-map op tree)
  (cond ((null? tree) '())
        ((not (pair? tree)) (op tree))
        (else (cons (tree-map op (car tree)) (tree-map op (cdr tree))))))

;;Exercise 2.32

I found this one quite tricky, but reasoned that we must do something with (car s). So I figured that they wanted us to pair (car s) to rest somehow. The most obvious way to do this is using a cons in the function. I have italicized the added part.

(define (subsets s)
  (if (null? s)
      (list '())
      (let ((rest (subsets (cdr s))))
        (append rest (map (lambda (x) (cons (car s) x)) rest)))))

I can’t give a mathematical explanation for this, as my darned high school education hasn’t said much about set theory so far. However, it’s not too hard to follow, that we are basically appending the car of each iteration, onto the cdr, in order to get (() (1) (2) (1 2)).

Okay, so that’s not a clear explanation :D
Anyone have a better one ;)

Posted 03/04/2010 by Emmanuel Jacyna in Code, Scheme, SICP

Tagged with , , , ,