Lisp Reverse “all” Function

折月煮酒 提交于 2019-12-06 05:46:19

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)))
(defun reverse-list (list)
  (let ((result nil))
    (dolist (e list result)
      (push e result))))

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!