To sort out atoms first and then sublists from a list in LISP

后端 未结 5 986
滥情空心
滥情空心 2020-12-07 04:15

I have this homework in LISP where I need to sort out atoms and then sublists from a list. I\'m sure this is supposed to be easy task but as I\'m not much of a programmer th

5条回答
  •  感动是毒
    2020-12-07 04:42

    Just in case you will want to exercise more, and you will find that the examples provided here are not enough :P

    (defun sort-atoms-first-recursive (x &optional y)
      (cond
        ((null x) y)
        ((consp (car x))
         (sort-atoms-first-recursive (cdr x) (cons (car x) y)))
        (t (cons (car x) (sort-atoms-first-recursive (cdr x) y)))))
    
    (defun sort-atoms-first-loop (x)
      (do ((a x (cdr a))
           (b) (c) (d) (e))
          (nil)
        (if (consp (car a))
          (if b (setf (cdr b) a b (cdr b)) (setf b a d a))
          (if c (setf (cdr c) a c (cdr c)) (setf c a e a)))
        (when (null (cdr a))
          (cond
            ((null d) (return e))
            ((null c) (return d))
            (t (setf (cdr b) nil (cdr c) d) (return e))))))
    
    
    (sort-atoms-first-recursive '(5 -1 (2 6 1) (8 7 -3) (0 (9 4)) -6))
    
    (sort-atoms-first-loop '(5 -1 (2 6 1) (8 7 -3) (0 (9 4)) -6))
    

    The second one is destructive (but doesn't create any new conses).

提交回复
热议问题