Page 1 of 1

Check if two elements are in order one after another in a li

Posted: Wed Apr 25, 2012 3:31 am
by halastoi
I have a list

Code: Select all

 (SetQ List '(1 j 3 k 4 h 5 n 6 w))
I need to do a function Verify that will verify if the first atom is before the 2nd. I want to verify this:

>

Code: Select all

Verify(3 k)
result should return

> T
// because atom '3' is anywhere before atom 'k'

And in this case :

>

Code: Select all

Verify(h 4)
result should return

> NIL
// because atom 'h' is anywhere after atom '4'

I have to check position of each element and compare positions

Re: Check if two elements are in order one after another in

Posted: Wed Apr 25, 2012 9:14 am
by jecxjo
A simple way is to first step through the list for the first element. If found return the new list from that point. Next search the new sublist for the second element.

Code: Select all

(defun verify (lst a b)
  (labels ((is-found (lst x)
              (cond
                ((null lst) nil)
                ((equal x (car lst)) lst)
                (t (is-found (cdr lst) x)))))
    (let* ((find-a (is-found lst a))
           (find-b (is-found find-a b)))
      (if (and find-a find-b)
        t
        nil))))
(is-found) recursively parses the list and returns the list from the found location down to the end. Next you just apply it for the first atom, then check the new list for the second.

Note: You stated in the subject line "one after another" but then in the description state that the second element could be anywhere. If you need it to be directly after just recursively look for the first element and then check if the cadr is the second.

Code: Select all

(defun verify-next (lst a b)
  (cond
    ((null lst) nil)
    ((and (equal (car lst) a) (equal (cadr lst) b)) t)
    (t (verify-next (cdr lst a b)))))

Re: Check if two elements are in order one after another in

Posted: Thu Apr 26, 2012 1:46 am
by edgar-rft
halastoi wrote:I have to check position of each element and compare positions
Then why don't you just simply compare the POSITIONs?