【问题标题】:List of Lists trouble LISPList of Lists 麻烦 LISP
【发布时间】:2013-10-29 22:12:44
【问题描述】:

我是 LISP 新手,所以我不太擅长这个...所以我的问题是,我得到了一个结构(列表列表),我的工作是创建一个函数来检索第二个每个子列表中的项目(从 0 开始计数)。所以最后还是想回(果果代理场)。

我可以执行遍历列表的基本递归调用,但我似乎无法弄清楚如何获取子列表中的第二项。

列表结构:

(defparameter *jack*
'((orange#8 apple fruit basment)
(pear#12 mango fruit basment)
(jones rabbit agent closet)
(jack dog agent yard)
))

到目前为止我的代码:

(defun attempt(*data*)
(cond ((null *data*)
     nil
     )
    ((attempt (rest *data*)))
    ))

我在想的是,我应该使用 first 和 rest 遍历列表子列表,但就像我说的那样,我想不通。帮助?

【问题讨论】:

标签: lisp common-lisp


【解决方案1】:
CL-USER> (mapcar #'caddr *jack*)
(FRUIT FRUIT AGENT AGENT)

编辑:如果您想练习递归方法,请尝试:

(defun attempt (list-of-lists)
    (if (null list-of-lists) nil
        (cons (third (car list-of-lists))
              (attempt (cdr list-of-lists)))))

EDIT2:尾递归:

(defun attempt-tail (list-of-lists)
    (labels ((iter (rest ans)
               (if (null rest) (nreverse ans)
                   (iter (cdr rest) (push (third (car rest)) ans)))))
      (iter list-of-lists nil)))

EDIT3:当我在它的时候,这里是循环版本:

(loop for list in *jack* collect (third list))

【讨论】:

  • 首先谢谢!其次,我想知道您是否可以使用尾递归来回答这个问题?
【解决方案2】:

这很可能是您正在寻找的:

(mapcar #'cadr *jack*)

【讨论】:

    【解决方案3】:

    是的,您可以为此过程定义一个尾递归过程;

    (defun nths (n l)"returns list of nths of a list of lists l"
      (nths-aux n l '()))
    
    (defun nths-aux (n l A)
      (if (null l) A;or (reverse A)
       (nths-aux n (cdr l)  (cons (nth n (car l)) A))))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多