【问题标题】:Every other letter in a list? LISP列表中的所有其他字母? LISP
【发布时间】:2014-11-04 19:15:36
【问题描述】:

我对 LISP 比较陌生,我正在为我正在尝试为演示文稿创建的 Lisp 程序尝试一些新东西。

我需要能够打印列表中的所有其他字符,例如,(A B C D E F) 将返回 (A C E) .. 但我很容易混淆...

我通常是 Java 程序员,所以这对我来说有点不同。

我正在尝试使用纯粹的递归来编程。所以类似于......

(defun every-other (lst)
(cond ((null lst) 0)
((    **** now this is where I get confused as to what I should do..
I've tried adding a counter to only remove even numbered elements, but I think I implemented the counter wrong, I also tried remove(cadr lst) lst, but that would only return zeros...

任何帮助将不胜感激..

谢谢!

【问题讨论】:

    标签: list lisp letter


    【解决方案1】:

    更短的递归解决方案:

    (defun every-other (l)
      (unless (null l)
        (cons (first l) (every-other (cddr l)))))
    

    【讨论】:

      【解决方案2】:
      (defun aaa (x)
         (aa (length x) x))
      (defun aa (n x)
              (cond ((null x) nil)
                    ((evenp (- n (length x))) (cons (car x) (aa n (cdr x))))
                    (t (aa n (cdr x)))))
      

      这是一个愚蠢的案例lol~

      【讨论】:

        【解决方案3】:

        只需使用循环。

        (loop :for c :in '(a b c d e f) :by #'cddr
              :collect c)
        

        :Byfor-in 子句中设置步进函数(默认为#'cdr)。为了得到所有其他元素,每次都分两步。 Cddr 是两次申请cdr 的快捷方式。

        【讨论】:

          【解决方案4】:

          为了好玩,基于loop 的解决方案:

          (defun every-other (lst)
            (loop 
              for i in lst
              for keep = t then (not keep) 
              if keep collect i))
          

          【讨论】:

            【解决方案5】:

            既然你说你希望它以递归方式完成,那就逐案考虑吧。

            1. 列表为null -> 返回空列表[空列表为'()]。
            2. 否则列表不为空 -> 在这种情况下,您要构建一个新列表,其中包含 第一个元素,跳过第二个元素,然后抓取 剩余列表的所有其他元素。

            将此案例分析转化为代码如下所示:

            (defun every-other (lst)
              (cond
                ;; If the list is null return the empty list. 
                ((null lst) '()) 
                ;; If the list is not null, construct [cons] a new list with the first element of lst
                ;; and every-other element of the list after the first two elements [rest returns the   
                ;; list without the first element, so we can just use it twice].
                (t (cons (first lst) (every-other (rest (rest lst)))))))
            

            现在对这段代码进行评估应该如下所示:

            (every-other '(a b c d e f))
            => (cons 'a (every-other '(c d e f)))
            => (cons 'a (cons 'c (every-other '(e f))))
            => (cons 'a (cons 'c (cons 'e (every-other '())))
            => (cons 'a (cons 'c (cons 'e '())))
            => (cons 'a (cons 'c '(e)))
            => (cons 'a '(c e))
            => '(a c e)
            

            【讨论】:

            • 很好的帮助!谢谢!!
            猜你喜欢
            • 1970-01-01
            • 2018-04-22
            • 1970-01-01
            • 1970-01-01
            • 2015-04-09
            • 2019-08-23
            • 2017-02-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多