Jump to content

Symmetric difference: Difference between revisions

m
sntax highlighting fixup automation
m (sntax highlighting fixup automation)
Line 24:
{{trans|Python}}
 
<langsyntaxhighlight 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)</langsyntaxhighlight>
 
{{out}}
Line 40:
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}}
<langsyntaxhighlight Actionlang="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!
Line 228:
Clear(s2)
Clear(s3)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Symmetric_difference.png Screenshot from Atari 8-bit computer]
Line 242:
=={{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 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 277:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">show_sdiff(record u, x)
{
record r;
Line 310:
 
0;
}</langsyntaxhighlight>
{{out}}
<pre>Jim
Line 318:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the associative array implementations in ALGOL_68/prelude.
<langsyntaxhighlight 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
Line 373:
e := NEXT c
OD;
print( ( newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 380:
 
=={{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 407:
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 416:
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang ="apl">symdiff ← ∪~∩</langsyntaxhighlight>
{{out}}
<pre> 'John' 'Bob' 'Mary' 'Serena' symdiff 'Jim' 'Mary' 'John' 'Bob'
Line 423:
=={{header|AppleScript}}==
{{Trans|JavaScript}} (ES6 Functional JS)
<langsyntaxhighlight AppleScriptlang="applescript">-- SYMMETRIC DIFFERENCE -------------------------------------------
 
-- symmetricDifference :: [a] -> [a] -> [a]
Line 534:
set sx to nub(xs)
sx & foldl(flipDelete, nub(ys), sx)
end union</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{"Serena", "Jim"}</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">a: ["John" "Bob" "Mary" "Serena"]
b: ["Jim" "Mary" "John" "Bob"]
print difference.symmetric a b</langsyntaxhighlight>
 
{{out}}
Line 549:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">setA = John, Bob, Mary, Serena
setB = Jim, Mary, John, Bob
MsgBox,, Singles, % SymmetricDifference(setA, setB)
Line 571:
Result .= B_%A_Index% ", "
Return, SubStr(Result, 1, -2)
}</langsyntaxhighlight>
Message boxes show:
<pre>Singles
Line 585:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK
BEGIN {
Line 617:
printf("\n")
}
</syntaxhighlight>
</lang>
<p>output:</p>
<pre>
Line 627:
=={{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 649:
IF set% AND 1 << i% o$ += list$(i%) + ", "
NEXT
= LEFT$(LEFT$(o$))</langsyntaxhighlight>
'''Output:'''
<pre>
Line 663:
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 678:
?
| !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 737:
 
return 0;
}</langsyntaxhighlight>output
<pre>
A \ B:
Line 750:
</pre>
If you prefer something elaborate:
<langsyntaxhighlight lang="c">#include <assert.h>
#include <stdio.h>
#include <string.h>
Line 884:
 
return 0;
}</langsyntaxhighlight>
Output
<pre>
Line 893:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 920:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 928:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <set>
#include <algorithm>
Line 951:
cout << endl;
return 0;
}</langsyntaxhighlight>
 
Output:
Line 957:
 
=={{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 973:
=={{header|D}}==
Generic version.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array;
 
struct Set(T) {
Line 999:
writeln(" B\\A: ", (B - A).items);
writeln("A symdiff B: ", symmetricDifference(A, B).items);
}</langsyntaxhighlight>
{{out}}
<pre> A\B: ["Serena"]
Line 1,006:
=={{header|Datalog}}==
Implemented using Souffle.
<langsyntaxhighlight lang="datalog">.decl A(text: symbol)
.decl B(text: symbol)
.decl SymmetricDifference(text: symbol)
Line 1,022:
 
SymmetricDifference(x) :- A(x), !B(x).
SymmetricDifference(x) :- B(x), !A(x).</langsyntaxhighlight>
{{out}}
<pre>
Line 1,036:
{{Trans|Pascal}}
Small variation of pascal.
<syntaxhighlight lang="delphi">
<lang Delphi>
PROGRAM Symmetric_difference;
 
Line 1,079:
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</langsyntaxhighlight>
 
=={{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 1,096:
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|Eiffel}}==
<syntaxhighlight lang="eiffel">note
<lang Eiffel>note
description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}."
URI: "http://rosettacode.org/wiki/Symmetric_difference"
Line 1,152:
end
 
end</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<langsyntaxhighlight 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
Line 1,163:
#Function<12.54118792/2 in :erl_eval.expr/5>
iex(4)> sym_dif.(a,b)
#MapSet<["Jim", "Serena"]></langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%% Implemented by Arjun Sunel
-module(symdiff).
-export([main/0]).
Line 1,177:
SymmDiffAB = sets:subtract(AUnionB,AIntersectionB),
sets:to_list(SymmDiffAB).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,184:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">> let a = set ["John"; "Bob"; "Mary"; "Serena"]
let b = set ["Jim"; "Mary"; "John"; "Bob"];;
 
Line 1,191:
 
> (a-b) + (b-a);;
val it : Set<string> = set ["Jim"; "Serena"]</langsyntaxhighlight>
Or, if you don't like the infix operators:
<langsyntaxhighlight lang="fsharp">> Set.union (Set.difference a b) (Set.difference b a);;
val it : Set<string> = set ["Jim"; "Serena"]</langsyntaxhighlight>
 
=={{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 1,227:
swap -1 xor and cr persons
cr bye
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,239:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Symmetric_difference
implicit none
 
Line 1,260:
end do outer2
end program</langsyntaxhighlight>
Output
<pre>
Line 1,268:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
redim shared as string Result(-1) 'represent our sets as strings;
'this'll do to illustrate the concept
Line 1,311:
print Result(i)
next i
</syntaxhighlight>
</lang>
{{out}}<pre>Serena
Jim
Line 1,317:
 
=={{header|Frink}}==
<langsyntaxhighlight 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]]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,331:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">SymmetricDifference := function(a, b)
return Union(Difference(a, b), Difference(b, a));
end;
Line 1,338:
b := ["Jim", "Mary", "John", "Jim", "Bob"];
SymmetricDifference(a,b);
[ "Jim", "Serena" ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,361:
}
fmt.Println(sd)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,367:
</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,474:
ppm <> csny: ${PC}
ppm <> ppm: ${PP}
"""</langsyntaxhighlight>
 
Output:
Line 1,518:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Set
 
a = fromList ["John", "Bob", "Mary", "Serena"]
Line 1,525:
(-|-) :: 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,555:
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,577:
write("}")
return
end</langsyntaxhighlight>
Sample output:
<pre>a = { Serena Mary Bob John }
Line 1,586:
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> A=: ~.;:'John Serena Bob Mary Serena'
B=: ~. ;:'Jim Mary John Jim Bob'
 
Line 1,596:
┌──────┬───┐
│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,609:
┌────┬──────┬───┬────┐
│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,661:
System.out.println("Symmetric Difference 2: " + symmetricDifference2);
}
}</langsyntaxhighlight>
Output:
<pre>In set A: [Mary, Bob, Serena, John]
Line 1,680:
 
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,695:
print(a);
print(b);
print(symmetric_difference(a,b));</langsyntaxhighlight>
outputs
<pre>Bob,John,Mary,Serena
Line 1,703:
'''Clear JavaScript'''
 
<langsyntaxhighlight lang="javascript">function Difference(A,B)
{
var a = A.length, b = B.length, c = 0, C = [];
Line 1,731:
Difference(B,A); // 'Jim'
SymmetricDifference(A,B); // 'Serena','Jim'
*/</langsyntaxhighlight>
 
===ES6===
====Functional====
By composition of generic functions;
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,799:
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,817:
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,828:
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,838:
(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,856:
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> A: ?("John";"Bob";"Mary";"Serena")
B: ?("Jim";"Mary";"John";"Bob")
 
Line 1,865:
(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,881:
val e = c.union(d)
println("A Δ B = $e")
}</langsyntaxhighlight>
 
{{out}}
Line 1,893:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 1,938:
AnB=$(_notin A B) ; echo "A - B = ${AnB}"
BnA=$(_notin B A) ; echo "B - A = ${BnA}"
echo "A xor B = ${AnB} ${BnA}"</langsyntaxhighlight>
{{out}}<pre>A - B = Serena
B - A = Jim
Line 1,944:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">
[
var(
Line 1,969:
 
]
</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,983:
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 2,004:
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 2,063:
print("Intersection A∩B : " .. A:intersection(B))
print("Difference A\\B : " .. A:difference(B))
print("Difference B\\A : " .. B:difference(A))</langsyntaxhighlight>
 
'''Output:'''
Line 2,078:
=={{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}
Line 2,087:
=={{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 2,193:
resultantSet = unique(resultantSet); %Make sure there are not duplicates
end %symmetricDifference</langsyntaxhighlight>
Solution Test:
<langsyntaxhighlight MATLABlang="matlab">>> A = {'John','Bob','Mary','Serena'}
 
A =
Line 2,217:
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 2,246:
print_set(Desc, Set, !IO) :-
to_sorted_list(Set, Elems),
io.format("%11s: %s\n", [s(Desc), s(string(Elems))], !IO).</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sets
 
var setA = ["John", "Bob", "Mary", "Serena"].toHashSet
Line 2,255:
echo setA -+- setB # Symmetric difference
echo setA - setB # Difference
echo setB - setA # Difference</langsyntaxhighlight>
Output:
<pre>{Serena, Jim}
Line 2,262:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main(int argc, const char *argv[]) {
Line 2,291:
}
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 2,301:
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 2,316:
 
# 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 2,333:
=={{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 2,364:
{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 2,374:
B = {FS.value.make [5 3 1 2]}
in
{Show {SymDiff A B}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">sd(u,v)={
my(r=List());
u=vecsort(u,,8);
Line 2,385:
Vec(r)
};
sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"])</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|FPC 3.0.2}}
<langsyntaxhighlight Pascallang="pascal">PROGRAM Symmetric_difference;
 
TYPE
Line 2,416:
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</langsyntaxhighlight>
{{out}}
<pre>ListA -> Bob John Mary Serena
Line 2,425:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub symm_diff {
# two lists passed in as references
my %in_a = map(($_=>1), @{+shift});
Line 2,441:
 
my ($a, $b, $s) = symm_diff(\@a, \@b);
print "A\\B: @$a\nB\\A: @$b\nSymm: @$s\n";</langsyntaxhighlight>
{{out}}
<pre>A\B: Serena
Line 2,448:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<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>
Line 2,479:
<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>
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 2,488:
</pre>
You can also use the builtin (which defaults to symmetic differences), though it will crash if you pass it "sets" with duplicate elements.
<!--<langsyntaxhighlight Phixlang="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>
Line 2,496:
<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>
<!--</langsyntaxhighlight>-->
Same output as above
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
Line 2,521:
"\nB \\ A: ", implode(', ', $b_minus_a),
"\nSymmetric difference: ", implode(', ', $symmetric_difference), "\n";
?></langsyntaxhighlight>
This outputs:
<pre>List A: John, Bob, Mary, Serena
Line 2,531:
=={{header|Picat}}==
Using the <code>ordset</code> module.
<langsyntaxhighlight Picatlang="picat">import ordset.
 
go =>
Line 2,549:
symmetric_difference(A,B) = union(subtract(A,B), subtract(B,A)).
% variant
symmetric_difference2(A,B) = subtract(union(A,B), intersection(B,A)).</langsyntaxhighlight>
 
{{out}}
Line 2,560:
 
=={{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,568:
=={{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,580:
 
> 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,614:
End;
End;
End;</langsyntaxhighlight>
Output:
<pre>
Line 2,622:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$A = @( "John"
"Bob"
"Mary"
Line 2,642:
# B - A
Compare $A $B | Where SideIndicator -eq "=>" | Select -ExpandProperty InputObject</langsyntaxhighlight>
{{out}}
<pre>InputObject SideIndicator
Line 2,660:
=={{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,674:
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,687:
=={{header|PureBasic}}==
===Simple approach===
<langsyntaxhighlight PureBasiclang="purebasic">Dim A.s(3)
Dim B.s(3)
 
Line 2,711:
EndIf
Next a
Next b</langsyntaxhighlight>
===Solution using lists===
<langsyntaxhighlight PureBasiclang="purebasic">DataSection
SetA:
Data.i 4
Line 2,785:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Set A: John, Bob, Mary, Serena
Line 2,796:
'''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,807:
{'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,813:
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,819:
>>> 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,832:
{'Jim', 'Mary', 'Serena', 'John', 'Bob'}
>>> setA.intersection(setB)
{'Mary', 'John', 'Bob'}</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "rosetta/bitwisesets.qky" loadfile ] now!
 
( i.e. using the Quackery code for sets at
Line 2,856:
 
say "Using built-in symmetric difference: "
A B symmdiff echoset cr </langsyntaxhighlight>
 
{{out}}
Line 2,868:
 
=={{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,874:
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,888:
(set-subtract A B)
(set-subtract B A)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my \A = set <John Serena Bob Mary Serena>;
my \B = set <Jim Mary John Jim Bob>;
 
Line 2,898:
say B ∖ A; # Set subtraction
say (A ∪ B) ∖ (A ∩ B); # Symmetric difference, via basic set operations
say A ⊖ B; # Symmetric difference, via dedicated operator</langsyntaxhighlight>
{{out}}
<pre>set(Serena)
Line 2,906:
 
=={{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,921:
 
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,957:
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,970:
===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,976:
∙</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the in-program lists (which has imbedded blanks):}}
<pre>
Line 2,988:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 14.12.2013 Walter Pachl a short solution
* 16.12.2013 fix duplicate element problem in input
Line 3,012:
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 3,047:
see "b-a :" see nl
see blist2 see nl
</syntaxhighlight>
</lang>
 
=={{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 3,082:
i = i + 1
wend
end function</langsyntaxhighlight>
<pre>
Jim
Line 3,093:
Both set types in the std-lib -- <b>HashSet</b> and <b>BTreeSet</b> -- implement a symmetric_difference method.
 
<langsyntaxhighlight lang="rust">use std::collections::HashSet;
 
fn main() {
Line 3,106:
println!("{:?}", diff);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,114:
 
=={{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 3,121:
 
scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim)</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 3,129:
In pure Scheme, to illustrate implementation of the algorithms:
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write))
Line 3,160:
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,176:
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 3,202:
(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 3,217:
begin
writeln(setA >< setB);
end func;</langsyntaxhighlight>
 
Output:
Line 3,225:
 
=={{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 3,234:
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">|A B|
A := Set new.
B := Set new.
Line 3,240:
B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ).
 
( (A - B) + (B - A) ) displayNl.</langsyntaxhighlight>
Output is
<pre>
Line 3,247:
 
=={{header|SQL}}/{{header|PostgreSQL}}==
<langsyntaxhighlight SQLlang="sql">create or replace function arrxor(anyarray,anyarray) returns anyarray as $$
select ARRAY(
(
Line 3,260:
)
)
$$ 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 3,273:
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 3,286:
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 3,300:
 
# 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 3,309:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
a="John'Bob'Mary'Serena"
b="Jim'Mary'John'Bob"
Line 3,330:
LOOP n=names,v=val
PRINT n," in: ",v
ENDLOOP</langsyntaxhighlight>
Output:
<pre>
Line 3,344:
=={{header|UNIX Shell}}==
{{works with|Bash}}
<langsyntaxhighlight lang="bash">uniq() {
u=("$@")
for ((i=0;i<${#u[@]};i++)); do
Line 3,386:
echo "A - B = ${ab[@]}"
echo "B - A = ${ba[@]}"
echo "Symmetric difference = ${sd[@]}"</langsyntaxhighlight>
Output:
<pre>Set A = John Serena Bob Mary Serena
Line 3,397:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">a = <'John','Bob','Mary','Serena'>
b = <'Jim','Mary','John','Bob'>
 
Line 3,409:
'a not b': ~&j/a b,
'b not a': ~&j/b a,
'symmetric difference': ~&jrljTs/a b></langsyntaxhighlight>
output:
<pre><
Line 3,420:
=={{header|Wren}}==
{{libheader|Wren-set}}
<langsyntaxhighlight lang="ecmascript">import "/set" for Set
 
var symmetricDifference = Fn.new { |a, b| a.except(b).union(b.except(a)) }
Line 3,430:
System.print("A - B = %(a.except(b))")
System.print("B - A = %(b.except(a))")
System.print("A △ B = %(symmetricDifference.call(a, b))")</langsyntaxhighlight>
 
{{out}}
Line 3,445:
operations can represent union, intersection, and difference.
 
<langsyntaxhighlight XPL0lang="xpl0">def John, Bob, Mary, Serena, Jim; \enumerate set items (0..4)
 
proc SetOut(S); \Output the elements in set
Line 3,464:
Text(0, "B\A = "); SetOut(B & ~A);
Text(0, "A\B U B\A = "); SetOut(A&~B ! B&~A);
]</langsyntaxhighlight>
 
{{out}}
Line 3,475:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">lista1$ = "John Serena Bob Mary Serena"
lista2$ = "Jim Mary John Jim Bob"
 
Line 3,519:
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>
10,339

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.