递归函数lisp返回列表 [英] recursive function lisp return list

查看:107
本文介绍了递归函数lisp返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是我事先向您道歉的新手问题.我正在编写一个递归函数,该函数返回给定列表中'o的数量

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

我不想返回出现的次数,而是只返回给定的列表'o.

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

喜欢:

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

应返回=> (o o o)

我不想使用poppushset ...只是我找不到要返回的值.

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

推荐答案

请注意,给定出现的次数(例如10),您可以简单地做到

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

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

或等效地

(loop repeat 10 collect 'o)

要计算列表中的'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)))))

并且非递归

(defun garde-o (a)
    (loop for x in a when (eq x 'o) collect x))

这篇关于递归函数lisp返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