Search code examples
lispcommon-lisp

How to return a specific list


I am trying to code this in LISP and I am having a lot of troubles with it.

This is what I have at the moment:

(defun list_incr (x)
    (if (eq (first x) nil)
        x
        (if (< (first x) (first(rest x)))
            (append (list (first x) (first(rest x))) (list_incr (rest(rest x))))
            (list_incr (cons (first x) (rest(rest x)))))))

If given a list (1 3 2 4), it needs to return (1 3 4). At the moment, my code does it fine for 2 consecutive increasing numbers, but when it decreases it doesn't work anymore.

I need the code to return a list with increasing numbers from the give list.

Some Examples:

if given a list (1 2 4 6 5), it should return (1 2 4 6)

if given (3 1 4 5 2 6), it should return (3 4 5 6)

Thank you!


Solution

  • Here is a possible recursive definition to solve the problem:

    (defun exercise-1d (x)
      (cond ((null x) nil)
            ((null (rest x)) x)
            ((> (second x) (first x)) (cons (first x) (exercise-1d (rest x))))
            (t (exercise-1d (cons (first x) (rest (rest x)))))))
    

    The recursion has two terminal cases: when the list is empty or contains a single element. In both cases the current list is returned.

    After the first two tests we are sure that the list has at least two elements, so we can start to check about the relation between the first two elements.

    If the second element is greater than the first one, then the first is included and the recursion is applied to the rest of the list.

    On the other hand, if the second element is not greater than the first, it is skipped, and the recursion is applied to the list constituted by the first element and all the elements following the second one.