3

I have this iterative process in Scheme. (In fact I don't really know what kind of process it really is)

(define (contains-double? lst)
 (cond
  ((or (null? lst) (null? (cdr lst))) #f)
  ((eq? (car lst) (cadr lst)) #t)
  (else (contains-double? (cdr lst)))))

It checks If there are 2 of the same numbers next to each other. For example:

(contains-double? '(1 2 3 3 3 5 2))    => #t
(contains-double? '(1 2 3 5 3 2))      => #f
(contains-double? '(1 2 3 2 2))        => #t

Can I make this process recursive?

Thanks in advance

Arno Moonens
  • 1,163
  • 1
  • 10
  • 19

1 Answers1

2

The procedure in the question is recursive (contains-double? is calling itself), but the process it generates is iterative because the procedure is written in a tail-recursive style - meaning that there is nothing to do after the procedure returns from the recursive call, except return its value.

The process generated by this procedure can be made recursive by removing the tail recursion:

(define (contains-double? lst)
  (if (or (empty? lst) (empty? (rest lst)))
      #f
      (or (contains-double? (rest lst))
          (= (first lst) (second lst)))))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    Your code is still tail-recursive. ;-) You could make it non-tail-recursive by swapping the two branches of the `or`: this turns it into a right-fold instead of the left-fold it currently is. – C. K. Young Nov 10 '12 at 17:34
  • @ChrisJester-Young Thanks, fixed it. I had my doubts if the `or` counted or not as tail recursive, because of the short-circuit evaluation – Óscar López Nov 10 '12 at 17:45