gpt4 book ai didi

list - 列表中的每个其他字母?语言语言

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:19 25 4
gpt4 key购买 nike

我是 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...

任何帮助将不胜感激..

谢谢!

最佳答案

既然你说你想递归地完成它,那就逐个考虑吧。

  1. 列表为空 -> 返回空列表[空列表为'()]。
  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)

关于list - 列表中的每个其他字母?语言语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25777280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com