1

How could I prevent the the double recursive call to (f (car l)) without using set/setq/setf ?

(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)))
    )
)

You think the following solves it?

(defun f(l)
  (cond
    ((null l) nil)
    ((listp (car l))
        (funcall #'(lambda(ff) (append ff (f (cdr l)) (list (car ff)))) (f (car l))))
    (T (list (car l)))
   )
)
3
  • This is not directly related to your question, but I don't get what this function is supposed to do. Could you explain a little? Commented Jun 13, 2016 at 14:47
  • You must just check it. It is an exercise ... This is all it is given. You must find out and keep its functionality, but avoid the second recursive call to (f (car l)) without using set/setq/setf. Commented Jun 13, 2016 at 20:09
  • I refactored the code (pastebin.com/raw/N0Aj8Qsq) and I would expect that append operate on proper lists, that's why I added assertions. The function works in degenerate cases with NILs. But you never build a (foo head) such that its first element is a non-empty list, because the base case of the recursion is (list head) with head a non-list. Replacing the last clause's body with (list (list head)) ensures the function returns something when given a proper list as input. I recognize that this is probably not important for this exercise. Commented Jun 14, 2016 at 7:04

1 Answer 1

4

Your attempt is okay, but is usually written as:

...
(bar (foo abcde))
...
(baz (foo abcde))
...

->

(let ((r (foo abcde)))
  ...
  (bar r)
  ...
  (baz r)
  ...)

also note:

(funcall #'(lambda (foo) ...) bar)

can be written in Common Lisp as:

((lambda (foo) ...) bar)

or preferred, as already mentioned, as:

(let ((foo bar))
  ...)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for clearing that up! I don't have any habits yet with CLisp, so thanks for making the code clean!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.