Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This is HtDP Excercise 12.4.2.

Develop a function insert-everywhere. It consumes a symbol and a list of words. The result is a list of words like its second argument, but with the first argument inserted between all letters and at the beginning and the end of all words of the second argument.

This is what I wrote:

#lang racket

;Data Definition:
;a symbol, list of symbols

;insert-everywhere: symbol, list of symbols -> list of list of symbols
;The function returns a list of list of symbols wherein the symbol is inserted at every position

; (insert-everywhere 'a '(b c d)) -> '((a b c d) (b a c d) (b c a d) (b c d a))


(define (insert-everywhere sym los)
  (define lst-len (find-len los))
  (define (iter n)
    (cond ((= n (+ lst-len 1)) '())
          (else (cons (insert n sym los) (iter (+ n 1))))))
  (iter 0))
;The above function first finds the list length. 
;Then it itereratively inserts the symbol at every position one by one, including in the end.

;Data Definition:
;list of symbols

;find-len : list of symbols-> number
;find the length of the list

;(find-len (list 'b 'c 'd)) -> 3


(define (find-len los)
  (cond ((null? los) 0)
        (else (+ 1 (find-len (cdr los))))))

;Data Definition:
;number , symbol, list of symbols

;insert : position, element, list of symbols-> list of symbols
;insert the element in the given position in the list

;(insert 2 'a '(b c d)) -> '(b c a d)


(define (insert pos elm los)
  (cond ((= pos 0) (cons elm los))
        (else (cons (car los) (insert (- pos 1) elm (cdr los))))))

Here is the tests i conducted:

(insert-everywhere 'a '()) ; returns '((a))
(insert-everywhere 'a '(b)) ; returns '((a b) (b a))
(insert-everywhere 'a '(b c d)) ; returns '((a b c d) (b a c d) (b c a d) (b c d a))

So it works. But I think this is not the way it was supposed to be solved. In their hint, they ask to use only recursion an append. I didn't really get it. Could someone suggest a better answer.

share|improve this question
You may have misunderstood the question. Also use standard procedures as much as possible. e.g. length instead of find-len. –  abuzittin gillifirca Mar 7 '13 at 7:10

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.