Lisp 反转“全部”功能

发布于 2024-10-06 01:54:58 字数 202 浏览 0 评论 0原文

我想在 lisp 中编写一个函数,使用映射函数反转列表中的所有元素,但我不知道如何开始这个。我想我必须以某种方式使用内置的反向函数。 例如,如果我有列表 (1 2 3 (4 5 6 (7 8 9))) 我会得到 (((9 8 7) 6 5 4) 3 2 1) 或者如果我有列表(1 2 3 (4 5) (6 7)) 我会得到 ((7 6) (5 4) 3 2 1) .. 任何帮助表示赞赏!

I want to write a function in lisp that reverses all elements from the list using map functions but I don't have any idea how to start this.. I think I have to use the built in reverse function somehow..
For example if I have the list (1 2 3 (4 5 6 (7 8 9))) I would get (((9 8 7) 6 5 4) 3 2 1)
or if I had the list(1 2 3 (4 5) (6 7)) I would get ((7 6) (5 4) 3 2 1) ..
Any help is appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苹果你个爱泡泡 2024-10-13 01:54:58

只是一个快速回答,不确定效率/优雅:

(defun reverse-deeply (list)
   (mapcar #'(lambda (li) 
               (cond
                ((consp li) (reverse-deeply li))
                (t li)))
           (reverse list)))

Just a quick answer, not sure about efficiency/elegancy:

(defun reverse-deeply (list)
   (mapcar #'(lambda (li) 
               (cond
                ((consp li) (reverse-deeply li))
                (t li)))
           (reverse list)))
鸵鸟症 2024-10-13 01:54:58
(defun reverse-list (list)
  (let ((result nil))
    (dolist (e list result)
      (push e result))))
(defun reverse-list (list)
  (let ((result nil))
    (dolist (e list result)
      (push e result))))
千鲤 2024-10-13 01:54:58

这是一个在 Common-Lisp 中适合我的版本。

(defun reverse-list (list)
    (if (atom list)
        list ;; Not actually a list, return the atom
      (reverse (mapcar #'reverse-list list)))

;; Testing it out
(reverse-list '((1 2 3) (4 5 (3 6))))

输出:

(((6 3) 5 4) (3 2 1))

Mapcar 是一个函数,它将另一个函数作为其第一个参数,将列表作为其第二个参数。然后它对列表的每个元素调用该函数。它返回所有答案的列表。因此,在我使用“mapcar”反转所有子列表后,我再次调用“reverse”来反转更大的列表。

它在每个子列表上调用的函数是“reverse-list”。这检查列表是否是一个原子。如果是,则它返回自身。如果它是一个列表,那么它会在列表中的每个元素上再次调用mapcar,然后反转结果。

Here is a version that works for me in Common-Lisp.

(defun reverse-list (list)
    (if (atom list)
        list ;; Not actually a list, return the atom
      (reverse (mapcar #'reverse-list list)))

;; Testing it out
(reverse-list '((1 2 3) (4 5 (3 6))))

Output:

(((6 3) 5 4) (3 2 1))

Mapcar is a function that takes another function as its first parameter and a list as its second parameter. It then calls that function on each element of the list. It returns a list of all of the answers. So after I use 'mapcar' to reverse all of the sublists, I call 'reverse' again to reverse the bigger list.

The function that it calls on each sublist is 'reverse-list'. This checks if the list is an atom. If it is, then it returns itself. If it's a list, then it calls mapcar again on each element in the list, then reverses the result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文