Skip to content

Instantly share code, notes, and snippets.

@sondnm
Forked from twfarland/HTDP12.4.TF_solution.rkt
Created June 13, 2020 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sondnm/66d1c971d9954c43be91c8e9cdb241ff to your computer and use it in GitHub Desktop.
Save sondnm/66d1c971d9954c43be91c8e9cdb241ff to your computer and use it in GitHub Desktop.
My solution for exercise 12.4 in HTDP
;; 12.4 Rearranging words
;; a 'word' is either
;; 1 - empty, or
;; 2 - (cons a w) where a is a symbol
;; ('a, 'b,..., 'z) and w is a word
;; examples:
(define noword empty)
(define red (cons 'r (cons 'e (cons 'd empty))))
(define blue (cons 'b (cons 'l (cons 'u (cons 'e empty)))))
(define pink (cons 'p (cons 'i (cons 'n (cons 'k empty)))))
;; a 'list of words' is either
;; 1 - empty, or
;; 2 - (cons w low) where w is a word and low is a list of words
;; examples:
(define nolow empty)
(define colours (cons red (cons blue (cons pink empty))))
;; arrangements : word -> list-of-words
;; to create a list of words that is 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)))]))
;; insert-everywhere/in-all-words : symbol list-of-words -> list-of-words
;; produces a list of words like the list of words given, but with the
;; given letter inserted between all letters and at the beginning and end
;; of each word in the word list given
(define (insert-everywhere/in-all-words l alow)
(cond
[(empty? alow) empty]
[else (append (insert-everywhere l (first alow))
(insert-everywhere/in-all-words l (rest alow)))]))
;; insert-everywhere : symbol word -> list-of-words
;; given l and a-word, produces a list of words like a-word, but with
;; l insert at the beginning, between all possible letters, or at the end
(define (insert-everywhere l a-word)
(cond
[(empty? a-word) (cons (cons l a-word) empty)]
[else
(cons (cons l a-word)
(prefix-all (first a-word)
(insert-everywhere l (rest a-word))))]))
;; prefix-all : symbol list-of-words -> list-of-words
;; given a symbol and a list of words, produces a new list of words
;; like that given, but with symbol l prefixed to each
(define (prefix-all l words)
(cond
[(empty? words) empty]
[else (cons (cons l (first words))
(prefix-all l (rest words)))]))
(arrangements '(r e d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment