Symmetric difference: Difference between revisions

m
First example shows symmetric difference w/o using `><` operator
No edit summary
m (First example shows symmetric difference w/o using `><` operator)
 
(42 intermediate revisions by 28 users not shown)
Line 20:
# In the mathematical notation above <code>A \ B</code> gives the set of items in A that are not in B; <code>A ∪ B</code> gives the set of items in both A and B, (their ''union''); and <code>A ∩ B</code> gives the set of items that are in both A and B (their ''intersection'').
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V setA = Set([‘John’, ‘Bob’, ‘Mary’, ‘Serena’])
V setB = Set([‘Jim’, ‘Mary’, ‘John’, ‘Bob’])
print(setA.symmetric_difference(setB))
print(setA - setB)
print(setB - setA)</syntaxhighlight>
 
{{out}}
<pre>
Set([Jim, Serena])
Set([Serena])
Set([Jim])
</pre>
 
=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
 
DEFINE PTR="CARD"
DEFINE NODE_SIZE="6"
TYPE SetNode=[PTR data,prv,nxt]
TYPE SetInfo=[PTR name,begin,end]
 
PROC PrintSet(SetInfo POINTER s)
SetNode POINTER n
CHAR ARRAY a
 
n=s.begin
PrintF("%S=(",s.name)
WHILE n
DO
Print(n.data)
a=n.data
IF n.nxt THEN
Print(", ")
FI
n=n.nxt
OD
PrintE(")")
RETURN
 
PROC CreateSet(SetInfo POINTER s CHAR ARRAY n)
s.name=n
s.begin=0
s.end=0
RETURN
 
PTR FUNC Find(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n
 
n=s.begin
WHILE n
DO
IF SCompare(v,n.data)=0 THEN
RETURN (n)
FI
n=n.nxt
OD
RETURN (0)
 
BYTE FUNC Contains(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n
 
n=Find(s,v)
IF n=0 THEN
RETURN (0)
FI
RETURN (1)
 
PROC Append(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n,tmp
 
IF Contains(s,v) THEN RETURN FI
 
n=Alloc(NODE_SIZE)
n.data=v
n.prv=s.end
n.nxt=0
IF s.end THEN
tmp=s.end tmp.nxt=n
ELSE
s.begin=n
FI
s.end=n
RETURN
 
PROC Remove(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n,prev,next
n=Find(s,v)
IF n=0 THEN RETURN FI
 
prev=n.prv
next=n.nxt
Free(n,NODE_SIZE)
 
IF prev THEN
prev.nxt=next
ELSE
s.begin=next
FI
IF next THEN
next.prv=prev
ELSE
s.end=prev
FI
RETURN
 
PROC AppendSet(SetInfo POINTER s,other)
SetNode POINTER n
 
n=other.begin
WHILE n
DO
Append(s,n.data)
n=n.nxt
OD
RETURN
 
PROC RemoveSet(SetInfo POINTER s,other)
SetNode POINTER n
 
n=other.begin
WHILE n
DO
Remove(s,n.data)
n=n.nxt
OD
RETURN
 
PROC Clear(SetInfo POINTER s)
SetNode POINTER n
 
DO
n=s.begin
IF n=0 THEN RETURN FI
Remove(s,n.data)
OD
RETURN
 
PROC Union(SetInfo POINTER a,b,res)
Clear(res)
AppendSet(res,a)
AppendSet(res,b)
RETURN
 
PROC Difference(SetInfo POINTER a,b,res)
Clear(res)
AppendSet(res,a)
RemoveSet(res,b)
RETURN
 
PROC SymmetricDifference(SetInfo POINTER a,b,res)
SetInfo tmp1,tmp2
CreateSet(tmp1,"")
CreateSet(tmp2,"")
Difference(a,b,tmp1)
Difference(b,a,tmp2)
Union(tmp1,tmp2,res)
Clear(tmp1)
Clear(tmp2)
RETURN
 
PROC TestSymmetricDifference(SetInfo POINTER a,b,res)
SymmetricDifference(a,b,res)
PrintF("%S XOR %S: ",a.name,b.name)
PrintSet(res)
RETURN
 
PROC TestDifference(SetInfo POINTER a,b,res)
Difference(a,b,res)
PrintF("%S-%S: ",a.name,b.name)
PrintSet(res)
RETURN
 
PROC Main()
SetInfo s1,s2,s3
 
Put(125) PutE() ;clear screen
AllocInit(0)
CreateSet(s1,"A")
CreateSet(s2,"B")
CreateSet(s3,"C")
 
Append(s1,"John") Append(s1,"Bob")
Append(s1,"Mary") Append(s1,"Serena")
Append(s2,"Jim") Append(s2,"Mary")
Append(s2,"John") Append(s2,"Bob")
PrintSet(s1) PrintSet(s2)
PutE()
 
TestSymmetricDifference(s1,s2,s3)
TestDifference(s1,s2,s3)
TestDifference(s2,s1,s3)
 
Clear(s1)
Clear(s2)
Clear(s3)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Symmetric_difference.png Screenshot from Atari 8-bit computer]
<pre>
A=(John, Bob, Mary, Serena)
B=(Jim, Mary, John, Bob)
 
A XOR B: C=(Serena, Jim)
A-B: C=(Serena)
B-A: C=(Jim)
</pre>
 
=={{header|Ada}}==
Ada has the lattice operation '''xor''' predefined on Boolean, modular types, 1D arrays, set implementations from the standard library. The provided solution uses arrays:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_XOR is
Line 48 ⟶ 268:
Put ("A - B = "); Put (A and not B); New_Line;
Put ("B - A = "); Put (B and not A); New_Line;
end Test_XOR;</langsyntaxhighlight>
Sample output:
<pre>
Line 57 ⟶ 277:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">show_sdiff(record u, x)
{
record r;
Line 90 ⟶ 310:
 
0;
}</langsyntaxhighlight>
{{out}}
<pre>Jim
Serena</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the associative array implementations in ALGOL_68/prelude.
<syntaxhighlight lang="algol68"># symetric difference using associative arrays to represent the sets #
# include the associative array code for string keys and values #
PR read "aArray.a68" PR
 
# adds the elements of s to the associative array a, #
# the elements will have empty strings for values #
OP // = ( REF AARRAY a, []STRING s )REF AARRAY:
BEGIN
FOR s pos FROM LWB s TO UPB s DO
a // s[ s pos ] := ""
OD;
a
END # // # ;
# returns an AARRAY containing the elements of a that aren't in b #
OP - = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
IF NOT ( b CONTAINSKEY key OF e ) THEN
result // key OF e := value OF e
FI;
e := NEXT a
OD;
result
END # - # ;
# returns an AARRAY containing the elements of a and those of b #
# i.e. in set terms a UNION b #
OP + = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT a
OD;
e := FIRST b;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT b
OD;
result
END # + # ;
# construct the associative arrays for the task #
REF AARRAY a := INIT LOC AARRAY;
REF AARRAY b := INIT LOC AARRAY;
a // []STRING( "John", "Bob", "Mary", "Serena" );
b // []STRING( "Jim", "Mary", "John", "Bob" );
# find and show the symetric difference of a and b #
REF AARRAY c := ( a - b ) + ( b - a );
REF AAELEMENT e := FIRST c;
WHILE e ISNT nil element DO
print( ( " ", key OF e ) );
e := NEXT c
OD;
print( ( newline ) )</syntaxhighlight>
{{out}}
<pre>
Serena Jim
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
matrices (A, B)
"John", "Bob", "Mary", "Serena", enlistar en 'A'
"Jim", "Mary", "John", "Bob", enlistar en 'B'
" A XOR B: {", diferencia simétrica(A,B), "}\n"
" A \ B: {", diferencia(A,B), "}\n"
" B \ A: {", diferencia(B,A), "}\n"
imprimir
terminar
</syntaxhighlight>
{{out}}
<pre>
A XOR B: {Jim,Serena}
A \ B: {Serena}
B \ A: {Jim}
</pre>
 
=={{header|Apex}}==
<langsyntaxhighlight Javalang="java">Set<String> setA = new Set<String>{'John', 'Bob', 'Mary', 'Serena'};
Set<String> setB = new Set<String>{'Jim', 'Mary', 'John', 'Bob'};
 
Line 123 ⟶ 431:
System.debug('Not in set B: ' + notInSetB);
System.debug('Symmetric Difference: ' + symmetricDifference);
System.debug('Symmetric Difference 2: ' + symmetricDifference2);</langsyntaxhighlight>
{{out}}
<pre>Not in set A: {Jim}
Line 130 ⟶ 438:
Symmetric Difference 2: {Jim, Serena}</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">symdiff ← ∪~∩</syntaxhighlight>
{{out}}
<pre> 'John' 'Bob' 'Mary' 'Serena' symdiff 'Jim' 'Mary' 'John' 'Bob'
Serena Jim </pre>
 
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}} (ES6 Functional JS)
<langsyntaxhighlight AppleScriptlang="applescript">-- SYMMETRIC DIFFERENCE -------------------------------------------
 
-- symmetricDifference :: [a] -> [a] -> [a]
Line 244 ⟶ 559:
set sx to nub(xs)
sx & foldl(flipDelete, nub(ys), sx)
end union</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{"Serena", "Jim"}</langsyntaxhighlight>
===Some alternatives===
There are several ways to approach this problem. Vanilla AppleScript doesn't do sets, but the following returns the required results:
<syntaxhighlight lang="applescript">on symmetricDifference(a, b)
set output to {}
repeat 2 times
repeat with thisItem in a
set thisItem to thisItem's contents
tell {thisItem}
if (not ((it is in b) or (it is in output))) then set end of output to thisItem
end tell
end repeat
set {a, b} to {b, a}
end repeat
return output
end symmetricDifference
 
on task()
=={{header|Arturo}}==
set a to {"John", "Serena", "Bob", "Mary", "Serena"}
set b to {"Jim", "Mary", "John", "Jim", "Bob"}
return symmetricDifference(a, b)
end task
 
task()</syntaxhighlight>
<lang arturo>A: #(@John @Bob @Mary @Serena)
B: #(@Jim @Mary @John @Bob)
 
{{output}}
print [symmetricDifference A B]</lang>
<syntaxhighlight lang="applescript">{"Serena", "Jim"}</syntaxhighlight>
 
AppleScriptObjC gives access to the Foundation framework's NSSet classes, whose mutable variety has relevant methods. A symmetricDifference() handler implementing (A ∖ B) ∪ (B ∖ A) might be:
{{out}}
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<pre>#("Jim" "Serena")</pre>
use framework "Foundation"
 
on symmetricDifference(a, b)
set a to current application's class "NSSet"'s setWithArray:(a)
set b to current application's class "NSMutableSet"'s setWithArray:(b)
set output to a's mutableCopy()
tell output to minusSet:(b)
tell b to minusSet:(a)
tell output to unionSet:(b)
return output's allObjects() as list
end symmetricDifference</syntaxhighlight>
 
And for (A ∪ B) ∖ (A ∩ B):
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
on symmetricDifference(a, b)
set a to current application's class "NSSet"'s setWithArray:(a)
set b to current application's class "NSMutableSet"'s setWithArray:(b)
set output to a's mutableCopy()
tell output to unionSet:(b)
tell b to intersectSet:(a)
tell output to minusSet:(b)
return output's allObjects() as list
end symmetricDifference</syntaxhighlight>
 
It's also possible in ASObjC to filter arrays or sets if you're so inclined:
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
on symmetricDifference(a, b)
set unionArray to (current application's class "NSArray"'s arrayWithArray:({a, b}))'s ¬
valueForKeyPath:("@distinctUnionOfArrays.self")
set filter to current application's class "NSPredicate"'s ¬
predicateWithFormat_("!((self IN %@) && (self IN %@))", a, b)
return (unionArray's filteredArrayUsingPredicate:(filter)) as list
end symmetricDifference</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: ["John" "Bob" "Mary" "Serena"]
b: ["Jim" "Mary" "John" "Bob"]
print difference.symmetric a b</syntaxhighlight>
 
{{out}}
 
<pre>Serena Jim</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">setA = John, Bob, Mary, Serena
setB = Jim, Mary, John, Bob
MsgBox,, Singles, % SymmetricDifference(setA, setB)
Line 283 ⟶ 671:
Result .= B_%A_Index% ", "
Return, SubStr(Result, 1, -2)
}</langsyntaxhighlight>
Message boxes show:
<pre>Singles
Line 297 ⟶ 685:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK
BEGIN {
Line 329 ⟶ 717:
printf("\n")
}
</syntaxhighlight>
</lang>
<p>output:</p>
<pre>
Line 339 ⟶ 727:
=={{header|BBC BASIC}}==
Here sets are represented as integers, hence there are a maximum of 32 elements in a set.
<langsyntaxhighlight lang="bbcbasic"> DIM list$(4)
list$() = "Bob", "Jim", "John", "Mary", "Serena"
Line 361 ⟶ 749:
IF set% AND 1 << i% o$ += list$(i%) + ", "
NEXT
= LEFT$(LEFT$(o$))</langsyntaxhighlight>
'''Output:'''
<pre>
Line 375 ⟶ 763:
Walk through the concatenation of the two lists, using backtracking (forced by the ~ operator).
If an element is in both lists, or if the element already is in the accumulated result <code>symdiff</code>, continue. Otherwise add the element to <code>symdiff</code>. When all elements are done and backtracking therefore finally fails, return the contents of <code>symdiff</code>. The flag <code>%</code> in the pattern <code>%@?x</code> ensures that only nontrivial elements (i.e. non-empty strings in this case) are matched. The <code>@</code> flag ensures that at most one string is matched. Together these flags ensure that exactly one element is matched.
<langsyntaxhighlight lang="bracmat">(SymmetricDifference=
A B x symdiff
. !arg:(?A.?B)
Line 390 ⟶ 778:
?
| !symdiff
));</langsyntaxhighlight>
Run:
<langsyntaxhighlight lang="bracmat">SymmetricDifference$(john serena bob mary serena.jim mary john jim bob)</langsyntaxhighlight>
Output:
<syntaxhighlight lang ="bracmat">serena jim</langsyntaxhighlight>
 
