This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

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

3 posts · 2366 views

I have a list
 (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:

>
Verify(3 k)
result should return

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

And in this case :

>
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

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.
(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.
(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

halastoi wrote:I have to check position of each element and compare positions
Then why don't you just simply compare the POSITIONs?