Matt
Matt

Reputation: 482

Avoid double recursion

(DEFUN F(L)
   (COND
      ((NULL L) NIL)
      ((LISTP (CAR L))
       (APPEND (F (CAR L))
               (F (CDR L))
               (CAR (F (CAR L)))))
      (T (LIST (CAR L)))
))

This function returns a dotted pair(if the first element is a sublist) with the first element of the sublist as the right part and on the left part are the element on the right and the second element of the list(if not sublist).Now,how can I rewrite this without using the double recursion of (F (CAR L)) and without using SET,SETQ,SETF?

Upvotes: 0

Views: 259

Answers (1)

Barmar
Barmar

Reputation: 780724

Use LET to bind a local variable to the repeated recursive call.

(DEFUN F(L)
   (COND
      ((NULL L) NIL)
      ((LISTP (CAR L))
       (LET ((FCAR (F CAR L)))
         (APPEND FCAR
                 (F (CDR L))
                 (CAR FCAR))))
      (T (LIST (CAR L)))
))

Upvotes: 1

Related Questions