[plt-scheme] HTDP 12.4.2

From: wooks wooks (wookiz at hotmail.com)
Date: Wed Jun 21 20:03:40 EDT 2006

This is an excercise that I skipped as being too difficult the first time I 
attempted HTDP.

http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-16.html#node_sec_12.4

I was on the verge of giving up again when I managed to write an  
insertEverywhere that (it appears to me at least) works to required 
specification. However the results I get from plugging it into the 
arrangements function provided by the excercise do not look right but I 
can't decipher what it is producing.

Here is my code


;CONTRACT
;insertEverywhere : symbol ('a - 'z) list (word) - list of lists
;returns a list of words constructed by interpersing symbol in  position of 
the word
;
(define (insertEverywhere sym letters)
  (infiltrate  sym empty  letters)
  )

;CONTRACT
;infiltrate : symbol list list - list of words
; (define (infiltrate infiltrator front back) ...
; auxiliary function for insertEverywhere

;TEMPLATE
;(define (infiltrate infiltrator front back)
;   (cond
;      [(empty? back) ....]
;      [(empty? front) ..(infiltrate infiltrator (list (first back)) (rest 
back).]
;      [else (..... (infiltrate infiltrator (append front (list (first 
back))) (rest back))]
;    )
;  )

(define (infiltrate infiltrator front back)
  (cond
    [(empty? back) (append front (list infiltrator))]
    [(empty? front)
     (cons (cons infiltrator back)
           (infiltrate infiltrator (append (list (first back) )) (rest 
back))) ]
    [else
     (cons (append front (list infiltrator) back)
           (infiltrate infiltrator (append front (list (first back))) (rest 
back)))]
    )
  )
;TESTS
(insertEverywhere 'g (cons 'a (cons 'b (cons 'c empty))))


;; arrangements : word  ->  list-of-words
;; to create a list of all rearrangements of the letters in a-word
(define (arrangements a-word)
  (cond
    [(empty? a-word) (cons empty empty)]
    [else (insertEverywhere (first a-word)
            (arrangements (rest a-word)))]))

;TESTS
(arrangements  (cons 'a (cons 'b (cons 'c empty))))




Posted on the users mailing list.