Skeen
Skeen

Reputation: 4722

Scheme matching elements

I'm currently playing a bit around with scheme, and I've been stuck for quite a while trying to figure out how to implement a test, that checks if any element in 'xs' is also stored in 'l'.

That is the mathematical function '\in', just for each element in the list xs.

Upvotes: 1

Views: 160

Answers (2)

Ross Larson
Ross Larson

Reputation: 2437

Do you want to write it yourself for practice, or do you just need the functionality?

If you just want the functionality then use the answer by larsmans (I have never used that, but it looks good to me).

To implement try the following (disclaimer: I have not tested this)


(define has-intersect?
      (lambda (xs l)
           (cond
             [(null? xs) #f]
             [(member? (car xs) l) #t]
             [else (has-intersect? (cdr xs) l)])))

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363597

In mathematical terms, you're checking whether the intersection of two lists/sets is non-empty. If you have an SRFI-1 library, this is trivial:

(not (null? (lset-intersection l xs)))

An implementation of SRFI-1 can be found in SLIB.

(Disclaimer: I'm a former SLIB contributor.)

Upvotes: 1

Related Questions