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

Discussion of Common Lisp

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

Postby halastoi » Wed Apr 25, 2012 3:31 am

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
halastoi
 
Posts: 3
Joined: Wed Apr 25, 2012 12:36 am

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

Postby jecxjo » Wed Apr 25, 2012 9:14 am

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)))))
jecxjo
 
Posts: 3
Joined: Thu Mar 01, 2012 11:29 am

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

Postby edgar-rft » Thu Apr 26, 2012 1:46 am

halastoi wrote:I have to check position of each element and compare positions

Then why don't you just simply compare the POSITIONs?
edgar-rft
 
Posts: 154
Joined: Fri Aug 06, 2010 6:34 am
Location: Germany


Return to Common Lisp

Who is online

Users browsing this forum: Yahoo [Bot] and 2 guests