=={{header|C}}==
Simple method:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
 
Line 449 ⟶ 837:
 
return 0;
}</langsyntaxhighlight>output
<pre>
A \ B:
Line 462 ⟶ 850:
</pre>
If you prefer something elaborate:
<langsyntaxhighlight lang="c">#include <assert.h>
#include <stdio.h>
#include <string.h>
Line 596 ⟶ 984:
 
return 0;
}</langsyntaxhighlight>
Output
<pre>
Line 605 ⟶ 993:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 632 ⟶ 1,020:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 640 ⟶ 1,028:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <set>
#include <algorithm>
Line 663 ⟶ 1,051:
cout << endl;
return 0;
}</langsyntaxhighlight>
 
Output:
Line 669 ⟶ 1,057:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(use '[clojure.set])
 
(defn symmetric-difference [s1 s2]
(union (difference s1 s2) (difference s2 s1)))
 
(symmetric-difference #{:john :bob :mary :serena} #{:jim :mary :john :bob})</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(set-exclusive-or
(remove-duplicates '(John Serena Bob Mary Serena))
(remove-duplicates '(Jim Mary John Jim Bob)))</langsyntaxhighlight>
Output:
(JIM SERENA)
Line 685 ⟶ 1,073:
=={{header|D}}==
Generic version.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array;
 
struct Set(T) {
Line 711 ⟶ 1,099:
writeln(" B\\A: ", (B - A).items);
writeln("A symdiff B: ", symmetricDifference(A, B).items);
}</langsyntaxhighlight>
{{out}}
<pre> A\B: ["Serena"]
B\A: ["Jim"]
A symdiff B: ["Serena", "Jim"]</pre>
=={{header|Datalog}}==
Implemented using Souffle.
<syntaxhighlight lang="datalog">.decl A(text: symbol)
.decl B(text: symbol)
.decl SymmetricDifference(text: symbol)
.output SymmetricDifference
 
A("this").
A("is").
A("a").
A("test").
B("also").
B("part").
B("of").
B("a").
B("test").
 
SymmetricDifference(x) :- A(x), !B(x).
SymmetricDifference(x) :- B(x), !A(x).</syntaxhighlight>
{{out}}
<pre>
this
is
also
part
of
</pre>
 
=={{header|Delphi}}==
{{libheader| System.Typinfo}}
{{Trans|Pascal}}
Small variation of pascal.
<syntaxhighlight lang="delphi">
PROGRAM Symmetric_difference;
 
uses
System.Typinfo;
 
TYPE
TName = (Bob, Jim, John, Mary, Serena);
TList = SET OF TName;
 
TNameHelper = record helper for TName
FUNCTION ToString(): string;
end;
 
{ TNameHlper }
 
FUNCTION TNameHelper.ToString: string;
BEGIN
Result := GetEnumName(TypeInfo(TName), Ord(self));
END;
 
PROCEDURE Put(txt: String; ResSet: TList);
VAR
I: TName;
 
BEGIN
Write(txt);
FOR I IN ResSet DO
Write(I.ToString, ' ');
WriteLn;
END;
 
VAR
ListA: TList = [John, Bob, Mary, Serena];
ListB: TList = [Jim, Mary, John, Bob];
 
BEGIN
Put('ListA -> ', ListA);
Put('ListB -> ', ListB);
Put('ListA >< ListB -> ', (ListA - ListB) + (ListB - ListA));
Put('ListA - ListB -> ', ListA - ListB);
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</syntaxhighlight>
'''Delphi/Object Pascal actually has a 'Symmetric Difference' operator `> <`: '''
<syntaxhighlight lang="pascal">
program SymmetricDifference;
 
type
charSet = set of Char;
 
var
s1, s2, s3: charSet;
ch: char;
 
begin
s1 := ['a', 'b', 'c', 'd'];
s2 := ['c', 'd', 'e', 'f'];
s3 := s1 >< s2;
 
for ch in s3 do
write(ch, ' ');
writeLn;
end.
</syntaxhighlight>
Output:
<pre>
a b e f
</pre>
 
=={{header|Déjà Vu}}==
Déjà Vu has no real set type. Instead, it uses a dictionary whose keys are the set values. The <code>set{</code> constructor uses <code>true</code> as a dummy value, and sets <code>false</code> as a dummy value.
<langsyntaxhighlight lang="dejavu">set :setA set{ :John :Bob :Mary :Serena }
set :setB set{ :Jim :Mary :John :Bob }
 
Line 732 ⟶ 1,221:
set{
 
!. symmetric-difference setA setB</langsyntaxhighlight>
{{out}}
<pre>set{ :Serena :Jim }</pre>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">? def symmDiff(a, b) { return (a &! b) | (b &! a) }
# value: <symmDiff>
 
? symmDiff(["John", "Bob", "Mary", "Serena"].asSet(), ["Jim", "Mary", "John", "Bob"].asSet())
# value: ["Jim", "Serena"].asSet()</langsyntaxhighlight>
 
=={{header|ElixirEasyLang}}==
<syntaxhighlight>
{{works with|Elixir|1.2}}
<lang elixir>iex(1)> a$[] = ~w[ "John" "Bob" "Mary" "Serena]" |> MapSet.new]
#MapSet<b$[] = [ "BobJim", "JohnMary", "MaryJohn", "SerenaBob" ]>
#
iex(2)> b = ~w[Jim Mary John Bob] |> MapSet.new
for i to 2
#MapSet<["Bob", "Jim", "John", "Mary"]>
for a$ in a$[]
iex(3)> sym_dif = fn(a,b) -> MapSet.difference(MapSet.union(a,b), MapSet.intersection(a,b)) end
for b$ in b$[]
#Function<12.54118792/2 in :erl_eval.expr/5>
if a$ = b$
iex(4)> sym_dif.(a,b)
a$ = ""
#MapSet<["Jim", "Serena"]></lang>
break 1
 
.
=={{header|Erlang}}==
.
<lang erlang>%% Implemented by Arjun Sunel
if a$ <> ""
-module(symdiff).
c$[] &= a$
-export([main/0]).
.
 
.
main() ->
swap a$[] b$[]
SetA = sets:from_list(["John","Bob","Mary","Serena"]),
.
SetB = sets:from_list(["Jim","Mary","John","Bob"]),
print c$[]
AUnionB = sets:union(SetA,SetB),
</syntaxhighlight>
AIntersectionB = sets:intersection(SetA,SetB),
SymmDiffAB = sets:subtract(AUnionB,AIntersectionB),
sets:to_list(SymmDiffAB).
</lang>
 
{{out}}
<pre>["Serena","Jim"]
</pre>
 
=={{header|F Sharp|F#}}==
<lang fsharp>> let a = set ["John"; "Bob"; "Mary"; "Serena"]
let b = set ["Jim"; "Mary"; "John"; "Bob"];;
 
val a : Set<string> = set ["Bob"; "John"; "Mary"; "Serena"]
val b : Set<string> = set ["Bob"; "Jim"; "John"; "Mary"]
 
> (a-b) + (b-a);;
val it : Set<string> = set ["Jim"; "Serena"]</lang>
Or, if you don't like the infix operators:
<lang fsharp>> Set.union (Set.difference a b) (Set.difference b a);;
val it : Set<string> = set ["Jim"; "Serena"]</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">note
<lang Eiffel>note
description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}."
URI: "http://rosettacode.org/wiki/Symmetric_difference"
Line 830 ⟶ 1,299:
end
 
end</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<syntaxhighlight lang="elixir">iex(1)> a = ~w[John Bob Mary Serena] |> MapSet.new
#MapSet<["Bob", "John", "Mary", "Serena"]>
iex(2)> b = ~w[Jim Mary John Bob] |> MapSet.new
#MapSet<["Bob", "Jim", "John", "Mary"]>
iex(3)> sym_dif = fn(a,b) -> MapSet.difference(MapSet.union(a,b), MapSet.intersection(a,b)) end
#Function<12.54118792/2 in :erl_eval.expr/5>
iex(4)> sym_dif.(a,b)
#MapSet<["Jim", "Serena"]></syntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">%% Implemented by Arjun Sunel
-module(symdiff).
-export([main/0]).
 
main() ->
SetA = sets:from_list(["John","Bob","Mary","Serena"]),
SetB = sets:from_list(["Jim","Mary","John","Bob"]),
AUnionB = sets:union(SetA,SetB),
AIntersectionB = sets:intersection(SetA,SetB),
SymmDiffAB = sets:subtract(AUnionB,AIntersectionB),
sets:to_list(SymmDiffAB).
</syntaxhighlight>
 
{{out}}
<pre>["Serena","Jim"]
</pre>
 
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">> let a = set ["John"; "Bob"; "Mary"; "Serena"]
let b = set ["Jim"; "Mary"; "John"; "Bob"];;
 
val a : Set<string> = set ["Bob"; "John"; "Mary"; "Serena"]
val b : Set<string> = set ["Bob"; "Jim"; "John"; "Mary"]
 
> (a-b) + (b-a);;
val it : Set<string> = set ["Jim"; "Serena"]</syntaxhighlight>
Or, if you don't like the infix operators:
<syntaxhighlight lang="fsharp">> Set.union (Set.difference a b) (Set.difference b a);;
val it : Set<string> = set ["Jim"; "Serena"]</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: symmetric-diff ( a b -- c )
[ diff ] [ swap diff ] 2bi append ;
 
{ "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff .</langsyntaxhighlight>
 
=={{header|Forth}}==
GForth 0.7.0 tested.
<langsyntaxhighlight Forthlang="forth">: elm ( n -- ; one cell per set )
[ cell 8 * 1- ] literal umin CREATE 1 swap lshift ,
DOES> ( -- 2^n ) @ ;
Line 863 ⟶ 1,374:
swap -1 xor and cr persons
cr bye
</syntaxhighlight>
</lang>
Output:
<pre>
Line 875 ⟶ 1,386:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Symmetric_difference
implicit none
 
Line 896 ⟶ 1,407:
end do outer2
end program</langsyntaxhighlight>
Output
<pre>
Serena
Jim
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
redim shared as string Result(-1) 'represent our sets as strings;
'this'll do to illustrate the concept
 
sub sym( A() as string, B() as string )
dim as integer ai, bi, ri
dim as boolean add_it
for ai = lbound(A) to ubound(A)
add_it = true
for bi = lbound(B) to ubound(B)
if A(ai) = B(bi) then
add_it=false
exit for 'if item is common to both lists, don't include it
end if
next bi
if add_it then
for ri = 0 to ubound(Result)
if A(ai) = Result(ri) then
add_it=false
exit for
'if item is already in the result, don't include it again
end if
next ri
end if
if add_it then
redim preserve as string Result(0 to ubound(Result)+1)
Result(ubound(Result)) = A(ai)
end if
 
next ai
end sub
 
dim as string A(0 to 3) = {"John", "Bob", "Mary", "Serena"}
dim as string B(0 to 4) = {"Jim", "Mary", "John", "Bob", "Jim"}
'contains a double to show code can handle it
 
sym(A(), B())
sym(B(), A())
 
for i as uinteger = 0 to ubound(Result)
print Result(i)
next i
</syntaxhighlight>
{{out}}<pre>Serena
Jim
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">A = new set["John", "Bob", "Mary", "Serena"]
B = new set["Jim", "Mary", "John", "Bob"]
 
println["Symmetric difference: " + symmetricDifference[A,B]]
println["A - B : " + setDifference[A,B]]
println["B - A : " + setDifference[B,A]]</syntaxhighlight>
{{out}}
<pre>
Symmetric difference: [Jim, Serena]
A - B : [Serena]
B - A : [Jim]
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn SymmetricDifferenceOfSets( setA as CFSetRef, setB as CFSetRef ) as CFSetRef
CFMutableSetRef notInSetA = fn MutableSetWithSet( setB )
MutableSetMinusSet( notInSetA, setA )
CFMutableSetRef notInSetB = fn MutableSetWithSet( setA )
MutableSetMinusSet( notInSetB, setB )
CFMutableSetRef symmetricDifference = fn MutableSetWithSet( notInSetA )
MutableSetUnionSet( symmetricDifference, notInSetB )
end fn = fn SetWithSet( symmetricDifference )
 
CFSetRef set1, set2
 
set1 = fn SetWithObjects( @"John", @"Serena", @"Bob", @"Mary", @"Serena", NULL )
set2 = fn SetWithObjects( @"Jim", @"Mary", @"John", @"Jim", @"Bob", NULL )
 
NSLog( @"Symmetric difference:\n%@", fn SymmetricDifferenceOfSets( set1, set2 ) )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Symmetric difference:
{(
Jim,
Serena
)}
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">SymmetricDifference := function(a, b)
return Union(Difference(a, b), Difference(b, a));
end;
Line 911 ⟶ 1,516:
b := ["Jim", "Mary", "John", "Jim", "Bob"];
SymmetricDifference(a,b);
[ "Jim", "Serena" ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 934 ⟶ 1,539:
}
fmt.Println(sd)
}</langsyntaxhighlight>
Output:
<pre>
Line 940 ⟶ 1,545:
</pre>
Alternatively, the following computes destructively on a. The result is the same.
<langsyntaxhighlight lang="go">func main() {
for e := range b {
delete(a, e)
}
fmt.Println(a)
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def symDiff = { Set s1, Set s2 ->
assert s1 != null
assert s2 != null
(s1 + s2) - (s1.intersect(s2))
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">Set a = ['John', 'Serena', 'Bob', 'Mary', 'Serena']
Set b = ['Jim', 'Mary', 'John', 'Jim', 'Bob']
 
Line 1,047 ⟶ 1,652:
ppm <> csny: ${PC}
ppm <> ppm: ${PP}
"""</langsyntaxhighlight>
 
Output:
Line 1,091 ⟶ 1,696:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Set
 
a = fromList ["John", "Bob", "Mary", "Serena"]
Line 1,098 ⟶ 1,703:
(-|-) :: Ord a => Set a -> Set a -> Set a
x -|- y = (x \\ y) `union` (y \\ x)
-- Equivalently: (x `union` y) \\ (x `intersect` y)</langsyntaxhighlight>
Symmetric difference:
<langsyntaxhighlight lang="haskell">*Main> a -|- b
fromList ["Jim","Serena"]</langsyntaxhighlight>
Individual differences:
<langsyntaxhighlight lang="haskell">*Main> a \\ b
fromList ["Serena"]
 
*Main> b \\ a
fromList ["Jim"]</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">CALL SymmDiff("John,Serena,Bob,Mary,Serena,", "Jim,Mary,John,Jim,Bob,")
CALL SymmDiff("John,Bob,Mary,Serena,", "Jim,Mary,John,Bob,")
 
Line 1,128 ⟶ 1,733:
EDIT(Text=a, Option=1, SortDelDbls=a) ! Option=1: keep case; Serena,
differences = TRIM( differences ) // a
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Set operations are built into Icon/Unicon.
<langsyntaxhighlight Iconlang="icon">procedure main()
 
a := set(["John", "Serena", "Bob", "Mary", "Serena"])
Line 1,150 ⟶ 1,755:
write("}")
return
end</langsyntaxhighlight>
Sample output:
<pre>a = { Serena Mary Bob John }
Line 1,159 ⟶ 1,764:
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> A=: ~.;:'John Serena Bob Mary Serena'
B=: ~. ;:'Jim Mary John Jim Bob'
 
Line 1,169 ⟶ 1,774:
┌──────┬───┐
│Serena│Jim│
└──────┴───┘</langsyntaxhighlight>
To illustrate some of the underlying mechanics used here:
<langsyntaxhighlight lang="j"> A -. B NB. items in A but not in B
┌──────┐
│Serena│
Line 1,182 ⟶ 1,787:
┌────┬──────┬───┬────┐
│John│Serena│Bob│Mary│
└────┴──────┴───┴────┘</langsyntaxhighlight>
Here's an alternative implementation:
<langsyntaxhighlight lang="j"> A (, -. [ -. -.) B
┌──────┬───┐
│Serena│Jim│
└──────┴───┘</langsyntaxhighlight>
Here, <code>(,)</code> contains all items from A and B and <code>([ -. -.)</code> is the idiom for set intersection, and their difference is the symmetric difference. (Note: an individual word in a J sentence may be placed inside a parenthesis with no change in evaluation, and this can also be used for emphasis when a word might get lost.)
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
Line 1,234 ⟶ 1,839:
System.out.println("Symmetric Difference 2: " + symmetricDifference2);
}
}</langsyntaxhighlight>
Output:
<pre>In set A: [Mary, Bob, Serena, John]
Line 1,253 ⟶ 1,858:
 
Uses the Array function <code>unique()</code> defined [[Create a Sequence of unique elements#JavaScript|here]].
<langsyntaxhighlight lang="javascript">// in A but not in B
function relative_complement(A, B) {
return A.filter(function(elem) {return B.indexOf(elem) == -1});
Line 1,268 ⟶ 1,873:
print(a);
print(b);
print(symmetric_difference(a,b));</langsyntaxhighlight>
outputs
<pre>Bob,John,Mary,Serena
Line 1,276 ⟶ 1,881:
'''Clear JavaScript'''
 
<langsyntaxhighlight lang="javascript">function Difference(A,B)
{
var a = A.length, b = B.length, c = 0, C = [];
Line 1,304 ⟶ 1,909:
Difference(B,A); // 'Jim'
SymmetricDifference(A,B); // 'Serena','Jim'
*/</langsyntaxhighlight>
 
===ES6===
====Functional====
By composition of generic functions;
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,372 ⟶ 1,977:
symmetricDifference(a, b)
);
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">["Serena", "Jim"]</langsyntaxhighlight>
====Procedural ====
<syntaxhighlight lang="javascript">
<lang JavaScript>
const symmetricDifference = (...args) => {
let result = new Set();
Line 1,390 ⟶ 1,995:
console.log(symmetricDifference([1, 2, 5], [2, 3, 5], [3, 4, 5]));
 
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">["Jim", "Serena"]
[1, 4, 5]
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 1,401 ⟶ 2,006:
given these assumptions, it is quite efficient. To workaround the
no-null requirement would be tedious but straightforward.
<langsyntaxhighlight lang="jq"># The following implementation of intersection (but not symmetric_difference) assumes that the
# elements of a (and of b) are unique and do not include null:
def intersection(a; b):
Line 1,411 ⟶ 2,016:
(a|unique) as $a | (b|unique) as $b
| (($a + $b) | unique) - (intersection($a;$b));
</syntaxhighlight>
</lang>
 
Example:<langsyntaxhighlight lang="jq">symmetric_difference( [1,2,1,2]; [2,3] )
[1,3]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Built-in function.
<langsyntaxhighlight lang="julia">A = ["John", "Bob", "Mary", "Serena"]
B = ["Jim", "Mary", "John", "Bob"]
@show A B symdiff(A, B)</langsyntaxhighlight>
 
{{out}}
Line 1,429 ⟶ 2,034:
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> A: ?("John";"Bob";"Mary";"Serena")
B: ?("Jim";"Mary";"John";"Bob")
 
Line 1,438 ⟶ 2,043:
(A _dvl B;B _dvl A) / Symmetric difference
("Serena"
"Jim")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 1,454 ⟶ 2,059:
val e = c.union(d)
println("A Δ B = $e")
}</langsyntaxhighlight>
 
{{out}}
Line 1,464 ⟶ 2,069:
A Δ B = [Serena, Jim]
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Symmetric difference - enumerate the items that are in A or B but not both.
 
# # Variables:
#
typeset -a A=( John Bob Mary Serena )
typeset -a B=( Jim Mary John Bob )
 
# # Functions:
#
# # Function _flattenarr(arr, sep) - flatten arr into string by separator sep
#
function _flattenarr {
typeset _arr ; nameref _arr="$1"
typeset _sep ; typeset -L1 _sep="$2"
typeset _buff
typeset _oldIFS=$IFS ; IFS="${_sep}"
 
_buff=${_arr[*]}
IFS="${_oldIFS}"
echo "${_buff}"
}
 
# # Function _notin(_arr1, _arr2) - elements in arr1 and not in arr2
#
function _notin {
typeset _ar1 ; nameref _ar1="$1"
typeset _ar2 ; nameref _ar2="$2"
typeset _i _buff _set ; integer _i
 
_buff=$(_flattenarr _ar2 \|)
for((_i=0; _i<${#_ar1[*]}; _i++)); do
[[ ${_ar1[_i]} != @(${_buff}) ]] && _set+="${_ar1[_i]} "
done
echo ${_set% *}
}
 
######
# main #
######
 
AnB=$(_notin A B) ; echo "A - B = ${AnB}"
BnA=$(_notin B A) ; echo "B - A = ${BnA}"
echo "A xor B = ${AnB} ${BnA}"</syntaxhighlight>
{{out}}<pre>A - B = Serena
B - A = Jim
A xor B = Serena Jim</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">
[
var(
Line 1,491 ⟶ 2,147:
 
]
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to diff :a :b [:acc []]
if empty? :a [output sentence :acc :b]
ifelse member? first :a :b ~
Line 1,505 ⟶ 2,161:
make "b [Jim Mary John Bob]
 
show diff :a :b ; [Serena Jim]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">A = { ["John"] = true, ["Bob"] = true, ["Mary"] = true, ["Serena"] = true }
B = { ["Jim"] = true, ["Mary"] = true, ["John"] = true, ["Bob"] = true }
 
Line 1,526 ⟶ 2,182:
for b_a in pairs(B_A) do
print( b_a )
end</langsyntaxhighlight>
 
Object-oriented approach:
 
<langsyntaxhighlight lang="lua">SetPrototype = {
__index = {
union = function(self, other)
Line 1,585 ⟶ 2,241:
print("Intersection A∩B : " .. A:intersection(B))
print("Difference A\\B : " .. A:difference(B))
print("Difference B\\A : " .. B:difference(A))</langsyntaxhighlight>
 
'''Output:'''
Line 1,600 ⟶ 2,256:
=={{header|Maple}}==
Maple has built-in support for set operations. Assign the sets A and B:
<langsyntaxhighlight Maplelang="maple">A := {John, Bob, Mary, Serena};
B := {Jim, Mary, John, Bob};</langsyntaxhighlight>
Now compute the symmetric difference with the '''symmdiff''' command:
<syntaxhighlight lang Maple="maple">symmdiff(A, B);</langsyntaxhighlight>
{{out}}
{Jim, Serena}
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has built-in support for operations on sets, using its generic symbolic lists. This function finds the entries in each list that are not present in the intersection of the two lists.
<langsyntaxhighlight Mathematicalang="mathematica">SymmetricDifference[x_List,y_List] := Join[Complement[x,Intersection[x,y]],Complement[y,Intersection[x,y]]]</langsyntaxhighlight>
For large lists, some performance improvement could be made by caching the intersection of the two lists to avoid computing it twice:
<langsyntaxhighlight Mathematicalang="mathematica">CachedSymmetricDifference[x_List,y_List] := Module[{intersect=Intersection[x,y]},Join[Complement[x,intersect],Complement[y,intersect]]]</langsyntaxhighlight>
Also, due to Mathematica's symbolic nature, these functions are automatically applicable to lists of any content, such as strings, integers, reals, graphics, or undefined generic symbols (e.g. unassigned variables).
 
=={{header|MATLAB}}==
If you are using a vector of numbers as the sets of which you like to find the symmetric difference, then there are already utilities that operate on these types of sets built into MATLAB. This code will take the symmetric difference of two vectors:
<langsyntaxhighlight MATLABlang="matlab">>> [setdiff([1 2 3],[2 3 4]) setdiff([2 3 4],[1 2 3])]
 
ans =
 
1 4</langsyntaxhighlight>
On the other hand, if you are using cell-arrays as sets, there are no built-in set utilities to operate on those data structures, so you will have to program them yourself. Also, the only way to have a set of strings is to put each string in a cell of a cell array, trying to put them into a vector will cause all of the strings to concatenate.
 
This code will return the symmetric difference of two sets and will take both cell arrays and vectors (as in the above example) as inputs.
 
<langsyntaxhighlight MATLABlang="matlab">function resultantSet = symmetricDifference(set1,set2)
assert( ~xor(iscell(set1),iscell(set2)), 'Both sets must be of the same type, either cells or matricies, but not a combination of the two' );
Line 1,715 ⟶ 2,371:
resultantSet = unique(resultantSet); %Make sure there are not duplicates
end %symmetricDifference</langsyntaxhighlight>
Solution Test:
<langsyntaxhighlight MATLABlang="matlab">>> A = {'John','Bob','Mary','Serena'}
 
A =
Line 1,739 ⟶ 2,395:
ans =
 
1 4 %Correct</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* builtin */
symmdifference({"John", "Bob", "Mary", "Serena"},
{"Jim", "Mary", "John", "Bob"});
{"Jim", "Serena"}</langsyntaxhighlight>
 
=={{header|Mercury}}==
<langsyntaxhighlight lang="mercury">:- module symdiff.
:- interface.
 
Line 1,768 ⟶ 2,424:
print_set(Desc, Set, !IO) :-
to_sorted_list(Set, Elems),
io.format("%11s: %s\n", [s(Desc), s(string(Elems))], !IO).</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
Set = new map
Set["set"] = {}
 
Set.init = function(items)
set = new Set
set.set = {}
for item in items
set.add(item)
end for
return set
end function
 
Set.contains = function(item)
return self.set.hasIndex(item)
end function
 
Set.items = function
return self.set.indexes
end function
 
Set.add = function(item)
self.set[item] = true
end function
 
Set.union = function(other)
result = Set.init
result.set = self.set + other.set
return result
end function
 
Set.difference = function(other)
result = Set.init
for item in self.items
if not other.contains(item) then result.add(item)
end for
return result
end function
 
Set.symmetricDifference = function(other)
diff1 = self.difference(other)
diff2 = other.difference(self)
return diff1.union(diff2)
end function
 
a = ["John", "Serena", "Bob", "Mary", "Serena"]
b = ["Jim", "Mary", "John", "Jim", "Bob"]
 
A1 = Set.init(a)
B1 = Set.init(b)
 
print "A XOR B " + A1.symmetricDifference(B1).items
print "A - B " + A1.difference(B1).items
print "B - A " + B1.difference(A1).items
</syntaxhighlight>
{{out}}
<pre>A XOR B ["Serena", "Jim"]
A - B ["Serena"]
B - A ["Jim"]
</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda>main :: [sys_message]
main = [Stdout (show (symdiff a b) ++ "\n")]
where a = ["John", "Serena", "Bob", "Mary", "Serena"]
b = ["Jim", "Mary", "John", "Jim", "Bob"]
 
symdiff :: [*]->[*]->[*]
symdiff a b = (a' -- b') ++ (b' -- a')
where a' = nub a
b' = nub b
 
nub :: [*]->[*]
nub = f []
where f acc [] = acc
f acc (a:as) = f acc as, if a $in acc
= f (a:acc) as, otherwise
 
in :: *->[*]->bool
in i [] = False
in i (a:as) = a == i \/ i $in as</syntaxhighlight>
{{out}}
<pre>["Serena","Jim"]</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sets
 
var setA = ["John", "Bob", "Mary", "Serena"].toSettoHashSet
var setB = ["Jim", "Mary", "John", "Bob"].toSettoHashSet
echo setA -+- setB # Symmetric difference
echo setA - setB # Difference
echo setB - setA # Difference</langsyntaxhighlight>
Output:
<pre>{Serena, Jim}
Line 1,784 ⟶ 2,525:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main(int argc, const char *argv[]) {
Line 1,813 ⟶ 2,554:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let unique lst =
let f lst x = if List.mem x lst then lst else x::lst in
List.rev (List.fold_left f [] lst)
Line 1,823 ⟶ 2,564:
unique (List.filter (fun v -> not (List.mem v b)) a)
 
let ( -|- ) a b = (b -| a) @ (a -| b)</langsyntaxhighlight>
in the toplevel:
<langsyntaxhighlight lang="ocaml"># let a = [ "John"; "Bob"; "Mary"; "Serena" ]
and b = [ "Jim"; "Mary"; "John"; "Bob" ]
;;
Line 1,838 ⟶ 2,579:
 
# b -| a ;;
- : string list = ["Jim"]</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">a = .set~of("John", "Bob", "Mary", "Serena")
b = .set~of("Jim", "Mary", "John", "Bob")
-- the xor operation is a symmetric difference
do item over a~xor(b)
say item
end</langsyntaxhighlight>
Output:
<pre>
Line 1,855 ⟶ 2,596:
=={{header|Oz}}==
Oz does not have a general set data type. We can implement some basic set operations in terms of list functions and use them to define the symmetric difference:
<langsyntaxhighlight lang="oz">declare
fun {SymDiff A B}
{Union {Diff A B} {Diff B A}}
Line 1,886 ⟶ 2,627:
{Show {SymDiff
{MakeSet [john serena bob mary serena]}
{MakeSet [jim mary john jim bob]}}}</langsyntaxhighlight>
Oz <em>does</em> have a type for finite sets of non-negative integers. This is part of the constraint programming support. For the given task, we could use it like this if we assume numbers instead of names:
<langsyntaxhighlight lang="oz">declare
fun {SymDiff A B}
{FS.union {FS.diff A B} {FS.diff B A}}
Line 1,896 ⟶ 2,637:
B = {FS.value.make [5 3 1 2]}
in
{Show {SymDiff A B}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">sd(u,v)={
my(r=List());
u=vecsort(u,,8);
v=vecsort(v,,8);
for(i=1,#u,if(!setsearch(v,u[i]),listput(r,u[i])));
for(i=1,#v,if(!setsearch(u,v[i]),listput(r,v[i])));
Vec(r)
};
sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"])</syntaxhighlight>
 
=={{header|Pascal}}==
{{works with|FPC 3.0.2}}
<langsyntaxhighlight Pascallang="pascal">PROGRAM Symmetric_difference;
 
TYPE
Line 1,923 ⟶ 2,675:
Put('ListA -> ', ListA);
Put('ListB -> ', ListB);
Put('ListA >< ListB -> ', (ListA ><- ListB) + (ListB - ListA));
Put('ListA - ListB -> ', ListA - ListB);
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</langsyntaxhighlight>
{{out}}
<pre>ListA -> Bob John Mary Serena
Line 1,934 ⟶ 2,686:
ListA - ListB -> Serena
ListB - ListA -> Jim</pre>
'''Object Pascal actually has a 'Symmetric Difference' operator `> <`: '''
<syntaxhighlight lang="pascal">
program SymmetricDifference;
 
type
=={{header|PARI/GP}}==
charSet = set of Char;
<lang parigp>sd(u,v)={
 
my(r=List());
var
u=vecsort(u,,8);
s1, s2, s3: charSet;
v=vecsort(v,,8);
ch: char;
for(i=1,#u,if(!setsearch(v,u[i]),listput(r,u[i])));
 
for(i=1,#v,if(!setsearch(u,v[i]),listput(r,v[i])));
begin
Vec(r)
s1 := ['a', 'b', 'c', 'd'];
};
s2 := ['c', 'd', 'e', 'f'];
sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"])</lang>
s3 := s1 >< s2;
 
for ch in s3 do
write(ch, ' ');
writeLn;
end.
</syntaxhighlight>
Output:
<pre>
a b e f
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub symm_diff {
# two lists passed in as references
my %in_a = map(($_=>1), @{+shift});
Line 1,963 ⟶ 2,729:
 
my ($a, $b, $s) = symm_diff(\@a, \@b);
print "A\\B: @$a\nB\\A: @$b\nSymm: @$s\n";</langsyntaxhighlight>
{{out}}
<pre>A\B: Serena
B\A: Jim
Symm: Serena Jim</pre>
 
=={{header|Perl 6}}==
<lang perl6>my \A = set <John Serena Bob Mary Serena>;
my \B = set <Jim Mary John Jim Bob>;
 
say A ∖ B; # Set subtraction
say B ∖ A; # Set subtraction
say (A ∪ B) ∖ (A ∩ B); # Symmetric difference, via basic set operations
say A ⊖ B; # Symmetric difference, via dedicated operator</lang>
{{out}}
<pre>set(Serena)
set(Jim)
set(Jim, Serena)
set(Jim, Serena)</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function Union(sequence a, sequence b)
<span style="color: #008080;">function</span> <span style="color: #000000;">Union</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
for i=1 to length(a) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if not find(a[i],b) then
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
b = append(b,a[i])
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return b
<span style="color: #008080;">return</span> <span style="color: #000000;">b</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function Difference(sequence a, sequence b)
<span style="color: #008080;">function</span> <span style="color: #000000;">Difference</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
sequence res = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
for i=1 to length(a) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if not find(a[i],b)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
and not find(a[i],res) then
<span style="color: #008080;">and</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
res = append(res,a[i])
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return res
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function Symmetric_Difference(sequence a, sequence b)
<span style="color: #008080;">function</span> <span style="color: #000000;">Symmetric_Difference</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
return Union(Difference(a, b), Difference(b, a))
<span style="color: #008080;">return</span> <span style="color: #000000;">Union</span><span style="color: #0000FF;">(</span><span style="color: #000000;">Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">))</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence a = {"John", "Serena", "Bob", "Mary", "Serena"},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Serena"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bob"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Serena"</span><span style="color: #0000FF;">},</span>
b = {"Jim", "Mary", "John", "Jim", "Bob"}
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Jim"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Jim"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bob"</span><span style="color: #0000FF;">}</span>
?Symmetric_Difference(a,a)
<span style="color: #0000FF;">?</span><span style="color: #000000;">Symmetric_Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
?Symmetric_Difference(a,b)
<span style="color: #0000FF;">?</span><span style="color: #000000;">Symmetric_Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
?Symmetric_Difference(b,a)
<span style="color: #0000FF;">?</span><span style="color: #000000;">Symmetric_Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
?Symmetric_Difference(b,b)</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">Symmetric_Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,021 ⟶ 2,775:
{}
</pre>
You can also use the builtin (which defaults to symmetic differences), though it will crash if you pass it "sets" with duplicate elements.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">include</span> <span style="color: #000000;">sets</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Serena"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bob"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Jim"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bob"</span><span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
Same output as above
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
Line 2,044 ⟶ 2,809:
"\nB \\ A: ", implode(', ', $b_minus_a),
"\nSymmetric difference: ", implode(', ', $symmetric_difference), "\n";
?></langsyntaxhighlight>
This outputs:
<pre>List A: John, Bob, Mary, Serena
Line 2,051 ⟶ 2,816:
B \ A: Jim
Symmetric difference: Serena, Jim</pre>
 
=={{header|Picat}}==
Using the <code>ordset</code> module.
<syntaxhighlight lang="picat">import ordset.
 
go =>
A = ["John", "Serena", "Bob", "Mary", "Serena"].new_ordset(),
B = ["Jim", "Mary", "John", "Jim", "Bob"].new_ordset(),
 
println(symmetric_difference=symmetric_difference(A,B)),
println(symmetric_difference2=symmetric_difference2(A,B)),
 
println(subtractAB=subtract(A,B)),
println(subtractBA=subtract(B,A)),
 
println(union=union(A,B)),
println(intersection=intersection(A,B)),
nl.
 
symmetric_difference(A,B) = union(subtract(A,B), subtract(B,A)).
% variant
symmetric_difference2(A,B) = subtract(union(A,B), intersection(B,A)).</syntaxhighlight>
 
{{out}}
<pre>symmetric_difference = [Jim,Serena]
symmetric_difference2 = [Jim,Serena]
subtractAB = [Serena]
subtractBA = [Jim]
union = [Bob,Jim,John,Mary,Serena]
intersection = [Bob,John,Mary]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de symdiff (A B)
(uniq (conc (diff A B) (diff B A))) )</langsyntaxhighlight>
Output:
<pre>(symdiff '(John Serena Bob Mary Serena) '(Jim Mary John Jim Bob))
Line 2,061 ⟶ 2,856:
=={{header|Pike}}==
The set type in Pike is 'multiset', that is, a value may appear multiple times and the difference operator only removes equal amounts of duplicates.
<langsyntaxhighlight Pikelang="pike">> multiset(string) A = (< "John", "Serena", "Bob", "Mary", "Bob", "Serena" >);
> multiset(string) B = (< "Jim", "Mary", "Mary", "John", "Bob", "Jim" >);
 
> A^B;
Result: (< "Bob", "Serena", "Serena", "Mary", "Jim", "Jim" >)</langsyntaxhighlight>
The <code>^</code> operator treats arrays like multisets.
<langsyntaxhighlight Pikelang="pike">> array(string) A = ({ "John", "Serena", "Bob", "Mary", "Serena", "Bob" });
> array(string) B = ({ "Jim", "Mary", "John", "Jim", "Bob", "Mary" });
> A^B;
Line 2,073 ⟶ 2,868:
 
> Array.uniq((A-B)+(B-A));
Result: ({ "Serena", "Jim" })</langsyntaxhighlight>
Set operations are also possible with mappings. Here the difference operator works as expected:
<langsyntaxhighlight Pikelang="pike">> mapping(string:int) A = ([ "John":1, "Serena":1, "Bob":1, "Mary":1 ]);
> mapping(string:int) B = ([ "Jim":1, "Mary":1, "John":1, "Bob":1 ]);
 
> A^B;
Result: ([ "Jim": 1, "Serena": 1 ])</langsyntaxhighlight>
Lastly, there is a Set class.
<langsyntaxhighlight Pikelang="pike">> ADT.Set A = ADT.Set((< "John", "Serena", "Bob", "Mary", "Serena", "Bob" >));
> ADT.Set B = ADT.Set((< "Jim", "Mary", "John", "Jim", "Bob", "Mary" >));
> (A-B)+(B-A);
Result: ADT.Set({ "Serena", "Jim" })</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* PL/I ***************************************************************
* 17.08.2013 Walter Pachl
**********************************************************************/
Line 2,107 ⟶ 2,902:
End;
End;
End;</langsyntaxhighlight>
Output:
<pre>
Line 2,115 ⟶ 2,910:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$A = @( "John"
"Bob"
"Mary"
Line 2,135 ⟶ 2,930:
# B - A
Compare $A $B | Where SideIndicator -eq "=>" | Select -ExpandProperty InputObject</langsyntaxhighlight>
{{out}}
<pre>InputObject SideIndicator
Line 2,153 ⟶ 2,948:
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<langsyntaxhighlight Prologlang="prolog">sym_diff :-
A = ['John', 'Serena', 'Bob', 'Mary', 'Serena'],
B = ['Jim', 'Mary', 'John', 'Jim', 'Bob'],
Line 2,167 ⟶ 2,962:
format('difference B\\A : ~w~n', [DBA]),
union(DAB, DBA, Diff),
format('symetric difference : ~w~n', [Diff]).</langsyntaxhighlight>
output :
<pre>A : [John,Serena,Bob,Mary,Serena]
Line 2,180 ⟶ 2,975:
=={{header|PureBasic}}==
===Simple approach===
<langsyntaxhighlight PureBasiclang="purebasic">Dim A.s(3)
Dim B.s(3)
 
Line 2,204 ⟶ 2,999:
EndIf
Next a
Next b</langsyntaxhighlight>
===Solution using lists===
<langsyntaxhighlight PureBasiclang="purebasic">DataSection
SetA:
Data.i 4
Line 2,278 ⟶ 3,073:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Set A: John, Bob, Mary, Serena
Line 2,289 ⟶ 3,084:
'''Python 3.x''' and '''Python 2.7''' have syntax for set literals:
 
<langsyntaxhighlight lang="python">>>> setA = {"John", "Bob", "Mary", "Serena"}
>>> setB = {"Jim", "Mary", "John", "Bob"}
>>> setA ^ setB # symmetric difference of A and B
Line 2,300 ⟶ 3,095:
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
>>> setA & setB # elements in both A and B (intersection)
{'Bob', 'John', 'Mary'}</langsyntaxhighlight>
 
Note that the order of set elements is undefined.
Line 2,306 ⟶ 3,101:
Earlier versions of Python:
 
<langsyntaxhighlight lang="python">>>> setA = set(["John", "Bob", "Mary", "Serena"])
>>> setB = set(["Jim", "Mary", "John", "Bob"])
>>> setA ^ setB # symmetric difference of A and B
Line 2,312 ⟶ 3,107:
>>> setA - setB # elements in A that are not in B
set(['Serena'])
>>> # and so on...</langsyntaxhighlight>
 
There is also a method call interface for these operations. In contrast to the operators above, they accept any iterables as arguments not just sets.
 
<langsyntaxhighlight lang="python">>>> setA.symmetric_difference(setB)
{'Jim', 'Serena'}
>>> setA.difference(setB)
Line 2,325 ⟶ 3,120:
{'Jim', 'Mary', 'Serena', 'John', 'Bob'}
>>> setA.intersection(setB)
{'Mary', 'John', 'Bob'}</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ $ "rosetta/bitwisesets.qky" loadfile ] now!
 
( i.e. using the Quackery code for sets at
http://rosettacode.org/wiki/Set#Indexed_Bitmaps )
 
set{ John Bob Mary Serena }set is A ( --> { )
 
set{ Jim Mary John Bob }set is B ( --> { )
 
say "A \ B is " A B difference echoset cr
 
say "B \ A is " B A difference echoset cr
 
say "(A \ B) U (B \ A) is "
A B difference B A difference union echoset cr
 
say "(A U B) \ (A n B) is "
A B union A B intersection difference echoset cr
 
say "Using built-in symmetric difference: "
A B symmdiff echoset cr </syntaxhighlight>
 
{{out}}
 
<pre>A \ B is { Serena }
B \ A is { Jim }
(A \ B) U (B \ A) is { Jim Serena }
(A U B) \ (A n B) is { Jim Serena }
Using built-in symmetric difference: { Jim Serena }
</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">a <- c( "John", "Bob", "Mary", "Serena" )
b <- c( "Jim", "Mary", "John", "Bob" )
c(setdiff(b, a), setdiff(a, b))
Line 2,334 ⟶ 3,162:
a <- c("John", "Serena", "Bob", "Mary", "Serena")
b <- c("Jim", "Mary", "John", "Jim", "Bob")
c(setdiff(b, a), setdiff(a, b)) </langsyntaxhighlight>
In both cases answer is:
<langsyntaxhighlight Rlang="r">[1] "Jim" "Serena"</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(define A (set "John" "Bob" "Mary" "Serena"))
Line 2,348 ⟶ 3,176:
(set-subtract A B)
(set-subtract B A)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my \A = set <John Serena Bob Mary Serena>;
my \B = set <Jim Mary John Jim Bob>;
 
say A ∖ B; # Set subtraction
say B ∖ A; # Set subtraction
say (A ∪ B) ∖ (A ∩ B); # Symmetric difference, via basic set operations
say A ⊖ B; # Symmetric difference, via dedicated operator</syntaxhighlight>
{{out}}
<pre>set(Serena)
set(Jim)
set(Jim, Serena)
set(Jim, Serena)</pre>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">a: [John Serena Bob Mary Serena]
b: [Jim Mary John Jim Bob]
difference a b</langsyntaxhighlight>
Result is
<pre>
Line 2,359 ⟶ 3,202:
</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, John Bob Mary Serena: e.A
, Jim Mary John Bob: e.B
= <Prout <Symdiff (e.A) (e.B)>>;
};
 
Symdiff {
(e.1) (e.2), <Diff (<Set e.1>) (<Set e.2>)>: e.3
, <Diff (<Set e.2>) (<Set e.1>)>: e.4
= <Union (e.3) (e.4)>;
};
 
Set {
= ;
s.1 e.1 s.1 e.2 = <Set e.1 s.1 e.2>;
s.1 e.1 = s.1 <Set e.1>;
};
 
Union {
(e.1) (e.2) = <Set e.1 e.2>;
};
 
Diff {
() (e.1) = ;
(e.1) () = e.1;
(s.1 e.1) (e.2 s.1 e.3) = <Diff (e.1) (e.2 e.3)>;
(s.1 e.1) (e.2) = s.1 <Diff (e.1) (e.2)>;
};</syntaxhighlight>
{{out}}
<pre>Serena Jim</pre>
=={{header|REXX}}==
===version 1===
Line 2,366 ⟶ 3,240:
 
The &nbsp; '''set''' &nbsp; elements may contain any character permitted with a REXX literal, including the literal character itself (expressed as a double literal delimiter), blanks, brackets, commas, and also a &nbsp; ''null'' &nbsp; value.
<langsyntaxhighlight lang="rexx">/*REXX program finds symmetric difference and symmetric AND (between two lists). */
a= '["John", "Serena", "Bob", "Mary", "Serena"]' /*note the duplicate element: Serena */
b= '["Jim", "Mary", "John", "Jim", "Bob"]' /* " " " " Jim */
Line 2,402 ⟶ 3,276:
say /* [↓] SA ≡ symmetric AND. */
SA= "["strip( strip(SA), 'T', ",")']' /*clean up and add brackets [ ] to it.*/
say ' symmetric AND =' SA /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the in-program lists:}}
<pre>
Line 2,415 ⟶ 3,289:
===version 1.5===
This REXX version shows the symmetric difference and symmetric AND between two lists, the lists have items that have imbedded blanks in them as well as some punctuation, and also a ''null'' element.
<langsyntaxhighlight lang="rexx">/*REXX pgm finds symmetric difference and symm. AND (between two lists).*/
a.=0 /*falsify the booleans*/
a= '["Zahn", "Yi", "Stands with a Fist", "", "Hungry Wolf", "Yi"]'
Line 2,421 ⟶ 3,295:
∙</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the in-program lists (which has imbedded blanks):}}
<pre>
Line 2,433 ⟶ 3,307:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 14.12.2013 Walter Pachl a short solution
* 16.12.2013 fix duplicate element problem in input
Line 2,457 ⟶ 3,331:
out: parse Arg e
If wordpos(e,res)=0 Then res=res e
Return</langsyntaxhighlight>
Output:
<pre>Serena Jim</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
alist = []
blist = []
Line 2,492 ⟶ 3,366:
see "b-a :" see nl
see blist2 see nl
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
<code>DIFFL</code> is defined at [[Set#RPL|Set]]
{{works with|Halcyon Calc|4.2.9}}
≪ DUP2 <span style="color:blue>DIFFL</span>
ROT ROT SWAP <span style="color:blue>DIFFL</span> +
≫ ≫ '<span style="color:blue>SYMDIFF</span>' STO
 
{"John" "Bob" "Mary" "Serena"} {"Jim" "Mary" "John" "Bob"} <span style="color:blue>SYMDIFF</span>
{{out}}
<pre>
1: {"Jim" "Serena"}
</pre>
 
=={{header|Ruby}}==
With arrays:
<langsyntaxhighlight lang="ruby">a = ["John", "Serena", "Bob", "Mary", "Serena"]
b = ["Jim", "Mary", "John", "Jim", "Bob"]
# the union minus the intersection:
p sym_diff = (a | b)-(a & b) # => ["Serena", "Jim"]</langsyntaxhighlight>
Class Set has a symmetric difference operator built-in:
<langsyntaxhighlight lang="ruby">require 'set'
a = Set["John", "Serena", "Bob", "Mary", "Serena"] #Set removes duplicates
b = Set["Jim", "Mary", "John", "Jim", "Bob"]
p sym_diff = a ^ b # => #<Set: {"Jim", "Serena"}></langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">
setA$ = "John,Bob,Mary,Serena"
setB$ = "Jim,Mary,John,Bob"
Line 2,527 ⟶ 3,414:
i = i + 1
wend
end function</langsyntaxhighlight>
<pre>
Jim
Serena
Jim,Serena
</pre>
 
 
=={{header|Rust}}==
Both set types in the std-lib -- <b>HashSet</b> and <b>BTreeSet</b> -- implement a symmetric_difference method.
 
<syntaxhighlight lang="rust">use std::collections::HashSet;
 
fn main() {
let a: HashSet<_> = ["John", "Bob", "Mary", "Serena"]
.iter()
.collect();
let b = ["Jim", "Mary", "John", "Bob"]
.iter()
.collect();
 
let diff = a.symmetric_difference(&b);
println!("{:?}", diff);
}
</syntaxhighlight>
 
{{out}}
<pre>
["Serena", "Jim"]
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">scala> val s1 = Set("John", "Serena", "Bob", "Mary", "Serena")
s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary)
 
Line 2,542 ⟶ 3,453:
 
scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim)</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 2,550 ⟶ 3,461:
In pure Scheme, to illustrate implementation of the algorithms:
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write))
Line 2,581 ⟶ 3,492:
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,597 ⟶ 3,508:
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.
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 2,623 ⟶ 3,534:
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</syntaxhighlight>
</lang>
 
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: striSet is set of string;
Line 2,639 ⟶ 3,549:
begin
writeln(setA >< setB);
end func;</langsyntaxhighlight>
 
Output:
Line 2,645 ⟶ 3,555:
{Jim, Serena}
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program symmetric_difference;
A := {"John", "Bob", "Mary", "Serena"};
B := {"Jim", "Mary", "John", "Bob"};
 
print("A - B:", A - B);
print("B - A:", B - A);
print("Symmetric difference:", (A-B) + (B-A));
end program;</syntaxhighlight>
{{out}}
<pre>A - B: {Serena}
B - A: {Jim}
Symmetric difference: {Jim Serena}</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var a = ["John", "Serena", "Bob", "Mary", "Serena"];
var b = ["Jim", "Mary", "John", "Jim", "Bob"];
a ^ b -> unique.dump.say;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,656 ⟶ 3,580:
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">|A B|
A := Set new.
B := Set new.
Line 2,662 ⟶ 3,586:
B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ).
 
( (A - B) + (B - A) ) displayNl.</langsyntaxhighlight>
Output is
<pre>
Line 2,669 ⟶ 3,593:
 
=={{header|SQL}}/{{header|PostgreSQL}}==
<langsyntaxhighlight SQLlang="sql">create or replace function arrxor(anyarray,anyarray) returns anyarray as $$
select ARRAY(
(
Line 2,682 ⟶ 3,606:
)
)
$$ language sql strict immutable;</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="sql">select arrxor('{this,is,a,test}'::text[],'{also,part,of,a,test}'::text[]);</langsyntaxhighlight>
Output:
<pre>
Line 2,695 ⟶ 3,619:
Swift's <code>Set</code> type supports difference as well as symmetric difference operators.
{{works with|Swift|1.2+}}
<langsyntaxhighlight lang="swift">let setA : Set<String> = ["John", "Bob", "Mary", "Serena"]
let setB : Set<String> = ["Jim", "Mary", "John", "Bob"]
println(setA.exclusiveOr(setB)) // symmetric difference of A and B
println(setA.subtract(setB)) // elements in A that are not in B</langsyntaxhighlight>
{{out}}
<pre>
Line 2,708 ⟶ 3,632:
It's common to represent sets as an unordered list of elements. (It is also the most efficient representation.) The <code>struct::set</code> package contains operations for working on such sets-as-lists.
{{tcllib|struct::set}}
<langsyntaxhighlight lang="tcl">package require struct::set
 
set A {John Bob Mary Serena}
Line 2,722 ⟶ 3,646:
 
# Of course, the library already has this operation directly...
puts "Direct Check: [struct::set symdiff $A $B]"</langsyntaxhighlight>
Produces this output:<pre>
A\B = Serena
Line 2,731 ⟶ 3,655:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
a="John'Bob'Mary'Serena"
b="Jim'Mary'John'Bob"
Line 2,752 ⟶ 3,676:
LOOP n=names,v=val
PRINT n," in: ",v
ENDLOOP</langsyntaxhighlight>
Output:
<pre>
Line 2,766 ⟶ 3,690:
=={{header|UNIX Shell}}==
{{works with|Bash}}
<langsyntaxhighlight lang="bash">uniq() {
u=("$@")
for ((i=0;i<${#u[@]};i++)); do
Line 2,808 ⟶ 3,732:
echo "A - B = ${ab[@]}"
echo "B - A = ${ba[@]}"
echo "Symmetric difference = ${sd[@]}"</langsyntaxhighlight>
Output:
<pre>Set A = John Serena Bob Mary Serena
Line 2,819 ⟶ 3,743:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">a = <'John','Bob','Mary','Serena'>
b = <'Jim','Mary','John','Bob'>
 
Line 2,831 ⟶ 3,755:
'a not b': ~&j/a b,
'b not a': ~&j/b a,
'symmetric difference': ~&jrljTs/a b></langsyntaxhighlight>
output:
<pre><
Line 2,839 ⟶ 3,763:
'b not a': <'Jim'>,
'symmetric difference': <'Jim','Serena'>></pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
const
(
alist = ["john", "bob", "mary", "serena"]
blist = ["jim", "mary", "john", "bob"]
)
 
fn main() {
mut rlist := []string{}
for elem in alist {
if blist.any(it == elem) == false {
println("a - b = $elem")
rlist << elem
}
}
for elem in blist {
if alist.any(it == elem) == false {
println("b - a = $elem")
rlist << elem
}
}
println("symmetric difference: $rlist")
}
</syntaxhighlight>
 
{{out}}
<pre>
a - b = serena
b - a = jim
symmetric difference: ['serena', 'jim']
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-set}}
<syntaxhighlight lang="wren">import "./set" for Set
 
var symmetricDifference = Fn.new { |a, b| a.except(b).union(b.except(a)) }
 
var a = Set.new(["John", "Bob", "Mary", "Serena"])
var b = Set.new(["Jim", "Mary", "John", "Bob"])
System.print("A = %(a)")
System.print("B = %(b)")
System.print("A - B = %(a.except(b))")
System.print("B - A = %(b.except(a))")
System.print("A △ B = %(symmetricDifference.call(a, b))")</syntaxhighlight>
 
{{out}}
<pre>
A = <Serena, Bob, Mary, John>
B = <Jim, Bob, Mary, John>
A - B = <Serena>
B - A = <Jim>
A △ B = <Serena, Jim>
</pre>
 
=={{header|XPL0}}==
An integer in XPL0 can represent a set of up to 32 elements, and bitwise Boolean
operations can represent union, intersection, and difference.
 
<syntaxhighlight lang="xpl0">def John, Bob, Mary, Serena, Jim; \enumerate set items (0..4)
 
proc SetOut(S); \Output the elements in set
int S;
int Name, I;
[Name:= ["John", "Bob", "Mary", "Serena", "Jim"];
for I:= 0 to 31 do
if S & 1<<I then
[Text(0, Name(I)); ChOut(0, ^ )];
CrLf(0);
];
 
int A, B;
[A:= 1<<John ! 1<<Bob ! 1<<Mary ! 1<<Serena;
B:= 1<<Jim ! 1<<Mary ! 1<<John ! 1<<Bob;
Text(0, "A xor B = "); SetOut(A | B);
Text(0, "A\B = "); SetOut(A & ~B);
Text(0, "B\A = "); SetOut(B & ~A);
Text(0, "A\B U B\A = "); SetOut(A&~B ! B&~A);
]</syntaxhighlight>
 
{{out}}
<pre>
A xor B = Serena Jim
A\B = Serena
B\A = Jim
A\B U B\A = Serena Jim
</pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">lista1$ = "John Serena Bob Mary Serena"
lista2$ = "Jim Mary John Jim Bob"
 
Line 2,885 ⟶ 3,898:
wend
end sub
</syntaxhighlight>
</lang>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn setCommon(list1,list2){ list1.filter(list2.holds); }
fcn sdiff(list1,list2)
{ list1.extend(list2).copy().removeEach(setCommon(list1,list2)) }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">a:=T("John","Bob","Mary","Serena");
b:=T("Jim","Mary","John","Bob");
sdiff(a,b).println();</langsyntaxhighlight>
To deal with duplicates, use [[Remove duplicate elements#zkl]]:
<langsyntaxhighlight lang="zkl">a:=T("John", "Serena", "Bob", "Mary", "Serena");
b:=T("Jim", "Mary", "John", "Jim", "Bob");
sdiff(a,b) : Utils.Helpers.listUnique(_).println();</langsyntaxhighlight>
{{out}}
<pre>
57

edits