0

I know this is a newbie question I apologize in advance. I'm writing a recursive function which returns the number of 'o in a given list

(defun garde-o (liste)
    (cond
        ((not liste) 0) 
        ((equal (car liste) 'o)  (+ 1 (garde-o(cdr liste)))   )
        ((garde-o(cdr liste))  )
    )
)

Instead of returning the number of occurence I would like to return the given list with only the 'o.

Like that:

(garde-o '(a o x & w o o))

should return => (o o o)

I don't want to use pop,push,set... just I can't find of to return this.

4
  • That's not python. It's lisp. Commented Feb 13, 2015 at 7:30
  • No I wrote too quickly it was lisp of course. Apologize. Commented Feb 13, 2015 at 7:33
  • Have you made attempts to solve this problem? Commented Feb 18, 2015 at 0:29
  • Use the cons Luke. Use not non-functional you. Commented Jan 9, 2016 at 21:36

1 Answer 1

1

Notice that given the number of occurrences, for example 10, you can simply do

(make-list 10 :initial-element 'o)

or equivalently

(loop repeat 10 collect 'o)

To count the 'o in your list, you can do

(count 'o '(a b c o p o a z))

Thus, a simple solution for your function would be

(defun garde-o (a)
    (make-list (count 'o a) :initial-element 'o))

However, you can do this recursively too

(defun garde-o (a)
    (cond ((null a) nil)
          ((eq (car a) 'o) (cons 'o (garde-o (cdr a))))
          (t (garde-o (cdr a)))))

and non-recursively

(defun garde-o (a)
    (loop for x in a when (eq x 'o) collect x))
Sign up to request clarification or add additional context in comments.

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.