1

I have two lists, lst1 and lst2. I want to define a function to check if they share some elements. For example:

  • (share-some-elements? '(a b) '(a c)) ⇒ true
  • (share-some-elements? '(a b) '(d e f)) ⇒ false
  • (share-some-elements? '(a b) '(a b d e)) ⇒ true

I have an implementation:

(define (share-some-elements? lst1 lst2)
  (ormap (λ (x) (member x lst1)) lst2))

Which checks if each element in lst2 is a member of lst1, and returns true if any of them is.

My questions are:

  1. What are the other ways of doing this?
  2. How can I extend this to support any number of lists? ie.
    • (all-share-some-elements? '(a b) '(a c) '(a d)) ⇒ true
    • (all-share-some-elements? '(a b) '(a c) '(b d)) ⇒ false
    • (all-share-some-elements? '(a b) '(a c) '(b d a)) ⇒ true

There is a similar question on how to do this on two lists in python: Checking if two lists share at least one element, which doesn't quite answer my questions.

Kisaragi Hiu
  • 202
  • 2
  • 8
  • 2
    You could use [set-intersection](http://docs.racket-lang.org/reference/sets.html#%28def._%28%28lib._racket%2Fset..rkt%29._set-intersect%29%29), which works on multiple lists. If the intersection is not empty, then you have elements in common. – Renzo Dec 20 '17 at 14:43

1 Answers1

2

Both questions can be solved using a single procedure that takes a variable number of arguments. Assuming that at least one list is passed, we have:

(define (all-share-some-elements? . lists)
  (not (null? (apply set-intersect lists))))

Explanation:

  • We apply set-intersect on all the lists.
  • If after the intersection the result is non-empty, then the lists share at least one element in common.

Using your examples:

(all-share-some-elements? '(a b) '(a c))
=> #t
(all-share-some-elements? '(a b) '(d e f))
=> #f
(all-share-some-elements? '(a b) '(a b d e))
=> #t

(all-share-some-elements? '(a b) '(a c) '(a d))
=> #t
(all-share-some-elements? '(a b) '(a c) '(b d))
=> #f
(all-share-some-elements? '(a b) '(a c) '(b d a))
=> #t
Óscar López
  • 232,561
  • 37
  • 312
  • 386