Symmetric difference: Difference between revisions

added scheme example
(Added Kotlin)
(added scheme example)
Line 2,503:
scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim)</lang>
 
=={{header|Scheme}}==
 
=== Pure R7RS ===
 
In pure Scheme, to illustrate implementation of the algorithms:
 
<lang scheme>
(import (scheme base)
(scheme write))
 
;; -- given two sets represented as lists, return (A \ B)
(define (a-without-b a b)
(cond ((null? a)
'())
((member (car a) (cdr a)) ; drop head of a if it's a duplicate
(a-without-b (cdr a) b))
((member (car a) b) ; head of a is in b so drop it
(a-without-b (cdr a) b))
(else ; head of a not in b, so keep it
(cons (car a) (a-without-b (cdr a) b)))))
 
;; -- given two sets represented as lists, return symmetric difference
(define (symmetric-difference a b)
(append (a-without-b a b)
(a-without-b b a)))
 
;; -- test case
(define A '(John Bob Mary Serena))
(define B '(Jim Mary John Bob))
 
(display "A\\B: ") (display (a-without-b A B)) (newline)
(display "B\\A: ") (display (a-without-b B A)) (newline)
(display "Symmetric difference: ") (display (symmetric-difference A B)) (newline)
;; -- extra test as we are using lists
(display "Symmetric difference 2: ")
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</lang>
 
{{out}}
<pre>
A\B: (Serena)
B\A: (Jim)
Symmetric difference: (Serena Jim)
Symmetric difference 2: (Serena Jim)
</pre>
 
=== Using a standard library ===
 
{{libheader|Scheme/SRFIs}}
 
SRFI 1 is one of the most popular SRFIs. It deals with lists, but also has functions treating lists as sets. The lset functions assume the inputs are sets, so we must delete duplicates if this property is not guaranteed on input.
 
<lang scheme>
(import (scheme base)
(scheme write)
(srfi 1))
 
(define (a-without-b a b)
(lset-difference equal?
(delete-duplicates a)
(delete-duplicates b)))
 
(define (symmetric-difference a b)
(lset-xor equal?
(delete-duplicates a)
(delete-duplicates b)))
 
;; -- test case
(define A '(John Bob Mary Serena))
(define B '(Jim Mary John Bob))
 
(display "A\\B: ") (display (a-without-b A B)) (newline)
(display "B\\A: ") (display (a-without-b B A)) (newline)
(display "Symmetric difference: ") (display (symmetric-difference A B)) (newline)
;; -- extra test as we are using lists
(display "Symmetric difference 2: ")
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</lang>
 
 
=={{header|Seed7}}==
342

edits