joshbusiness
joshbusiness

Reputation: 128

Lisp program that creates a sublist with each increment

I'm currently working on a program that increments through a list and creates a sublist within a list for each time it's incremented. for example if I had a list of

(1 2 3 4 5 6)

. Then I want to increment through it and create

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

. So far I have:

(defun INCREMENT (L) (unless (endp L) (cons (list (first L)) (INC (rest L)))))

but all this will return is

((1) (2) (3) (4))

I know it's just increment the number of times list is used along with going through the elements of the list but I'm still kind of learning the syntax of Lisp. Can anybody help me out with this?

Upvotes: 3

Views: 88

Answers (1)

Óscar López
Óscar López

Reputation: 236122

Here's a possible solution, the trick is to use list before calling the recursion. Also notice that we must handle the base cases: when the list is empty and when there's only one element left:

(defun INCREMENT (L)
  (cond ((endp L) '())
        ((endp (rest L)) (list (first L)))
        (t (cons (first L)
                 (list (INCREMENT (rest L)))))))

Upvotes: 5

Related Questions