recursive function lisp return list

前提是你 提交于 2019-12-12 02:15:23

问题


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.


回答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))


来源:https://stackoverflow.com/questions/28494515/recursive-function-lisp-return-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!