[racket] [htdp] Help with Exercise 12.4.2

From: Jos Koot (jos.koot at telefonica.net)
Date: Tue Jul 6 16:15:44 EDT 2010

Exercise 12.4.2 is notorius. When looking to (list 'a 'b 'c), you should
exspect 6 distinct permutations.
Jos

> -----Original Message-----
> From: users-bounces at racket-lang.org 
> [mailto:users-bounces at racket-lang.org] On Behalf Of Sam Griff
> Sent: 06 July 2010 20:00
> To: users at racket-lang.org
> Subject: [racket] [htdp] Help with Exercise 12.4.2
> 
> Hello. Like many others working through HtDP I have hit the 
> wall at this exercise. I'm not sure what I have so far is in 
> line with the "proper" way to do this exercise and would 
> appreciate any help/suggestions. Here is the code I have so far:
> 
> ;; A list of words is either
> ;; 1. empty
> ;; 2. (cons w low)
> ;;    where w is a word and low is a list of words
> 
> ;; 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 (insert-everywhere/in-all-words (first a-word)
>             (arrangements (rest a-word)))]))
> 
> ;; Contract:
> ;; insert-everywhere/in-single-word : symbol word -> 
> list-of-words ;; Purpose:
> ;; to insert a symbol everywhere in a single word ;; Examples:
> ;; (insert-everywhere/in-single-word 'a empty) should produce 
> (list 'a) ;; (insert-everywhere/in-single-word 'b (list 'a)) 
> should produce (list (list 'a 'b) (list 'b 'a)) ;; 
> (insert-everywhere/in-single-word 'c (list 'a 'b)) should 
> produce (list (list 'c 'a 'b) (list 'a 'c 'b) (list 'a 'b 
> 'c)) ;; Template:
> ;; (define (insert-everywhere/in-single-word s w)
> ;;   (cond
> ;;     [(empty? w) ...]
> ;;     [else ... (first w) ... 
> (insert-everywhere/in-single-word s w) ...]))
> (define (insert-everywhere/in-single-word s w)
>   (cond
>     [(empty? w) (list s)]
>     [else  (list (list s (first w)) (cons (first w) 
> (insert-everywhere/in-single-word s (rest w))))]))
> 
> ;; insert-everywhere/in-all-words : symbol list-of-words -> 
> list-of-words ;; to insert a symbol everywhere in a list of 
> words (define (insert-everywhere/in-all-words s low)
>   (cond
>     [(empty? low) empty]
>     [else (append (insert-everywhere/in-single-word s (first 
> low)) (insert-everywhere/in-all-words s (rest low)))]))
> 
> 
> ;; Tests:
> (define testword1 (list 'a))
> (define testword2 (list 'a 'b))
> (check-expect (insert-everywhere/in-single-word 'a empty) 
> (list 'a)) (check-expect (insert-everywhere/in-single-word 'b 
> testword1) (list (list 'b 'a) (list 'a 'b))) (check-expect 
> (insert-everywhere/in-single-word 'c testword2) (list (list 
> 'c 'a 'b) (list 'a 'c 'b) (list 'a 'b 'c)))
> 
> 
> Thanks,
> 
> Sam
> _________________________________________________
>   For list-related administrative tasks:
>   http://lists.racket-lang.org/listinfo/users




Posted on the users mailing list.