6

Say I have a function that takes a list and does something:

(defun foo(aList)
   (loop for element in aList ...))

But if the list is nested I want to flatten it first before the loop does stuff, so I want to use another function (defun flatten(aList)) that flattens any list:

(defun foo(flatten(aList))
   (loop for element in aList ...))

Lisp doesn't like this. Is there another direct way around this?

2 Answers 2

5

Here's one way:

(defun foo (alist)
  (loop for element in (flatten alist) ...)
Sign up to request clarification or add additional context in comments.

Comments

1

You can pass the function as an &optional argument.

(defun foo (alist &optional fn)
  (if (not (null fn))
      (setf alist (funcall fn alist)))
  (dostuff alist))

A sample run where dostuff just print its argument:

(foo '(1 2 (3)))
=> (1 2 (3))
(foo '(1 2 (3)) #'flatten)
=> (1 2 3)

This approach is more flexible as you are not tied to just one 'pre-processor' function.

Comments

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.