CLISP : Check if two elements are in order one after another in a list

巧了我就是萌 提交于 2019-12-13 01:18:54

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/10303736/clisp-check-if-two-elements-are-in-order-one-after-another-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!