lisp - 用最后一个元素替换子列表

标签 lisp common-lisp

(defun rep(list)
(format t"~a~%" list)
    (cond
        ((null list) nil)
        ((atom (car list)) (cons (car list) (rep  (cdr list))))
        ((listp (car list))  (cons (car (reverse (car list))) (cdr list)))
        (t (rep list))
    )
)

编写一个函数,用它的最后一个元素替换列表的每个子列表。 子列表是来自第一级的元素,即列表。 示例:

(a (b c) (d (e (f)))) ==> (a c (e (f))) ==> (a c (f)) ==> (a c f)
     (a (b c) (d ((e) f))) ==> (a c ((e) f)) ==> (a c f)

我有上述问题需要解决。知道了一点,但我被卡住了。 显然它不会转到列表中的下一个元素,我不知道为什么。有什么想法吗?

最佳答案

我会这样分解:

(defun last-element (lst)
  (if (listp lst)
    (last-element (car (last lst)))
    lst))

(defun rep (lst)
  (when lst
    (cons (last-element (car lst)) (rep (cdr lst)))))

然后

(rep '(a (b c) (d (e (f)))))
=> '(A C F)

关于lisp - 用最后一个元素替换子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21728971/

相关文章:

lisp - 如何使用 ltk 显示图像?

macros - 在运行时处理内部变量和数据结构的 LISP 宏

common-lisp - Common Lisp 中 &environment 的作用是什么?

emacs - 在 LispBox 中的 Emacs 中加载 SLIME 编辑命令

function - Common Lisp中#'callee and '被调用者之间的区别

recursion - Lisp逆向 "all"函数

lisp - 如何在 Common Lisp 中进行模式匹配

package - Common Lisp 将包名称附加到宏中带引号的键中

list - 在 Common Lisp 中创建升序数字列表

common-lisp - CLOS 是否对字符串有 eql 特化调度?