I have a list
L=(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 before atom 'k'
And in this case :
>Verify(h 4)
result should return
> NIL
// because atom 'h' is after atom '4'
I have to check position of each element and compare positions
What dialect of Lisp are you using? Here are some pointers on how to derive a solution, fill-in the blanks:
(define (verify lst a b)
; what happens if there's only one element left in the list?
(cond ((null? (cdr lst)) <???>)
; how do we check if the current element is equal to the `a` parameter
; and the next element is equal to the `b` parameter?
(<???> T)
; how do we continue traversing the rest of the list?
(else (verify <???> a b))))
;;; tests
(define lst '(1 j 3 k 4 h 5 n 6 w))
(verify lst 3 'k)
> T
(verify lst 'h '4)
> F
This is a one-liner in Common Lisp:
(defun verify (list a b)
(member b (member a list)))
Note it does not return T or NIL, but a "generalized boolean" (any value other than nil
is true). This is a fundamental concept in Lisp:
http://clhs.lisp.se/Body/26_glo_g.htm#generalized_boolean
This also assumes that "before" means "anywhere before". Your homework problem looks like it may be about "immediately before". It should be easy to modify.