tags:

views:

35

answers:

1

My professor has given us a refresher assignment in clisp. One exercise is to achieve the same thing in three ways: Return a flattened list of all positive integers in a given list.

Now, there's only one way I really like doing this, using cons and recursion, but he wants me to do this using mapcan and a loop (I suspect lisp is not his first choice of language because this style of coding feels extremely resistant to the nature of lisp). I'm having a hard time working out how one would do this using a loop...I need to first start a list, I suppose?

I apologize for vague language as I'm not really sure how to TALK about using a functional language to write procedurally. Following is my first attempt.

(defun posint-loop (l)  
  (loop for i in l
        do (if (listp i)  
               (posint-loop i)  
               (if (integerp i)  
                   (if (> i 0)  
                       (append i) ; this doesn't work because there's nothing to
                                  ; start appending to!
                       nil)  
                   nil))))
+1  A: 

In order to establish a new lexical binding, use let or the with keyword of loop. In order to extend an existing list, you might want to use push; if you need the original order, you can nreverse the new list finally.

Another way would be to use the when and collect keywords of loop.

Another hint: mapcan implicitly creates a new list.

Svante