views:

102

answers:

2

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?

+4  A: 

Here's one way:

(defun foo (alist)
  (loop for element in (flatten alist) ...)
Xach
great, thank you!
John
+1  A: 

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.

Vijay Mathew