简体   繁体   中英

Scheme recursive or iterative

(define unique?
  (lambda (l)
    (or (null? l) 
        (null? (cdr l))
        (and (not (in? (car l) (cdr l))) 
             (unique? (cdr l)))))

Can someone please tell me if it's an iteratibe or recursive procedure? I guess it is iterative, but I am not sure and I don't know how to explain i

You code is clearly recursive because unique? calls unique? . The procedure unique? will be iterative if the recursive call occurs in the tail position. The R6RS standard, see Section 11.20 'Tail calls and tail contexts', details the tail contexts for each syntactic form. Analyzing your lambda we reason as:

  • The last expression in a lambda is a tail context, so your or ... is a tail expression
  • The last expression in a or is a tail expression, so your and ... is a tail expression
  • The last expression in a and is a tail expression, so your unique? is a tail call

Therefore, unique? calls itself as a tail call and is thus iterative.

The function is recursive because it calls itself. Note, however that since it is tail-recursive, it can be compiled to iterative form.

The criteria for a function to be tail recursive is simply that there be nothing to do after the recursive call returns, which is true in your case.

How to convert a tail-recursive function into a loop

To transform a tail-recursive function into a while loop, follow the following steps. (There is not an automatic function for converting an arbitrary recursive function into a while loop--you have to convert it into a tail-recursive function first.)

  1. Turn the helper function parameters into local variables; their initial values are the same as the initial values for the call to the helper function from the main function.
  2. The continue test is the same as the test in the helper function, for the direction that causes a tail-recursive call to be made. (If the tail-recursive call appears in the else part of the if, then add a call to not.)
  3. The body uses set! to update the value of each variable; the values are the same as the arguments passed to the tail-recursive call.
  4. Return the value of the accumulator; this comes after the while loop.

Source: Tail recursion and loops

Since the other two answers explained what and why your function is tail-recursive; I am just going to leave an easy way for beginners to remember the difference:

A tail - recursive function does not operate on the recursive call.

A non - tail-recursive function does operate on the recursive call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM