newlearner
newlearner

Reputation: 149

How to make sublists of a list in Lisp?

I want to make sublists of a given list when my first number is lower than my next number. I already wrote something but it's not working, it says 'NIL ist not a real number' I hope someone can help me further

(defun order(lst)
       (cond ((null lst) nil)
            (t (if (< (car lst) (cadr lst))
                (cons (car lst) (cadr lst))) (order (rest lst)))))


(print(order '(1 4 5 12 22 34 7 9 0)))

 //Output should be this -->((1 4 5) (12 22 34) (7 9) (0))

Upvotes: 1

Views: 225

Answers (1)

claasic
claasic

Reputation: 1050

Since this seems like homework just some pointers:

  1. Right now you are only forming a new list with cons that is exactly two long. Think about how you want the recursion to go to either extend this new list if necessary or include new elements before "closing" it.

  2. You don't call any further recursion when you find a sorted pair. Your code just ends.

  3. If the two compared elements are NOT sorted you do nothing with the old head, you just drop it. Overall there is no "outer" list generated in the course of your algorithm.

  4. Right now cadr might run into the end of the list. So < will be called on a number and nil which leads to disaster.

Upvotes: 3

Related Questions