[plt-scheme] HtDP newbie question, 12.4.2

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Mon Mar 31 12:37:35 EDT 2008

Not bad.

Here is a rewrite, with all appends eliminated when unnecessary:

> ;MAIN FUNCTION: arrangements: word --> list of words
> (define (arrangements a-word)
>   (cond [(empty? a-word) (cons empty empty)]
>         [else (insert-everywhere/in-all-words (first a-word)  
> (arrangements (rest a-word)))]))
>
> ;HELPER #1: insert-everywhere/in-all-words : letter, list of words  
> --> list of words
> (define (insert-everywhere/in-all-words s low)
>   (cond
>     [(empty? (rest low)) (insert-everywhere/one-word s (first low))]
>     [else (append (insert-everywhere/one-word s (first low))  
> (insert-everywhere/in-all-words s (rest low)))]))
>
> ;HELPER #2: insert-everywhere/one-word : letter, word --> list of  
> words
> ;NOTE: this function just adds the last word to Helper #3
> (define (insert-everywhere/one-word letter a-word)
>   (cons (append a-word (list letter)) (insert-everywhere-except- 
> last-letter letter a-word)))

;; I do not understand why the above function needs a helper.

> ;HELPER #3: insert-everywhere-except-last-letter : letter, word -->  
> list of words
> (define (insert-everywhere-except-last-letter letter a-word)
>   (cond
>     [(empty? a-word) empty]
>     [(empty? (rest a-word)) (cons (list letter (first a-word)) empty)]
>     [else (cons (cons letter a-word) (add-first-letter (first a- 
> word) (insert-everywhere-except-last-letter letter (rest a-word))))]))
>
> ;HELPER #4 : add-first-letter : letter, list of words --> list of  
> words
> (define (add-first-letter letter low)
>   (cond
>     [(empty? (rest low)) (cons (append (list letter) (first low))  
> empty)]
>     [else (cons (cons letter (first low)) (add-first-letter letter  
> (rest low)))]))



Also, I'd very much recommend test cases for helper functions, too.

Time to move on -- Matthias



Posted on the users mailing list.