Set: Difference between revisions

101,290 bytes added ,  3 months ago
m
(Added AppleScript.)
m (→‎{{header|Wren}}: Minor tidy)
 
(31 intermediate revisions by 21 users not shown)
Line 31:
{{Template:See also lists}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V s1 = Set([1, 2, 3, 4])
V s2 = Set([3, 4, 5, 6])
print(s1.union(s2))
print(s1.intersection(s2))
print(s1.difference(s2))
print(s1 < s1)
print(Set([3, 1]) < s1)
print(s1 <= s1)
print(Set([3, 1]) <= s1)
print(Set([3, 2, 4, 1]) == s1)
print(s1 == s2)
print(2 C s1)
print(10 !C s1)
print(Set([1, 2, 3, 4, 5]) > s1)
print(Set([1, 2, 3, 4]) > s1)
print(Set([1, 2, 3, 4]) >= s1)
print(s1.symmetric_difference(s2))
print(s1.len)
s1.add(99)
print(s1)
s1.discard(99)
print(s1)</syntaxhighlight>
 
{{out}}
<pre>
Set([1, 2, 3, 4, 5, 6])
Set([3, 4])
Set([1, 2])
0B
1B
1B
1B
1B
0B
1B
1B
1B
0B
1B
Set([1, 2, 5, 6])
4
Set([1, 2, 3, 4, 99])
Set([1, 2, 3, 4])
</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 Intersection(SetInfo POINTER a,b,res)
SetNode POINTER n
 
Clear(res)
n=a.begin
WHILE n
DO
IF Contains(b,n.data) THEN
Append(res,n.data)
FI
n=n.nxt
OD
RETURN
 
PROC Difference(SetInfo POINTER a,b,res)
Clear(res)
AppendSet(res,a)
RemoveSet(res,b)
RETURN
 
BYTE FUNC IsSubset(SetInfo POINTER s,sub)
SetNode POINTER n
 
n=sub.begin
WHILE n
DO
IF Contains(s,n.data)=0 THEN
RETURN (0)
FI
n=n.nxt
OD
RETURN (1)
 
BYTE FUNC AreEqual(SetInfo POINTER a,b)
IF IsSubset(a,b)=0 OR IsSubset(b,a)=0 THEN
RETURN (0)
FI
RETURN (1)
 
BYTE FUNC IsProperSubset(SetInfo POINTER s,sub)
IF IsSubset(s,sub)=1 AND IsSubset(sub,s)=0 THEN
RETURN (1)
FI
RETURN (0)
 
PROC TestContains(SetInfo POINTER s CHAR ARRAY v)
IF Contains(s,v) THEN
PrintF("%S contains %S%E",s.name,v)
ELSE
PrintF("%S does not contain %S%E",s.name,v)
FI
RETURN
 
PROC TestUnion(SetInfo POINTER a,b,res)
Union(a,b,res)
PrintF("Union %S and %S: ",a.name,b.name)
PrintSet(res)
RETURN
 
PROC TestIntersection(SetInfo POINTER a,b,res)
Intersection(a,b,res)
PrintF("Intersection %S and %S: ",a.name,b.name)
PrintSet(res)
RETURN
 
PROC TestDifference(SetInfo POINTER a,b,res)
Difference(a,b,res)
PrintF("Difference %S-%S: ",a.name,b.name)
PrintSet(res)
RETURN
 
PROC TestSubset(SetInfo POINTER s,sub)
IF IsSubset(s,sub) THEN
PrintF("%S is a subset of %S%E",sub.name,s.name)
ELSE
PrintF("%S is not a subset of %S%E",sub.name,s.name)
FI
RETURN
 
PROC TestEqual(SetInfo POINTER a,b)
IF AreEqual(a,b) THEN
PrintF("%S and %S are equal%E",a.name,b.name)
ELSE
PrintF("%S and %S are not equal%E",a.name,b.name)
FI
RETURN
 
PROC TestProperSubset(SetInfo POINTER s,sub)
IF IsSubset(s,sub) THEN
PrintF("%S is a proper subset of %S%E",sub.name,s.name)
ELSE
PrintF("%S is not a proper subset of %S%E",sub.name,s.name)
FI
RETURN
 
PROC TestAppend(SetInfo POINTER s CHAR ARRAY v)
Append(s,v)
PrintF("%S+%S: ",s.name,v)
PrintSet(s)
RETURN
 
PROC TestRemove(SetInfo POINTER s CHAR ARRAY v)
Remove(s,v)
PrintF("%S-%S: ",s.name,v)
PrintSet(s)
RETURN
 
PROC Main()
SetInfo s1,s2,s3,s4
 
Put(125) PutE() ;clear screen
AllocInit(0)
CreateSet(s1,"A")
CreateSet(s2,"B")
CreateSet(s3,"C")
CreateSet(s4,"D")
 
Append(s1,"Action!") Append(s1,"Basic")
Append(s1,"Ada") Append(s1,"Fortran")
Append(s2,"Pascal") Append(s2,"Action!")
Append(s2,"C++") Append(s2,"C#")
Append(s3,"Basic") Append(s3,"Fortran")
Append(s3,"Action!") Append(s3,"Ada")
PrintSet(s1) PrintSet(s2) PrintSet(s3)
PutE()
 
TestContains(s1,"Action!")
TestContains(s2,"Fortran")
TestUnion(s1,s2,s4)
TestIntersection(s1,s2,s4)
TestDifference(s2,s1,s4)
TestSubset(s1,s4)
TestSubset(s2,s4)
TestEqual(s1,s3)
TestEqual(s2,s3)
TestProperSubset(s1,s4)
TestProperSubset(s1,s3)
TestRemove(s3,"Fortran")
TestRemove(s3,"C#")
TestAppend(s3,"Java")
TestAppend(s3,"Java")
 
Clear(s1)
Clear(s2)
Clear(s3)
Clear(s4)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Set.png Screenshot from Atari 8-bit computer]
<pre>
A=(Action!, Basic, Ada, Fortran)
B=(Pascal, Action!, C++, C#)
C=(Basic, Fortran, Action!, Ada)
 
A contains Action!
B does not contain Fortran
Union A and B: D=(Action!, Basic, Ada, Fortran, Pascal, C++, C#)
Intersection A and B: D=(Action!)
Difference B-A: D=(Pascal, C++, C#)
D is not a subset of A
D is a subset of B
A and C are equal
B and C are not equal
D is not a proper subset of A
C is a proper subset of A
C-Fortran: C=(Basic, Action!, Ada)
C-C#: C=(Basic, Action!, Ada)
C+Java: C=(Basic, Action!, Ada, Java)
C+Java: C=(Basic, Action!, Ada, Java)
</pre>
 
=={{header|Ada}}==
Line 37 ⟶ 394:
An alternative hash-based solution could use the Hashed_Maps package from Ada.Containers.
 
<langsyntaxhighlight Adalang="ada">with ada.containers.ordered_sets, ada.text_io;
use ada.text_io;
 
Line 66 ⟶ 423:
end loop;
end set_demo;
</syntaxhighlight>
</lang>
 
{{out}}
Line 81 ⟶ 438:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">record
union(record a, record b)
{
Line 161 ⟶ 518:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> banana is not an element of A
Line 170 ⟶ 527:
no
no</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Reuses a lot of code from the Symetric difference task.
<syntaxhighlight lang="algol68"># sets using associative arrays #
# include the associative array code for string keys and values #
PR read "aArray.a68" PR
 
# adds the elements of s to the set 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 a set 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 a set containing the elements of a and those of b, i.e. a UNION b #
PRIO U = 6;
OP U = ( 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 # U # ;
# returns a set containing the elements of a INTERSECTION b #
PRIO N = 6;
OP N = ( 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 b CONTAINSKEY key OF e THEN
result // key OF e := value OF e
FI;
e := NEXT a
OD;
result
END # N # ;
# returns TRUE if all the elements of a are in b, FALSE otherwise #
OP <= = ( REF AARRAY a, REF AARRAY b )BOOL:
BEGIN
BOOL result := TRUE;
REF AAELEMENT e := FIRST a;
WHILE result AND ( e ISNT nil element ) DO
result := b CONTAINSKEY key OF e;
e := NEXT a
OD;
result
END # <= # ;
# returns TRUE if all the elements of a are in b #
# and all the elements of b are in a, FALSE otherwise #
OP = = ( REF AARRAY a, REF AARRAY b )BOOL: a <= b AND b <= a;
# returns NOT ( a = b ) #
OP /= = ( REF AARRAY a, REF AARRAY b )BOOL: NOT ( a = b );
# returns TRUE if all the elements of a are in b #
# but not all the elements of b are in a, FALSE otherwise #
OP < = ( REF AARRAY a, REF AARRAY b )BOOL: a <= b AND b /= a;
 
# prints the elements of a in no-particlar order #
PROC print set = ( REF AARRAY a )VOID:
BEGIN
print( ( "[" ) );
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
print( ( " ", key OF e ) );
e := NEXT a
OD;
print( ( " ]", newline ) )
END # print set # ;
 
# construct associative arrays for the task #
REF AARRAY gas giants := INIT LOC AARRAY;
REF AARRAY ice giants := INIT LOC AARRAY;
REF AARRAY rocky planets := INIT LOC AARRAY;
REF AARRAY inner planets := INIT LOC AARRAY;
REF AARRAY moonless planets := INIT LOC AARRAY;
gas giants // []STRING( "Jupiter", "Saturn" );
ice giants // []STRING( "Uranus", "Neptune" );
rocky planets // []STRING( "Mercury", "Venus", "Earth", "Mars" );
inner planets // []STRING( "Mercury", "Venus", "Earth", "Mars" );
moonless planets // []STRING( "Mercury", "Venus" );
 
print( ( "rocky planets : " ) );print set( rocky planets );
print( ( "inner planets : " ) );print set( inner planets );
print( ( "gas giants : " ) );print set( gas giants );
print( ( "ice giants : " ) );print set( ice giants );
print( ( "moonless planets: " ) );print set( moonless planets );
print( ( newline ) );
 
print( ( """Saturn"" is "
, IF gas giants CONTAINSKEY "Saturn" THEN "" ELSE " not" FI
, "in gas giants", newline
)
);
print( ( """Venus"" is "
, IF gas giants CONTAINSKEY "Venus" THEN "" ELSE "not " FI
, "in gas giants", newline
)
);
print( ( "gas giants UNION ice giants : " ) );
print set( gas giants U ice giants );
print( ( "moonless planets INTERSECTION rocky planets: " ) );
print set( moonless planets N rocky planets );
print( ( "rocky planets \ moonless planets : " ) );
print set( rocky planets - moonless planets );
print( ( "moonless planets <= rocky planets : "
, IF moonless planets <= rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
print( ( "moonless planets = rocky planets : "
, IF moonless planets = rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
print( ( "inner planets = rocky planets : "
, IF inner planets = rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
print( ( "moonless planets < rocky planets : "
, IF moonless planets < rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
 
# REF AARRAYs are mutable #
 
REF AARRAY all planets := inner planets U gas giants U ice giants;
print( ( "all planets : " ) );
print set( all planets );
print( ( "... after restoration of Pluto: " ) );
all planets // "Pluto";
print set( all planets )</syntaxhighlight>
{{out}}
<pre>
rocky planets : [ Mercury Mars Earth Venus ]
inner planets : [ Mercury Mars Earth Venus ]
gas giants : [ Jupiter Saturn ]
ice giants : [ Neptune Uranus ]
moonless planets: [ Mercury Venus ]
 
"Saturn" is in gas giants
"Venus" is not in gas giants
gas giants UNION ice giants : [ Neptune Jupiter Saturn Uranus ]
moonless planets INTERSECTION rocky planets: [ Mercury Venus ]
rocky planets \ moonless planets : [ Mars Earth ]
moonless planets <= rocky planets : yes
moonless planets = rocky planets : no
inner planets = rocky planets : yes
moonless planets < rocky planets : yes
all planets : [ Neptune Jupiter Mercury Mars Earth Venus Saturn Uranus ]
... after restoration of Pluto: [ Neptune Jupiter Mercury Mars Earth Venus Pluto Saturn Uranus ]
</pre>
 
=={{header|Apex}}==
In Apex, Sets are unordered collections of elements. Although elements can be anything including primitives, Ids, Apex classes, or sObjects, typically they are used with primitives and Ids.
 
<langsyntaxhighlight lang="apex">
public class MySetController{
public Set<String> strSet {get; private set; }
Line 204 ⟶ 738:
}
}
</syntaxhighlight>
</lang>
</pre>
 
Line 211 ⟶ 745:
macOS's Foundation framework offers a few classes of set which can be used in AppleScript by means of AppleScriptObjectiveC code. The basic types are <tt>NSSet</tt> and its mutable equivalent <tt>NSMutableSet</tt>.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
--use scripting additions
Line 260 ⟶ 794:
end doSetTask
 
doSetTask()</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight lang="applescript">"Set S: 0, 9, 1, 6, 2, 7, 3, 8
\"aardvark\" is a member of S: false
3 is a member of S: true
Line 276 ⟶ 810:
A is a subset of S: true
A is equal to B: false
A is equal to S: true"</langsyntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: [1 2 3 4]
b: [3 4 5 6]
 
print in? 3 a
print contains? b 3
 
print union a b
print intersection a b
print difference a b
print difference.symmetric a b
 
print a = b
 
print subset? [1 3] a
print subset?.proper [1 3] a
print subset? [1 3] [1 3]
print subset?.proper [1 3] [1 3]
 
print superset? a [1 3]
print superset?.proper a [1 3]
print superset? [1 3] [1 3]
print superset?.proper [1 3] [1 3]</syntaxhighlight>
 
{{out}}
 
<pre>true
true
1 2 3 4 5 6
3 4
1 2
1 2 5 6
false
true
true
true
false
true
true
true
false</pre>
 
=={{header|ATS}}==
{{libheader|xxHash}}
The following demonstrates sets of strings stored as a hash-keyed AVL tree. It requires the [http://www.xxhash.net xxHash] C library.
 
You might notice the operator overloading.
 
(Aside: If one were going to write an ATS implementation of sets as linked lists, it might be well to base the implementation on the reference code for Scheme SRFI-1: [https://srfi.schemers.org/srfi-1/srfi-1-reference.scm]. This is particularly so if an '''eq?'''-like function is possible for set members.)
 
<syntaxhighlight lang="ats">(*------------------------------------------------------------------*)
 
#define ATS_DYNLOADFLAG 0
 
#include "share/atspre_staload.hats"
 
(*------------------------------------------------------------------*)
(* String hashing using XXH3_64bits from the xxHash suite. *)
 
#define ATS_EXTERN_PREFIX "hashsets_postiats_"
 
%{^ /* Embedded C code. */
 
#include <xxhash.h>
 
ATSinline() atstype_uint64
hashsets_postiats_mem_hash (atstype_ptr data, atstype_size len)
{
return (atstype_uint64) XXH3_64bits (data, len);
}
 
%}
 
extern fn mem_hash : (ptr, size_t) -<> uint64 = "mac#%"
 
fn
string_hash (s : string) :<> uint64 =
let
val len = string_length s
in
mem_hash ($UNSAFE.cast{ptr} s, len)
end
 
(*------------------------------------------------------------------*)
(* A trimmed down version of the AVL trees from the AVL Tree task. *)
 
datatype bal_t =
| bal_minus1
| bal_zero
| bal_plus1
 
datatype avl_t (key_t : t@ype+,
data_t : t@ype+,
size : int) =
| avl_t_nil (key_t, data_t, 0)
| {size_L, size_R : nat}
avl_t_cons (key_t, data_t, size_L + size_R + 1) of
(key_t, data_t, bal_t,
avl_t (key_t, data_t, size_L),
avl_t (key_t, data_t, size_R))
typedef avl_t (key_t : t@ype+,
data_t : t@ype+) =
[size : int] avl_t (key_t, data_t, size)
 
extern fun {key_t : t@ype}
avl_t$compare (u : key_t, v : key_t) :<> int
 
#define NIL avl_t_nil ()
#define CONS avl_t_cons
#define LNIL list_nil ()
#define :: list_cons
#define F false
#define T true
 
typedef fixbal_t = bool
 
prfn
lemma_avl_t_param {key_t : t@ype} {data_t : t@ype} {size : int}
(avl : avl_t (key_t, data_t, size)) :<prf>
[0 <= size] void =
case+ avl of NIL => () | CONS _ => ()
 
fn {}
minus_neg_bal (bal : bal_t) :<> bal_t =
case+ bal of
| bal_minus1 () => bal_plus1
| _ => bal_zero ()
 
fn {}
minus_pos_bal (bal : bal_t) :<> bal_t =
case+ bal of
| bal_plus1 () => bal_minus1
| _ => bal_zero ()
 
fn
avl_t_is_empty {key_t : t@ype} {data_t : t@ype} {size : int}
(avl : avl_t (key_t, data_t, size)) :<>
[b : bool | b == (size == 0)] bool b =
case+ avl of
| NIL => T
| CONS _ => F
 
fn
avl_t_isnot_empty {key_t : t@ype} {data_t : t@ype} {size : int}
(avl : avl_t (key_t, data_t, size)) :<>
[b : bool | b == (size <> 0)] bool b =
~avl_t_is_empty avl
 
fn {key_t : t@ype} {data_t : t@ype}
avl_t_search_ref {size : int}
(avl : avl_t (key_t, data_t, size),
key : key_t,
data : &data_t? >> opt (data_t, found),
found : &bool? >> bool found) :<!wrt>
#[found : bool] void =
let
fun
search (p : avl_t (key_t, data_t),
data : &data_t? >> opt (data_t, found),
found : &bool? >> bool found) :<!wrt,!ntm>
#[found : bool] void =
case+ p of
| NIL =>
{
prval _ = opt_none {data_t} data
val _ = found := F
}
| CONS (k, d, _, left, right) =>
begin
case+ avl_t$compare<key_t> (key, k) of
| cmp when cmp < 0 => search (left, data, found)
| cmp when cmp > 0 => search (right, data, found)
| _ =>
{
val _ = data := d
prval _ = opt_some {data_t} data
val _ = found := T
}
end
in
$effmask_ntm search (avl, data, found)
end
 
fn {key_t : t@ype} {data_t : t@ype}
avl_t_search_opt {size : int}
(avl : avl_t (key_t, data_t, size),
key : key_t) :<>
Option (data_t) =
let
var data : data_t?
var found : bool?
val _ = $effmask_wrt avl_t_search_ref (avl, key, data, found)
in
if found then
let
prval _ = opt_unsome data
in
Some {data_t} data
end
else
let
prval _ = opt_unnone data
in
None {data_t} ()
end
end
 
fn {key_t : t@ype} {data_t : t@ype}
avl_t_insert_or_replace {size : int}
(avl : avl_t (key_t, data_t, size),
key : key_t,
data : data_t) :<>
[sz : pos] (avl_t (key_t, data_t, sz), bool) =
let
fun
search {size : nat}
(p : avl_t (key_t, data_t, size),
fixbal : fixbal_t,
found : bool) :<!ntm>
[sz : pos]
(avl_t (key_t, data_t, sz), fixbal_t, bool) =
case+ p of
| NIL => (CONS (key, data, bal_zero, NIL, NIL), T, F)
| CONS (k, d, bal, left, right) =>
case+ avl_t$compare<key_t> (key, k) of
| cmp when cmp < 0 =>
let
val (p1, fixbal, found) = search (left, fixbal, found)
in
case+ (fixbal, bal) of
| (F, _) => (CONS (k, d, bal, p1, right), F, found)
| (T, bal_plus1 ()) =>
(CONS (k, d, bal_zero (), p1, right), F, found)
| (T, bal_zero ()) =>
(CONS (k, d, bal_minus1 (), p1, right), fixbal, found)
| (T, bal_minus1 ()) =>
let
val+ CONS (k1, d1, bal1, left1, right1) = p1
in
case+ bal1 of
| bal_minus1 () =>
let
val q = CONS (k, d, bal_zero (), right1, right)
val q1 = CONS (k1, d1, bal_zero (), left1, q)
in
(q1, F, found)
end
| _ =>
let
val p2 = right1
val- CONS (k2, d2, bal2, left2, right2) = p2
val q = CONS (k, d, minus_neg_bal bal2,
right2, right)
val q1 = CONS (k1, d1, minus_pos_bal bal2,
left1, left2)
val q2 = CONS (k2, d2, bal_zero (), q1, q)
in
(q2, F, found)
end
end
end
| cmp when cmp > 0 =>
let
val (p1, fixbal, found) = search (right, fixbal, found)
in
case+ (fixbal, bal) of
| (F, _) => (CONS (k, d, bal, left, p1), F, found)
| (T, bal_minus1 ()) =>
(CONS (k, d, bal_zero (), left, p1), F, found)
| (T, bal_zero ()) =>
(CONS (k, d, bal_plus1 (), left, p1), fixbal, found)
| (T, bal_plus1 ()) =>
let
val+ CONS (k1, d1, bal1, left1, right1) = p1
in
case+ bal1 of
| bal_plus1 () =>
let
val q = CONS (k, d, bal_zero (), left, left1)
val q1 = CONS (k1, d1, bal_zero (), q, right1)
in
(q1, F, found)
end
| _ =>
let
val p2 = left1
val- CONS (k2, d2, bal2, left2, right2) = p2
val q = CONS (k, d, minus_pos_bal bal2,
left, left2)
val q1 = CONS (k1, d1, minus_neg_bal bal2,
right2, right1)
val q2 = CONS (k2, d2, bal_zero (), q, q1)
in
(q2, F, found)
end
end
end
| _ => (CONS (key, data, bal, left, right), F, T)
in
if avl_t_is_empty avl then
(CONS (key, data, bal_zero, NIL, NIL), F)
else
let
prval _ = lemma_avl_t_param avl
val (avl, _, found) = $effmask_ntm search (avl, F, F)
in
(avl, found)
end
end
 
fn {key_t : t@ype} {data_t : t@ype}
avl_t_insert {size : int}
(avl : avl_t (key_t, data_t, size),
key : key_t,
data : data_t) :<>
[sz : pos] avl_t (key_t, data_t, sz) =
(avl_t_insert_or_replace<key_t><data_t> (avl, key, data)).0
 
fun {key_t : t@ype} {data_t : t@ype}
push_all_the_way_left (stack : List (avl_t (key_t, data_t)),
p : avl_t (key_t, data_t)) :
List0 (avl_t (key_t, data_t)) =
let
prval _ = lemma_list_param stack
in
case+ p of
| NIL => stack
| CONS (_, _, _, left, _) =>
push_all_the_way_left (p :: stack, left)
end
 
fun {key_t : t@ype} {data_t : t@ype}
update_generator_stack (stack : List (avl_t (key_t, data_t)),
right : avl_t (key_t, data_t)) :
List0 (avl_t (key_t, data_t)) =
let
prval _ = lemma_list_param stack
in
if avl_t_is_empty right then
stack
else
push_all_the_way_left<key_t><data_t> (stack, right)
end
 
fn {key_t : t@ype} {data_t : t@ype}
avl_t_make_data_generator {size : int}
(avl : avl_t (key_t, data_t, size)) :
() -<cloref1> Option data_t =
let
typedef avl_t = avl_t (key_t, data_t)
 
val stack = push_all_the_way_left<key_t><data_t> (LNIL, avl)
val stack_ref = ref stack
 
(* Cast stack_ref to its (otherwise untyped) pointer, so it can be
enclosed within ‘generate’. *)
val p_stack_ref = $UNSAFE.castvwtp0{ptr} stack_ref
 
fun
generate () :<cloref1> Option data_t =
let
(* Restore the type information for stack_ref. *)
val stack_ref =
$UNSAFE.castvwtp0{ref (List avl_t)} p_stack_ref
 
var stack : List0 avl_t = !stack_ref
var retval : Option data_t
in
begin
case+ stack of
| LNIL => retval := None ()
| p :: tail =>
let
val- CONS (_, d, _, left, right) = p
in
retval := Some d;
stack :=
update_generator_stack<key_t><data_t> (tail, right)
end
end;
!stack_ref := stack;
retval
end
in
generate
end
 
(*------------------------------------------------------------------*)
(* Sets implemented with a hash function, AVL trees and association *)
(* lists. *)
 
(* The interface - - - - - - - - - - - - - - - - - - - - - - - - - *)
 
(* For simplicity, let us support only 64-bit hashes. *)
 
typedef hashset_t (key_t : t@ype+) =
avl_t (uint64, List1 key_t)
 
extern fun {key_t : t@ype} (* Implement a hash function with this. *)
hashset_t$hashfunc : key_t -<> uint64
 
extern fun {key_t : t@ype} (* Implement key equality with this. *)
hashset_t$key_eq : (key_t, key_t) -<> bool
 
extern fun
hashset_t_nil :
{key_t : t@ype}
() -<> hashset_t key_t
 
extern fun {key_t : t@ype}
hashset_t_add_member :
(hashset_t key_t, key_t) -<> hashset_t key_t
 
(*
"remove_member" is not implemented here, because the trimmed down AVL
tree implementation above does not include deletion. We shall
implement everything else without using a member deletion routine.
 
extern fun {key_t : t@ype}
hashset_t_remove_member :
(hashset_t key_t, key_t) -<> hashset_t key_t
 
Of course you can remove a member by using hashset_t_difference.
*)
 
extern fun {key_t : t@ype}
hashset_t_has_member :
(hashset_t key_t, key_t) -<> bool
 
typedef hashset_t_binary_operation (key_t : t@ype) =
(hashset_t key_t, hashset_t key_t) -> hashset_t key_t
 
extern fun {key_t : t@ype}
hashset_t_union : hashset_t_binary_operation key_t
 
extern fun {key_t : t@ype}
hashset_t_intersection : hashset_t_binary_operation key_t
 
extern fun {key_t : t@ype}
hashset_t_difference : hashset_t_binary_operation key_t
 
extern fun {key_t : t@ype}
hashset_t_subset :
(hashset_t key_t, hashset_t key_t) -> bool
 
extern fun {key_t : t@ype}
hashset_t_equal :
(hashset_t key_t, hashset_t key_t) -> bool
 
(* Note: generators for hashset_t produce their output in unspecified
order. *)
extern fun {key_t : t@ype}
hashset_t_make_generator :
hashset_t key_t -> () -<cloref1> Option key_t
 
(* The implementation - - - - - - - - - - - - - - - - - - - - - - - *)
 
(* I make no promises that these are the most efficient
implementations I could devise. They certainly are not! But they
were easy to write and will work. *)
 
implement
hashset_t_nil () =
avl_t_nil ()
 
fun {key_t : t@ype}
find_key {n : nat} .<n>.
(lst : list (key_t, n),
key : key_t) :<>
List0 key_t =
(* This implementation is tail recursive. It will not build up the
stack. *)
case+ lst of
| list_nil () => lst
| list_cons (head, tail) =>
if hashset_t$key_eq<key_t> (key, head) then
lst
else
find_key (tail, key)
 
implement {key_t}
hashset_t_add_member (set, key) =
(* The following implementation assumes equal keys are
interchangeable. *)
let
implement
avl_t$compare<uint64> (u, v) =
if u < v then ~1 else if v < u then 1 else 0
typedef lst_t = List1 key_t
val hash = hashset_t$hashfunc<key_t> key
val lst_opt = avl_t_search_opt<uint64><lst_t> (set, hash)
in
case+ lst_opt of
| Some lst =>
begin
case+ find_key<key_t> (lst, key) of
| list_cons _ => set
| list_nil () =>
avl_t_insert<uint64><lst_t>
(set, hash, list_cons (key, lst))
end
| None () =>
avl_t_insert<uint64><lst_t>
(set, hash, list_cons (key, list_nil ()))
end
 
implement {key_t}
hashset_t_has_member (set, key) =
let
implement
avl_t$compare<uint64> (u, v) =
if u < v then ~1 else if v < u then 1 else 0
typedef lst_t = List1 key_t
val hash = hashset_t$hashfunc<key_t> key
val lst_opt = avl_t_search_opt<uint64><lst_t> (set, hash)
in
case+ lst_opt of
| None () => false
| Some lst =>
begin
case+ find_key<key_t> (lst, key) of
| list_nil () => false
| list_cons _ => true
end
end
 
implement {key_t}
hashset_t_union (u, v) =
let
val gen_u = hashset_t_make_generator<key_t> u
val gen_v = hashset_t_make_generator<key_t> v
var w : hashset_t key_t = hashset_t_nil ()
var k_opt : Option key_t
in
for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ())
w := hashset_t_add_member (w, option_unsome k_opt);
for (k_opt := gen_v (); option_is_some k_opt; k_opt := gen_v ())
w := hashset_t_add_member (w, option_unsome k_opt);
w
end
 
implement {key_t}
hashset_t_intersection (u, v) =
let
val gen_u = hashset_t_make_generator<key_t> u
var w : hashset_t key_t = hashset_t_nil ()
var k_opt : Option key_t
in
for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ())
let
val+ Some k = k_opt
in
if hashset_t_has_member<key_t> (v, k) then
w := hashset_t_add_member (w, k)
end;
w
end
 
implement {key_t}
hashset_t_difference (u, v) =
let
val gen_u = hashset_t_make_generator<key_t> u
var w : hashset_t key_t = hashset_t_nil ()
var k_opt : Option key_t
in
for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ())
let
val+ Some k = k_opt
in
if ~hashset_t_has_member<key_t> (v, k) then
w := hashset_t_add_member (w, k)
end;
w
end
 
implement {key_t}
hashset_t_subset (u, v) =
let
val gen_u = hashset_t_make_generator<key_t> u
var subset : bool = true
var done : bool = false
in
while (~done)
case+ gen_u () of
| None () => done := true
| Some k =>
if ~hashset_t_has_member<key_t> (v, k) then
begin
subset := false;
done := true
end;
subset
end
 
implement {key_t}
hashset_t_equal (u, v) =
hashset_t_subset<key_t> (u, v)
&& hashset_t_subset<key_t> (v, u)
 
implement {key_t}
hashset_t_make_generator (set) =
let
typedef lst_t = List1 key_t
typedef lst_t_0 = List0 key_t
 
val avl_gen = avl_t_make_data_generator<uint64><lst_t> (set)
 
val current_list_ref : ref lst_t_0 = ref (list_nil ())
val current_list_ptr =
$UNSAFE.castvwtp0{ptr} current_list_ref
in
lam () =>
let
val current_list_ref =
$UNSAFE.castvwtp0{ref lst_t_0} current_list_ptr
in
case+ !current_list_ref of
| list_nil () =>
begin
case+ avl_gen () of
| None () => None ()
| Some lst =>
begin
case+ lst of
| list_cons (head, tail) =>
begin
!current_list_ref := tail;
Some head
end
end
end
| list_cons (head, tail) =>
begin
!current_list_ref := tail;
Some head
end
end
end
 
(*------------------------------------------------------------------*)
 
implement
hashset_t$hashfunc<string> (s) =
string_hash s
 
implement
hashset_t$key_eq<string> (s, t) =
s = t
 
typedef strset_t = hashset_t string
 
fn {}
strset_t_nil () :<> strset_t =
hashset_t_nil ()
 
fn
strset_t_add_member (set : strset_t,
member : string) :<> strset_t =
hashset_t_add_member<string> (set, member)
 
fn {}
strset_t_member_add (member : string,
set : strset_t) :<> strset_t =
strset_t_add_member (set, member)
 
#define SNIL strset_t_nil ()
infixr ( :: ) ++ (* Right associative, same precedence as :: *)
overload ++ with strset_t_member_add
 
fn
strset_t_has_member (set : strset_t,
member : string) :<> bool =
hashset_t_has_member<string> (set, member)
overload [] with strset_t_has_member
 
fn
strset_t_union (u : strset_t, v : strset_t) : strset_t =
hashset_t_union<string> (u, v)
overload + with strset_t_union
 
fn
strset_t_intersection (u : strset_t, v : strset_t) : strset_t =
hashset_t_intersection<string> (u, v)
infixl ( + ) ^
overload ^ with strset_t_intersection
 
fn
strset_t_difference (u : strset_t, v : strset_t) : strset_t =
hashset_t_difference<string> (u, v)
overload - with strset_t_difference
 
fn
strset_t_subset (u : strset_t, v : strset_t) : bool =
hashset_t_subset<string> (u, v)
overload <= with strset_t_subset
 
fn
strset_t_equal (u : strset_t, v : strset_t) : bool =
hashset_t_equal<string> (u, v)
overload = with strset_t_equal
 
fn
strset_t_make_generator (set : strset_t) :
() -<cloref1> Option string =
hashset_t_make_generator<string> set
 
fn
strset_t_print (set : strset_t) : void =
let
val gen = strset_t_make_generator set
var s_opt : Option string
var separator : string = ""
in
print! ("#<strset_t ");
for (s_opt := gen (); option_is_some s_opt; s_opt := gen ())
case+ s_opt of
| Some s =>
begin
(* The following quick and dirty implemenetation does not
insert escape sequences. *)
print! (separator, "\"", s, "\"");
separator := " "
end;
print! (">")
end
 
implement
main0 () =
let
val set1 =
"one" ++ "two" ++ "three" ++ "guide" ++ "design" ++ SNIL
val set2 =
"ett" ++ "två" ++ "tre" ++ "guide" ++ "design" ++ SNIL
in
print! ("set1 = ");
strset_t_print set1;
 
println! ();
println! ();
println! ("set1[\"one\"] = ", set1["one"]);
println! ("set1[\"two\"] = ", set1["two"]);
println! ("set1[\"three\"] = ", set1["three"]);
println! ("set1[\"four\"] = ", set1["four"]);
 
println! ();
print! ("set2 = ");
strset_t_print set2;
 
println! ();
println! ();
println! ("set2[\"ett\"] = ", set2["ett"]);
println! ("set2[\"två\"] = ", set2["två"]);
println! ("set2[\"tre\"] = ", set2["tre"]);
println! ("set2[\"fyra\"] = ", set2["fyra"]);
 
println! ();
print! ("Union\nset1 + set2 = ");
strset_t_print (set1 + set2);
println! ();
println! ();
print! ("Intersection\nset1 ^ set2 = ");
strset_t_print (set1 ^ set2);
println! ();
println! ();
print! ("Difference\nset1 - set2 = ");
strset_t_print (set1 - set2);
println! ();
 
println! ();
println! ("Subset");
println! ("set1 <= set1: ", set1 <= set1);
println! ("set2 <= set2: ", set2 <= set2);
println! ("set1 <= set2: ", set1 <= set2);
println! ("set2 <= set1: ", set2 <= set1);
println! ("(set1 ^ set2) <= set1: ", (set1 ^ set2) <= set1);
println! ("(set1 ^ set2) <= set2: ", (set1 ^ set2) <= set2);
 
println! ();
println! ("Equal");
println! ("set1 = set1: ", set1 = set1);
println! ("set2 = set2: ", set2 = set2);
println! ("set1 = set2: ", set1 = set2);
println! ("set2 = set1: ", set2 = set1);
println! ("(set1 ^ set2) = (set2 ^ set1): ",
(set1 ^ set2) = (set2 ^ set1));
println! ("(set1 ^ set2) = set1: ", (set1 ^ set2) = set1);
println! ("(set1 ^ set2) = set2: ", (set1 ^ set2) = set2)
end
 
(*------------------------------------------------------------------*)</syntaxhighlight>
 
{{out}}
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW hashsets-postiats.dats -lxxhash -lgc && ./a.out
set1 = #<strset_t "guide" "design" "two" "one" "three">
 
set1["one"] = true
set1["two"] = true
set1["three"] = true
set1["four"] = false
 
set2 = #<strset_t "två" "guide" "design" "ett" "tre">
 
set2["ett"] = true
set2["två"] = true
set2["tre"] = true
set2["fyra"] = false
 
Union
set1 + set2 = #<strset_t "två" "guide" "design" "two" "ett" "one" "three" "tre">
 
Intersection
set1 ^ set2 = #<strset_t "guide" "design">
 
Difference
set1 - set2 = #<strset_t "two" "one" "three">
 
Subset
set1 <= set1: true
set2 <= set2: true
set1 <= set2: false
set2 <= set1: false
(set1 ^ set2) <= set1: true
(set1 ^ set2) <= set2: true
 
Equal
set1 = set1: true
set2 = set2: true
set1 = set2: false
set2 = set1: false
(set1 ^ set2) = (set2 ^ set1): true
(set1 ^ set2) = set1: false
(set1 ^ set2) = set2: false</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">test(Set,element){
for i, val in Set
if (val=element)
Line 329 ⟶ 1,698:
equal(SetA,SetB){
return (SetA.MaxIndex() = SetB.MaxIndex() && subset(SetA,SetB)) ? 1: 0
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">A:= ["apple", "cherry", "elderberry", "grape"]
B:= ["banana", "cherry", "date", "elderberry", "fig"]
C:= ["apple", "cherry", "elderberry", "grape", "orange"]
Line 371 ⟶ 1,740:
Res .= "`nA is " (equal(A,E)?"":"not ") "a equal to Set E"
 
MsgBox % Res</langsyntaxhighlight>
{{out}}
<pre>A:= ["apple", "cherry", "elderberry", "grape"]
Line 394 ⟶ 1,763:
A is not a equal to Set E</pre>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
The sets are represented as 32-bit integers, which means that the maximum number of elements is 32.
<langsyntaxhighlight lang="bbcbasic"> DIM list$(6)
list$() = "apple", "banana", "cherry", "date", "elderberry", "fig", "grape"
Line 438 ⟶ 1,808:
IF set% AND 1 << i% o$ += list$(i%) + ", "
NEXT
= LEFT$(LEFT$(o$))</langsyntaxhighlight>
{{out}}
<pre>
Line 455 ⟶ 1,825:
Set A is not equal to set B
</pre>
 
=={{header|BQN}}==
 
BQN can use lists with only unique elements to represent sets. The following implement all the basic set relations.
 
<syntaxhighlight lang="bqn">Union ← ⍷∾
Inter ← ∊/⊣
Diff ← ¬∘∊/⊣
Subset ← ∧´∊
Eq ← ≡○∧
CreateSet ← ⍷
 
•Show 2‿4‿6‿8 Union 2‿3‿5‿7
•Show 2‿4‿6‿8 Inter 2‿3‿5‿7
•Show 2‿4‿6‿8 Diff 2‿3‿5‿7
•Show 2‿4‿6‿8 Subset 2‿3‿5‿7
•Show 2‿4‿6‿8 Eq 2‿3‿5‿7
•Show CreateSet 2‿2‿3‿5‿7‿2</syntaxhighlight><syntaxhighlight lang="text">⟨ 2 4 6 8 3 5 7 ⟩
⟨ 2 ⟩
⟨ 4 6 8 ⟩
0
0
⟨ 2 3 5 7 ⟩</syntaxhighlight>
 
=={{header|C}}==
Line 460 ⟶ 1,853:
 
A frequent use of set is that of small, non-negative integers, implemented as a bit field as shown below.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef unsigned int set_t; /* probably 32 bits; change according to need */
Line 504 ⟶ 1,897:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 562 ⟶ 1,955:
Console.ReadKey();
}
}</langsyntaxhighlight>
{{out}}
<pre>Set creation
Line 592 ⟶ 1,985:
C++11 standard library also contains unordered_set based on a hash table. However, algorithms like std::set_intersection etc take sorted ranges, so set-specific functions should be hand-rolled.
 
<langsyntaxhighlight lang="cpp">
#include <set>
#include <iostream>
Line 672 ⟶ 2,065:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
value a = set {1, 2, 3};
value b = set {3, 4, 5};
Line 692 ⟶ 2,085:
a subset of b? ``subset``
a == b? ``equality``");
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">(require 'clojure.set)
 
; sets can be created using the set method or set literal syntax
Line 710 ⟶ 2,103:
(clojure.set/difference a b)
 
(clojure.set/subset? a b)</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
This implements functions from the task, along with an iteration helper called "each".
<langsyntaxhighlight lang="coffeescript">
# For ad-hoc set features, it sometimes makes sense to use hashes directly,
# rather than abstract to this level, but I'm showing a somewhat heavy
Line 800 ⟶ 2,193:
 
run_tests()
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Common Lisp provides some set operations on lists.
<langsyntaxhighlight lang="lisp">(setf a '(1 2 3 4))
(setf b '(2 3 4 5))
 
Line 825 ⟶ 2,218:
(subsetp b a))
"~a = ~a~%"
"~a ≠ ~a~%") a b)</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range;
 
Line 848 ⟶ 2,241:
const s5 = [1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8];
assert(s4.nWayUnion.equal(s5));
}</langsyntaxhighlight> =={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
module set;
import std.typecons : Tuple, tuple;
Line 1,002 ⟶ 2,395:
return true;
}
</syntaxhighlight>
</lang>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="d">void main(){
//Set Creation
Set A = new Set.from([1,2,3]);
Line 1,042 ⟶ 2,435:
print('A is equal to B = ${B.containsAll(A) && A.containsAll(B)}');
print('B is equal to AC = ${B.containsAll(AC) && AC.containsAll(B)}');
}</langsyntaxhighlight>
{{out}}
<pre>Set A = {1, 2, 3}
Line 1,065 ⟶ 2,458:
A is equal to B = false
B is equal to AC = true</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| Boost.Generics.Collection}}
The library [https://github.com/MaiconSoft/DelphiBoostLib Boost.Generics.Collection].
<syntaxhighlight lang="delphi">
program Set_task;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
Boost.Generics.Collection;
 
begin
var s1 := TSet<Integer>.Create([1, 2, 3, 4, 5, 6]);
var s2 := TSet<Integer>.Create([2, 5, 6, 3, 4, 8]);
var s3 := TSet<Integer>.Create([1, 2, 5]);
 
Writeln('S1 ', s1.ToString);
Writeln('S2 ', s2.ToString);
Writeln('S3 ', s3.ToString, #10);
 
Writeln('4 is in S1? ', s1.Has(4));
Writeln('S1 union S2 ', (s1 + S2).ToString);
Writeln('S1 intersection S2 ', (s1 * S2).ToString);
Writeln('S1 difference S2 ', (s1 - S2).ToString);
Writeln('S3 is subset S2 ', s1.IsSubSet(s3));
Writeln('S1 equality S2? ', s1 = s2);
readln;
end.</syntaxhighlight>
{{out}}
<pre>S1 { 1, 2, 3, 4, 5, 6 }
S2 { 2, 3, 4, 5, 6, 8 }
S3 { 1, 2, 5 }
 
4 is in S1? TRUE
S1 union S2 { 1, 2, 3, 4, 5, 6, 8 }
S1 intersection S2 { 2, 3, 4, 5, 6 }
S1 difference S2 { 1 }
S3 is subset S2 TRUE
S1 equality S2? FALSE</pre>
 
=={{header|Diego}}==
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
// Set creation
add_set(A)_values(🐖,🦬,🦘,🦫,🦭);
add_set(B)_values(🐈‍⬛,🦬,🦫,🦤,🐐);
add_set(C)_values(🐈‍⬛,🦫);
add_set(M)_value(🐖);
 
// Membership
ms_msg()_calc([M]∈[B])
? with_msg()_msg(set M is an element in set B);
: with_msg()_msg(set M is not an element in set B);
;
 
ms_msg()_calc(🐖∈[A])
? with_msg()_msg(🐖 is an element in set A);
: with_msg()_msg(🐖 is not an element in set A);
;
 
// Union
ms_msg()_msg(A∪B=[])_calc([A]∪[B]);
 
// Intersection
ms_msg()_msg(A∩B=[])_calc([A]∩[B]);
 
// Difference
ms_msg()_msg(A∖B=[])_calc([A]∖[B]); // U+2216 is used not U+005c (\)
ms_msg()_msg(A\\B=[])_calc([A]\\[B]); // U+005c (\) has to be escaped
 
// Subset
ms_msg()_calc([C]⊆[A])
? with_msg()_msg(set C is a subset of set A);
: with_msg()_msg(set C is not a subset of set A);
;
 
ms_msg()_calc([C]⊆[B])
? with_msg()_msg(set C is a subset of set B);
: with_msg()_msg(set C is not a subset of set B);
;
 
// Equality
ms_msg()_calc([A]=[B])
? with_msg()_msg(set A is equal to set B);
: with_msg()_msg(set A is not equal to set B);
;
 
// Test
ms_msg()_calc([A]⊂[B])_or()_calc([A]⊊[B])
? with_msg()_msg(set A is a proper subset of set B);
: with_msg()_msg(set A is not a proper subset of set B);
;
 
ms_msg()_calc([C]⊂[B]||[C]⊊[B]) // alternative syntax
? with_msg()_msg(set C is a proper subset of set B);
: with_msg()_msg(set C is not a proper subset of set B);
;
 
// Modify a mutable set (all sets are mutable)
with_set(M)_push(🦬,🦘,🦫,🦭);
ms_msg()_calc([M]=[A])
? with_msg()_msg(set M is equal to set A);
: with_msg()_msg(set M is not equal to set A);
;
 
reset_namespace[];</syntaxhighlight>
 
{{out}}
 
<pre>set M is an element in set B
🐖 is an element in set A
A∪B=🐖,🦬,🦘,🦫,🦭,🐈‍⬛,🦤,🐐
A∩B=🦬,🦫
A∖B=🐖,🦘,🦭
A\B=🐖,🦘,🦭
set C is not a subset of set A
set C is a subset of set B
set A is not equal to set B
set A is not a proper subset of set B
set C is a proper subset of set B
set M is equal to set A</pre>
 
=={{header|EchoLisp}}==
Line 1,070 ⟶ 2,586:
 
The set operations are: ∩ ∪ ⊆ / ∈ = ∆ ×
<langsyntaxhighlight lang="lisp">
; use { } to read a set
(define A { 1 2 3 4 3 5 5}) → { 1 2 3 4 5 } ; duplicates are removed from a set
Line 1,104 ⟶ 2,620:
; A few functions return sets :
(primes 10) → { 2 3 5 7 11 13 17 19 23 29 }
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{works with|Elixir|1.1}}
<langsyntaxhighlight lang="elixir">iex(1)> s = MapSet.new
#MapSet<[]>
iex(2)> sa = MapSet.put(s, :a)
Line 1,135 ⟶ 2,651:
false
iex(14)> sa == sab
false</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 1,162 ⟶ 2,678:
=={{header|F_Sharp|F#}}==
The Collections.Set<'T> class implements "Immutable sets based on binary trees, where comparison is the F# structural comparison function, potentially using implementations of the IComparable interface on key values." (http://msdn.microsoft.com/en-us/library/ee353619.aspx)
<langsyntaxhighlight lang="fsharp">[<EntryPoint>]
let main args =
// Create some sets (of int):
Line 1,187 ⟶ 2,703:
printfn "s1 ⊂ s1? %A" (Set.isProperSubset s1 s1)
printfn "s1 ⊂ s2? %A" (Set.isProperSubset s1 s2)
0</langsyntaxhighlight>
{{out}}
<pre>Some sets (of int):
Line 1,211 ⟶ 2,727:
=={{header|Factor}}==
We will use Factor's hash-sets for this task. A hash-set is created with <code>HS{ ... }</code>.
<langsyntaxhighlight lang="factor">( scratchpad ) USE: sets
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } union .
HS{ 2 3 4 5 6 7 }
Line 1,225 ⟶ 2,741:
f
( scratchpad ) HS{ 6 5 7 } HS{ 5 6 7 } set= .
t</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 1,232 ⟶ 2,748:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
include FMS-SILib.f
 
Line 1,289 ⟶ 2,805:
i{ 5 6 } i{ 5 6 7 } set= . 0 ok
i{ 6 5 7 } i{ 5 6 7 } set= . -1 ok
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">function is_in( N as integer, S() as integer ) as boolean
'test if the value N is in the set S
for i as integer = 0 to ubound(S)
if N=S(i) then return true
next i
return false
end function
 
sub add_to_set( N as integer, S() as integer )
'adds the element N to the set S
if is_in( N, S() ) then return
dim as integer k = ubound(S)
redim preserve S(0 to k+1)
S(k+1)=N
end sub
 
sub setunion( S() as integer, T() as integer, U() as integer )
'makes U() the union of the sets S and T
dim as integer k = ubound(S)
redim U(-1)
for i as integer = 0 to k
add_to_set( S(i), U() )
next i
k = ubound(T)
for i as integer = 0 to k
if not is_in( T(i), U() ) then
add_to_set( T(i), U() )
end if
next i
end sub
 
sub setintersect( S() as integer, T() as integer, U() as integer )
'makes U() the intersection of the sets S and T
dim as integer k = ubound(S)
redim U(-1)
for i as integer = 0 to k
if is_in(S(i), T()) then add_to_set( S(i), U() )
next i
end sub
 
sub setsubtract( S() as integer, T() as integer, U() as integer )
'makes U() the difference of the sets S and T
dim as integer k = ubound(S)
redim U(-1)
for i as integer = 0 to k
if not is_in(S(i), T()) then add_to_set( S(i), U() )
next i
end sub
 
function is_subset( S() as integer, T() as integer ) as boolean
for i as integer = 0 to ubound(S)
if not is_in( S(i), T() ) then return false
next i
return true
end function
 
function is_equal( S() as integer, T() as integer ) as boolean
if not is_subset( S(), T() ) then return false
if not is_subset( T(), S() ) then return false
return true
end function
 
function is_proper_subset( S() as integer, T() as integer ) as boolean
if not is_subset( S(), T() ) then return false
if is_equal( S(), T() ) then return false
return true
end function
 
sub show_set( L() as integer )
'display a set
dim as integer num = ubound(L)
if num=-1 then
print "[]"
return
end if
print "[";
for i as integer = 0 to num-1
print str(L(i))+", ";
next i
print str(L(num))+"]"
end sub
 
'sets are created by making an empty array
redim as integer S1(-1), S2(-1), S3(-1), S4(-1), S5(-1)
'and populated by adding elements one-by-one
add_to_set( 20, S1() ) : add_to_set( 30, S1() )
add_to_set( 40, S1() ) : add_to_set( 50, S1() )
add_to_set( 19, S2() ) : add_to_set( 20, S2() )
add_to_set( 21, S2() ) : add_to_set( 22, S2() )
add_to_set( 22, S3() ) : add_to_set( 21, S3() )
add_to_set( 19, S3() ) : add_to_set( 20, S3() )
add_to_set( 21, S3() ) ' attempt to add a number that's already in the set
add_to_set( 21, S4() )
print "S1 ",
show_set S1()
print "S2 ",
show_set S2()
print "S3 ",
show_set S3()
print "S4 ",
show_set S4()
print "S5 ",
show_set S5()
print "----"
redim as integer S_U(-1)
setunion S1(), S2(), S_U()
print "S1 U S2 ",
show_set S_U()
redim as integer S_U(-1)
setintersect S1(), S2(), S_U()
print "S1 n S2 ",
show_set S_U()
redim as integer S_U(-1)
setsubtract S1(), S2(), S_U()
print "S1 \ S2 ",
show_set S_U()
redim as integer S_U(-1)
setsubtract S3(), S1(), S_U()
print "S3 \ S1 ",
show_set S_U()
print "S4 in S3? ", is_subset(S4(), S3())
print "S3 in S4? ", is_subset(S3(), S4())
print "S5 in S3? ", is_subset(S5(), S3()) 'empty set is a subset of every set
print "S2 = S3? ", is_equal(S2(), S3())
print "S4 proper subset of S3? ", is_proper_subset( S4(), S3() )
print "S2 proper subset of S3? ", is_proper_subset( S2(), S3() )</syntaxhighlight>
{{out}}
<pre>
S1 [20, 30, 40, 50]
S2 [19, 20, 21, 22]
S3 [22, 21, 19, 20]
S4 [21]
S5 []
----
S1 U S2 [20, 30, 40, 50, 19, 21, 22]
S1 n S2 [20]
S1 \ S2 [30, 40, 50]
S3 \ S1 [22, 21, 19]
S4 in S3? true
S3 in S4? false
S5 in S3? true
S2 = S3? true
S4 proper subset of S3? true
S2 proper subset of S3? false</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
a = new set[1, 2]
b = toSet[[2,3]] // Construct a set from an array
Line 1,302 ⟶ 2,964:
isSubset[a,b] // Returns true if a is a subset of b
a==b // set equality test
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">A = {1, 2, 3}
B = {3, 4, 5}
C = {1, 2, 3, 4, 5}
Line 1,327 ⟶ 2,989:
println( 'S subset of C: ' + S.subsetOf(C) )
S.remove( 1 )
println( 'S after 1 removed: ' + S )</langsyntaxhighlight>
 
{{out}}
Line 1,345 ⟶ 3,007:
S subset of C: true
S after 1 removed: {2, 3, 4}
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
 
local fn DoIt
// create
CFSetRef s1 = fn SetWithArray( @[@"a",@"b",@"c",@"d",@"e"] )
CFSetRef s2 = fn SetWithArray( @[@"b",@"c",@"d",@"e",@"f",@"h"] )
CFSetRef s3 = fn SetWithArray( @[@"b",@"c",@"d"] )
CFSetRef s4 = fn SetWithArray( @[@"b",@"c",@"d"] )
NSLog(@"s1: %@",s1)
NSLog(@"s2: %@",s2)
NSLog(@"s3: %@",s3)
NSLog(@"s4: %@\n",s4)
 
// membership
NSLog(@"\"b\" in s1: %d", fn SetContainsObject( s1, @"b" ))
NSLog(@"\"f\" in s1: %d\n", fn SetContainsObject( s1, @"f" ))
 
// union
CFMutableSetRef s12 = fn MutableSetWithSet( s1 )
MutableSetUnionSet( s12, s2 )
NSLog(@"s1 union s2: %@\n", s12)
 
// intersection
CFMutableSetRef s1i2 = fn MutableSetWithSet( s1 )
MutableSetIntersectSet( s1i2, s2 )
NSLog(@"s1 intersect s2: %@\n", s1i2)
 
// difference
CFMutableSetRef s1d2 = fn MutableSetWithSet( s1 )
MutableSetMinusSet( s1d2, s2 )
NSLog(@"s1 - s2: %@\n", s1d2)
 
// subsetof
NSLog(@"s3 subset of s1: %d\n", fn SetIsSubsetOfSet( s3, s1 ))
 
// equality
NSLog(@"s3 == s4: %d\n", fn SetIsEqual( s3, s4 ))
 
// cardinality
NSLog(@"size of s1: %lu\n", fn SetCount(s1))
 
// has intersection (not disjoint)
NSLog(@"s1 intersects s2: %d\n", fn SetIntersectsSet( s1, s2 ))
 
// adding and removing elements from mutable set
CFMutableSetRef s1mut = fn MutableSetWithSet( s1 )
MutableSetAddObject( s1mut, @"g" )
NSLog(@"s1mut after adding \"g\": %@\n", s1mut)
MutableSetAddObject( s1mut, @"b" )
NSLog(@"s1mut after adding \"b\" again: %@\n", s1mut)
MutableSetRemoveObject( s1mut, @"c" )
NSLog(@"s1mut after removing \"c\": %@\n", s1mut)
end fn
 
fn DoIt
 
HandleEvents</syntaxhighlight>
 
{{out}}
<pre>
s1: {(
d,
b,
e,
c,
a
)}
s2: {(
d,
b,
e,
c,
h,
f
)}
s3: {(
b,
c,
d
)}
s4: {(
b,
c,
d
)}
 
"b" in s1: 1
"f" in s1: 0
 
s1 union s2: {(
d,
b,
f,
e,
c,
a,
h
)}
 
s1 intersect s2: {(
d,
b,
e,
c
)}
 
s1 - s2: {(
a
)}
 
s3 subset of s1: 1
 
s3 == s4: 1
 
size of s1: 5
 
s1 intersects s2: 1
 
s1mut after adding "g": {(
d,
b,
g,
e,
c,
a
)}
 
s1mut after adding "b" again: {(
d,
b,
g,
e,
c,
a
)}
 
s1mut after removing "c": {(
d,
b,
g,
e,
a
)}
</pre>
 
Line 1,351 ⟶ 3,159:
===Maps===
Go maps meet the task description in that they do not require orderable elements. To demonstrate that, a set of complex numbers is shown here. Complex numbers can be compared for equality but are not ordered.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,481 ⟶ 3,289:
func properSubset(a, b set) bool {
return len(a) < len(b) && subset(a, b)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,506 ⟶ 3,314:
 
Note that the elements here, being integers, are of course ordered and so might not meet a strict reading of the task requirements.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,638 ⟶ 3,446:
}
return
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,661 ⟶ 3,469:
===Intsets===
Not quite in the stanard library but still in the official "sub repository", intsets are a ''sparse'' bit set. Like big.Int they use a single bit to represent a possible element, but the sparse representation efficiently allows for large "holes" in the element sequence. Also the intsets API provides a more set-like terminology so the RC task can be coded more directly.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,720 ⟶ 3,528:
}
return &set
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,741 ⟶ 3,549:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def s1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set
def m1 = 6
def m2 = 7
Line 1,759 ⟶ 3,567:
assert s1 != su && su.containsAll(s1) : 'proper subset'
s1 << 0
assert s1 == su : 'added element 0 to s1'</langsyntaxhighlight>
 
=={{header|Haskell}}==
{{works with|GHC}}
GHC offers a functional, persistent set data structure in its <code>Data.Set</code> module. It is implemented using a binary search tree. Elements must be of an orderable type (instance of <code>Ord</code>).
<langsyntaxhighlight lang="haskell">Prelude> import Data.Set
Prelude Data.Set> empty :: Set Integer -- Empty set
fromList []
Line 1,798 ⟶ 3,606:
fromList [1,2,3,4,99]
Prelude Data.Set> delete 3 s1 -- Create a new set by deleting
fromList [1,2,4]</langsyntaxhighlight>
 
Regular lists can also be used as sets. Haskell has some functions to help with using lists as sets. No requirement is made of element type. However, these are not very efficient because they require linear time to find an element.
<langsyntaxhighlight lang="haskell">Prelude> import Data.List
Prelude Data.List> let s3 = nub [1,2,3,4,3] -- Remove duplicates from list
Prelude Data.List> s3
Line 1,815 ⟶ 3,623:
[42,1,2,3,4]
Prelude Data.List> delete 3 s3 -- Return new list with first occurrence of element removed
[1,2,4]</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,823 ⟶ 3,631:
Implemented directly:
 
<langsyntaxhighlight lang="unicon">
procedure display_set (s)
writes ("[")
Line 1,885 ⟶ 3,693:
write ("(1,2,5) is not included in a")
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,904 ⟶ 3,712:
Using library:
 
<langsyntaxhighlight lang="unicon">
link sets
 
Line 1,944 ⟶ 3,752:
write ("(1,2,5) is not included in a")
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,967 ⟶ 3,775:
Here are definitions for the required operations:
 
<langsyntaxhighlight lang="j">union=: ~.@,
intersection=: [ -. -.
difference=: -.
subset=: *./@e.
equality=: -:&(/:~)</langsyntaxhighlight>
 
Examples:
 
<langsyntaxhighlight lang="j"> 2 4 6 8 ~.@, 2 3 5 7
2 4 6 8 3 5 7
2 4 6 8 ([ -. -.) 2 3 5 7
Line 1,986 ⟶ 3,794:
1
2 4 6 8 3 5 7 -:&(/:~) 8 7 6 5 4 3 2
1</langsyntaxhighlight>
 
Examples again, using names rather than code:
 
<langsyntaxhighlight lang="j"> 2 4 6 8 union 2 3 5 7
2 4 6 8 3 5 7
2 4 6 8 intersection 2 3 5 7
Line 2,001 ⟶ 3,809:
1
2 4 6 8 3 5 7 equality 8 7 6 5 4 3 2
1</langsyntaxhighlight>
 
Note that J uses 1 for true and 0 for false. Mathematical revisionists object to this, but this is consistent with the original (and revised) formulations of boolean algebra. (And there are deep ties to Bayes' rule.)
Line 2,007 ⟶ 3,815:
Note that these operations can be combined in sentences with other operations. For example we could define
 
<langsyntaxhighlight lang="j">properSubset=: subset * 1 - equality</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|7+}}
To use this in Java 5 replace all "<>" with "<Integer>".
<langsyntaxhighlight lang="java5">import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
Line 2,073 ⟶ 3,881:
Collections.unmodifiableSet(a); //returns an immutable copy of a
}
}</langsyntaxhighlight>
{{out}}
<pre>a: [1, 2, 3, 4, 5]
Line 2,093 ⟶ 3,901:
JavaScript does not support native sets before ECMAScript 6.
 
<langsyntaxhighlight lang="javascript">
var set = new Set();
 
Line 2,117 ⟶ 3,925:
for (var item of set) {
console.log('item is ' + item);
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 2,137 ⟶ 3,945:
 
For example:
<langsyntaxhighlight lang="jq">{"a":true, "b":true } == {"b":true, "a":true}.
{"a":true} + {"b":true } == { "a":true, "b":true}</langsyntaxhighlight>
 
Thus, it can be seen that jq has built-in support for sets of finite-length Unicode strings.
Line 2,147 ⟶ 3,955:
 
Here is a jq filter for determining whether a JSON object is a "string set":
<langsyntaxhighlight lang="jq">def is_stringset:
. as $in | type == "object" and reduce keys[] as $key (true; . and $in[$key] == true);</langsyntaxhighlight>
 
'''String-set membership''':
Line 2,154 ⟶ 3,962:
The test for set membership, m ∈ S, where m is a string and S is a
set of strings, corresponds exactly to the jq test:
<syntaxhighlight lang ="jq">T | has(m)</langsyntaxhighlight>
where T is the JSON object corresponding to S. This test is also efficient.
 
'''String-set intersection'''
<langsyntaxhighlight lang="jq"># Set-intersection: A ∩ B
def stringset_intersection(A;B):
reduce (A|keys)[] as $k
({}; if (B|has($k)) then . + {($k):true} else . end);</langsyntaxhighlight>
 
'''String-set difference'''
<langsyntaxhighlight lang="jq"># stringset_difference: A \ B
def stringset_difference(A;B):
reduce (A|keys)[] as $k
({}; if (B|has($k)) then . else . + {($k):true} end);</langsyntaxhighlight>
 
'''Subset'''
<langsyntaxhighlight lang="jq"># A ⊆ B iff string_subset(A;B)
def stringset_subset(A;B):
reduce (A|keys)[] as $k
(true; . and (B|has($k)));</langsyntaxhighlight>
 
=== Finite Sets of JSON Entities ===
Line 2,194 ⟶ 4,002:
jq operator "unique". To test whether an arbitrary JSON entity is a set
without sorting:
<langsyntaxhighlight lang="jq">def is_set:
. as $in
| type == "array" and
reduce range(0;length-1) as $i
(true; if . then $in[$i] < $in[$i+1] else false end);</langsyntaxhighlight>
 
The following library of set-theoretic functions is intended for use
Line 2,217 ⟶ 4,025:
whether m is an element of S, but for large sets, this is inefficient. A generally more efficient test membership of m in S would use
bsearch as defined at [[Binary search]] or as provided in recent versions of jq:
<langsyntaxhighlight lang="jq">def is_member(m): bsearch(m) > -1;</langsyntaxhighlight>
 
'''Intersection'''
<langsyntaxhighlight lang="jq"># If A and B are sets, then intersection(A;B) emits their intersection:
def intersection($A;$B):
def pop:
Line 2,230 ⟶ 4,038:
else [$i, $j+1] | pop
end;
[[0,0] | pop];</langsyntaxhighlight>
'''Difference'''
<langsyntaxhighlight lang="jq"># If A and B are sets, then A-B is emitted
def difference(A;B):
(A|length) as $al
Line 2,250 ⟶ 4,058:
end
) | .[2]
end ;</langsyntaxhighlight>
 
'''Union'''
Line 2,257 ⟶ 4,065:
 
To compute the union of two sets efficiently, it is helpful to define a function for merging sorted arrays.
<langsyntaxhighlight lang="jq"># merge input array with array x by comparing the heads of the arrays in turn;
# if both arrays are sorted, the result will be sorted:
def merge(x):
Line 2,278 ⟶ 4,086:
def union(A;B):
A|merge(B)
| reduce .[] as $m ([]; if length == 0 or .[length-1] != $m then . + [$m] else . end);</langsyntaxhighlight>
 
'''A ⊆ B'''
<langsyntaxhighlight lang="jq">def subset(A;B):
# TCO
def _subset:
Line 2,290 ⟶ 4,098:
else [ .[0], .[1][1:] ] | _subset
end;
[A,B] | _subset;</langsyntaxhighlight>
 
'''Test whether two sets intersect'''
Line 2,298 ⟶ 4,106:
If A and B are sets (i.e. A == (A|unique) and B == (B|unique)),
then ''[A,B] | intersect'' emits true if A and B have at least one element in common:
<langsyntaxhighlight lang="jq">def intersect:
.[0] as $A | .[1] as $B
| ($A|length) as $al
Line 2,309 ⟶ 4,117:
end
end;
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Line 2,338 ⟶ 4,146:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 2,373 ⟶ 4,181:
println("fruits5 + 'guava' : $fruits5")
println("fruits5 - 'cherry' : ${fruits5 - "cherry"}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,406 ⟶ 4,214:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">// Extend set type
define set->issubsetof(p::set) => .intersection(#p)->size == .size
define set->oncompare(p::set) => .intersection(#p)->size - .size
Line 2,430 ⟶ 4,238:
 
//A = B -- equality; true if every element of set A is in set B and vice-versa.
#set1 == #set2</langsyntaxhighlight>
 
{{out}}
Line 2,443 ⟶ 4,251:
{{trans|Erlang}}
 
<langsyntaxhighlight lang="lisp">
> (set set-1 (sets:new))
#(set 0 16 16 8 80 48 ...)
Line 2,472 ⟶ 4,280:
> (=:= set-3 set-4)
true
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
Sets are not natively available- implemented here in string form so no need to dim/redim or pass number of elements.
<syntaxhighlight lang="lb">
<lang lb>
A$ ="red hot chili peppers rule OK"
B$ ="lady in red"
Line 2,626 ⟶ 4,434:
end function
</syntaxhighlight>
</lang>
Line 2,645 ⟶ 4,453:
=={{header|Lua}}==
{{works with|lua|5.1}}
<langsyntaxhighlight lang="lua">function emptySet() return { } end
function insert(set, item) set[item] = true end
function remove(set, item) set[item] = nil end
Line 2,713 ⟶ 4,521:
return subset(setA, setB) and (size(setA) == size(setB))
end
</syntaxhighlight>
</lang>
 
{{works with|lua|5.3}}
Line 2,722 ⟶ 4,530:
The code is intended to be placed into a file and accessed as a module. E.g. if placed into the file "set.lua" it would be accessed with <code>set = require 'set'</code>.
 
<langsyntaxhighlight lang="lua">local function new(_, ...)
local r = {}
local s = setmetatable({}, {
Line 2,832 ⟶ 4,640:
end
 
return setmetatable({}, { __call = new })</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 2,838 ⟶ 4,646:
For search in a tuple we have O(N).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Sets {
setA=("apple", "cherry", "grape")
Line 2,912 ⟶ 4,720:
}
Sets
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
Sets in Maple are built-in, native data structures, and are immutable. Sets are formed by enclosing a sequence of objects between braces. You can get something essentially equivalent to set comprehensions by using {seq}, which applies the set constructor ("{}") to the sequencing operation "seq".
<syntaxhighlight lang="maple">
<lang Maple>
> S := { 2, 3, 5, 7, 11, Pi, "foo", { 2/3, 3/4, 4/5 } };
S := {2, 3, 5, 7, 11, "foo", Pi, {2/3, 3/4, 4/5}}
Line 2,958 ⟶ 4,766:
> evalb( { 1, 2, 3 } = { 1, 2, 4 } );
false
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">set1 = {"a", "b", "c", "d", "e"}; set2 = {"a", "b", "c", "d", "e", "f", "g"};
MemberQ[set1, "a"]
Union[set1 , set2]
Line 2,968 ⟶ 4,776:
MemberQ[Subsets[set2], set1](*Subset*)
set1 == set2(*Equality*)
set1 == set1(*Equality*)</langsyntaxhighlight>
{{out}}
<pre>True
Line 2,976 ⟶ 4,784:
True
False
True</pre>
</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
There are two types of sets supported, sets with numeric values are stored in a vector, sets with string elements are stored in a cell-array.
<syntaxhighlight lang="matlab">
<lang Matlab>
% Set creation
s = [1, 2, 4]; % numeric values
Line 2,999 ⟶ 4,806:
% A = B -- equality; true if every element of set A is in set B and vice-versa.
isempty(setxor(A, B))
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">/* illustrating some functions on sets; names are self-explanatory */
 
a: {1, 2, 3, 4};
Line 3,079 ⟶ 4,886:
 
setequalp(a, b);
false</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
This is a full implementation of a set class.
<langsyntaxhighlight lang="nanoquery">class set
declare internal_list
 
Line 3,160 ⟶ 4,967:
return str(this.internal_list)
end
end</langsyntaxhighlight>
Testing this implementation:
<langsyntaxhighlight lang="nanoquery">import "rosetta-code/set.nq"
 
a = new(set, {1, 2, 3, 4, 5})
Line 3,186 ⟶ 4,993:
println "a intersect b: " + a.intersection(b)
println "add 7 to a: " + a.append(7)
println "add 2 to a again: " + a.append(2)</langsyntaxhighlight>
{{out}}
<pre>a: [1, 2, 3, 4, 5]
Line 3,205 ⟶ 5,012:
=={{header|Nemerle}}==
The <tt>Nemerle.Collections</tt> namespace provides an implementation of a Set.
<langsyntaxhighlight Nemerlelang="nemerle">using System.Console;
using Nemerle.Collections;
 
Line 3,231 ⟶ 5,038:
WriteLine($"$same\t$sub12");
}
}</langsyntaxhighlight>
 
=={{header|Nim}}==
Nim provides a set constructor which accepts elements of an ordinal type with at most 65536 values. Each element is represented by a bit. For non-ordinal elements or if the possible number of elements is too large (for instance for a set of strings or a set of 32 or 64 bits integers), the standard library provides a set constructor named HashSet.
<lang nim>var # creation
 
s = {0,3,5,10}
Here is an example of usage of a set.
 
<syntaxhighlight lang="nim">var # creation
s = {0, 3, 5, 10}
t = {3..20, 50..55}
 
Line 3,247 ⟶ 5,058:
if s <= t: echo "s ⊆ t" # subset
 
if s <= t: echo "s ⊂ t" # strong subset
 
if s == t: echo "s = s" # equality
 
s.incl(4) # add 4 to set
s.excl(5) # remove 5 from set</langsyntaxhighlight>
 
HashSets are not very different, less efficient but more versatile. Here is the same program with HashSets. The only difference is the way to create a HashSet: this is done by converting an array or sequence to the HashSet. As there is no way to specify a range in an array, we use a conversion of range to sequence with “toSeq” and a union.
 
<syntaxhighlight lang="nim">import sequtils, sets
 
var # creation
s = [0, 3, 5, 10].toHashSet
t = toSeq(3..20).toHashSet + toSeq(50..55).toHashSet
 
if 5 in s: echo "5 is in!" # element test
 
var
c = s + t # union
d = s * t # intersection
e = s - t # difference
 
if s <= t: echo "s ⊆ t" # subset
 
if s < t: echo "s ⊂ t" # strong subset
 
if s == t: echo "s = s" # equality
 
s.incl(4) # add 4 to set
s.excl(5) # remove 5 from set</syntaxhighlight>
 
Note that there exists also an Ordered constructor which remembers the insertion order. And for sets of integers, the module “intsets” provides another constructor better suited for sparse integer sets.
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main (int argc, const char *argv[]) {
Line 3,311 ⟶ 5,148:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,393 ⟶ 5,230:
In the interactive toplevel:
{{works with|OCaml|4.02+}}
<langsyntaxhighlight lang="ocaml"># module IntSet = Set.Make(struct type t = int let compare = compare end);; (* Create a module for our type of set *)
module IntSet :
sig
Line 3,460 ⟶ 5,297:
- : IntSet.elt list = [1; 2; 3; 4; 99]
# IntSet.elements (IntSet.remove 3 s1);; (* Create a new set by deleting *)
- : IntSet.elt list = [1; 2; 4]</langsyntaxhighlight>
 
(Note: <code>of_list</code> is only available in OCaml 4.02+. In earlier versions, you can implement one yourself like
Line 3,470 ⟶ 5,307:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
; test set
(define set1 '(1 2 3 4 5 6 7 8 9))
Line 3,502 ⟶ 5,339:
(print (equal? set1 set4))
; ==> #true
</syntaxhighlight>
</lang>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">-- Set creation
-- Using the OF method
s1 = .set~of(1, 2, 3, 4, 5, 6)
Line 3,536 ⟶ 5,373:
Use Arg set_name,set
Say set_name':' set~makearray~makestring((LINE),',')
return</langsyntaxhighlight>
The set operators don't come out too well :-(
{{out}}
Line 3,548 ⟶ 5,385:
=={{header|PARI/GP}}==
Aside from ⊆, all operations are already a part of GP.
<langsyntaxhighlight lang="parigp">setsubset(s,t)={
for(i=1,#s,
if(!setsearch(t,s[i]), return(0))
Line 3,561 ⟶ 5,398:
setminus(s,t)
setsubset(s,t)
s==t</langsyntaxhighlight>
 
{{out}}
Line 3,579 ⟶ 5,416:
--[[User:Guionardo|Guionardo]] 22:03, 7 January 2012 (UTC)
 
<langsyntaxhighlight lang="pascal">program Rosetta_Set;
 
{$mode objfpc}{$H+}
Line 3,672 ⟶ 5,509:
readln;
 
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
For real code, try Set::Object from CPAN. Here we provide a primitive implementation using hashes.
<langsyntaxhighlight lang="perl">use strict;
 
package Set; # likely will conflict with stuff on CPAN
Line 3,788 ⟶ 5,625:
print "w = x ^ y = ", $w = ($x ^ $y), "\n";
print "w is ", ($w == $z) ? "" : "not ", "equal to z\n";
print "w is ", ($w == $x) ? "" : "not ", "equal to x\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
First, a simple implementaion using native sequences:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence set1 = {1,2,3},
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
set2 = {3,4,5}
<span style="color: #008080;">function</span> <span style="color: #000000;">is_element</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">set</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">return</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span>
function element(object x, sequence set)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return find(x,set)!=0
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">set_union</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">set2</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;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
function union(sequence set1, sequence set2)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">is_element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
for i=1 to length(set2) do
<span style="color: #000000;">set1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
if not element(set2[i],set1) then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
set1 = append(set1,set2[i])
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">return</span> <span style="color: #000000;">set1</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return set1
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">set_intersection</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
function intersection(sequence set1, sequence set2)
<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;">set1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
sequence res = {}
<span style="color: #008080;">if</span> <span style="color: #000000;">is_element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
for i=1 to length(set1) do
<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;">set1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
if element(set1[i],set2) then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
res = append(res,set1[i])
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return res
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">set_difference</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
function difference(sequence set1, sequence set2)
<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;">set1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
sequence res = {}
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">is_element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
for i=1 to length(set1) do
<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;">set1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
if not element(set1[i],set2) then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
res = append(res,set1[i])
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return res
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">set_subset</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">set2</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;">set1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
function subset(sequence set1, sequence set2)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">is_element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
for i=1 to length(set1) do
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
if not element(set1[i],set2) then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return false
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return true
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">set_equality</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)!=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
function equality(sequence set1, sequence set2)
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
if length(set1)!=length(set2) then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return false
<span style="color: #008080;">return</span> <span style="color: #000000;">set_subset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return subset(set1,set2)
end function
<span style="color: #000080;font-style:italic;">--test code:</span>
 
<span style="color: #0000FF;">?</span><span style="color: #000000;">is_element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 1</span>
--test code:
<span style="color: #0000FF;">?</span><span style="color: #000000;">is_element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 0</span>
?element(3,set1) -- 1
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_union</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- {1,2,3,4,5}</span>
?element(4,set1) -- 0
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_intersection</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- {3}</span>
?union(set1,set2) -- {1,2,3,4,5}
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_difference</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- {1,2}</span>
?intersection(set1,set2) -- {3}
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_subset</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 0</span>
?difference(set1,set2) -- {1,2}
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_subset</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 1</span>
?subset(set1,set2) -- 0
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_equality</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 0</span>
?subset({1,2},set1) -- 1
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_equality</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 1</span>
?equality(set1,set2) -- 0
<!--</syntaxhighlight>-->
?equality(set1,{3,1,2}) -- 1</lang>
{{out}}
<small>Note that you get true/false instead of 1/0 under pwa/p2js - use printf(1,"%t\n",...) in place of ? to get an exact match.</small>
<pre>
1
Line 3,868 ⟶ 5,706:
Alternative using dictionaries, which needs several additional visitor routines (at a pinch they could be merged),
but performance is better on larger sets:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>integer set1 = new_dict(),
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
set2 = new_dict()
<span style="color: #008080;">function</span> <span style="color: #000000;">create_set</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">={})</span>
setd(3,0,set1)
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
setd(1,0,set1)
<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;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
setd(2,0,set1)
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
setd(5,0,set2)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
setd(3,0,set2)
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
setd(4,0,set2)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">element</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">set</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">getd_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">u_visitor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">user_data</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">union_set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">user_data</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<span style="color: #008080;">or</span> <span style="color: #008080;">not</span> <span style="color: #000000;">element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">union_set</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">,</span><span style="color: #000000;">union_set</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">set_union</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">union_set</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">u_visitor</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">union_set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">u_visitor</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">union_set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">},</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">union_set</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">i_visitor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">user_data</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">inter_sect</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">user_data</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">,</span><span style="color: #000000;">inter_sect</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">set_intersection</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">inter_sect</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i_visitor</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">inter_sect</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">},</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">inter_sect</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">d_visitor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">user_data</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">diff_set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">user_data</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">,</span><span style="color: #000000;">diff_set</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">set_difference</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">diff_set</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d_visitor</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">diff_set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">},</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">diff_set</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">subset_res</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">s_visitor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">user_data</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">set2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">user_data</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">subset_res</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- cease traversal</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">subset</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">subset_res</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s_visitor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">subset_res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">equality</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">dict_size</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)!=</span><span style="color: #7060A8;">dict_size</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">subset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">map</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- for keys()
-- matching test code:</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">set1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">create_set</span><span style="color: #0000FF;">({</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}),</span>
<span style="color: #000000;">set2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">create_set</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}),</span>
<span style="color: #000000;">set3</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">create_set</span><span style="color: #0000FF;">({</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 1</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">element</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 0</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">keys</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set_union</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- {1,2,3,4,5}</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">keys</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set_intersection</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- {3}</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">keys</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set_difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- {1,2}</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">subset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 0</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">subset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 1</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">equality</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 0</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set3</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">equality</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set3</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 1</span>
<!--</syntaxhighlight>-->
Same output as above. I have written a builtins/sets.e, and tried another approach with builtins/sets2.e, but neither really hit the spot.
 
=={{header|Phixmonti}}==
function element(object x, integer set)
<syntaxhighlight lang="Phixmonti">include ..\Utilitys.pmt
return getd_index(x,set)!=0
end function
 
def isElement find enddef
function u_visitor(object key, object data, object user_data)
integer {union_set,set2} = user_data
if set2=0
or not element(key,union_set) then
setd(key,data,union_set)
end if
return 1
end function
 
def setUnion dup >ps remove ps> chain enddef
function union(integer set1, integer set2)
integer union_set = new_dict()
traverse_dict(routine_id("u_visitor"),{union_set,0},set1)
traverse_dict(routine_id("u_visitor"),{union_set,set2},set2)
return union_set
end function
 
def setIntersection over >ps remove ps> swap remove enddef
function i_visitor(object key, object data, object user_data)
integer {union_set,set2} = user_data
if element(key,set2) then
setd(key,data,union_set)
end if
return 1
end function
 
def setDifference remove enddef
function intersection(integer set1, integer set2)
integer union_set = new_dict()
traverse_dict(routine_id("i_visitor"),{union_set,set2},set1)
return union_set
end function
 
def setSubset swap remove len not nip enddef
function d_visitor(object key, object data, object user_data)
integer {union_set,set2} = user_data
if not element(key,set2) then
setd(key,data,union_set)
end if
return 1
end function
 
def setEquality sort swap sort == enddef
function difference(integer set1, integer set2)
integer union_set = new_dict()
traverse_dict(routine_id("d_visitor"),{union_set,set2},set1)
return union_set
end function
 
( 1 2 3 ) 1 isElement ?
integer res
4 isElement ?
function s_visitor(object key, object data, object user_data)
( 3 4 5 ) setUnion ?
integer set2 = user_data
( 1 2 3 ) ( 3 4 5 ) setIntersection ?
if not element(key,set2) then
( 1 2 3 ) ( 3 4 res5 =) 0setDifference ?
( 1 2 3 ) ( 3 4 return5 0) --setSubset cease traversal?
( 1 2 3 ) ( 1 2 ) setSubset ?
end if
( 1 2 3 ) ( 3 4 5 ) setEquality ?
return 1
( 1 2 3 ) ( 3 1 2 ) setEquality ?
end function
 
</syntaxhighlight>
function subset(integer set1, integer set2)
{{out}}
res = 1
<pre>1
traverse_dict(routine_id("s_visitor"),set2,set1)
0
return res
[1, 2, 3, 4, 5]
end function
[3]
 
[1, 2]
function equality(integer set1, integer set2)
0
if dict_size(set1)!=dict_size(set2) then
1
return false
0
end if
1
return subset(set1,set2)
end function
 
include builtins/map.e -- for keys()
 
=== Press any key to exit ===</pre>
-- matching test code:
?element(3,set1) -- 1
?element(4,set1) -- 0
?keys(union(set1,set2)) -- {1,2,3,4,5}
?keys(intersection(set1,set2)) -- {3}
?keys(difference(set1,set2)) -- {1,2}
?subset(set1,set2) -- 0
integer set3 = new_dict()
setd(2,0,set3)
setd(1,0,set3)
?subset(set3,set1) -- 1
?equality(set1,set2) -- 0
setd(3,0,set3)
?equality(set1,set3) -- 1</lang>
same output as above
 
=={{header|PicoLisp}}==
We may use plain lists, or '[http://software-lab.de/doc/refI.html#idx idx]' structures for sets. A set may contain any type of data.
===Using lists===
<langsyntaxhighlight PicoLisplang="picolisp">(setq
Set1 (1 2 3 7 abc "def" (u v w))
Set2 (2 3 5 hello (x y z))
Line 4,014 ⟶ 5,894:
 
: (= (sort (copy Set2)) (sort (copy Set2)))
-> T</langsyntaxhighlight>
===Using 'idx' structures===
<langsyntaxhighlight PicoLisplang="picolisp"># Create three test-sets
(balance 'Set1 (1 2 3 7 abc "def" (u v w)))
(balance 'Set2 (2 3 5 hello (x y z)))
Line 4,072 ⟶ 5,952:
 
: (= (idx 'Set2) (idx 'Set2))
-> T</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Line 4,079 ⟶ 5,959:
When used in PowerShell, the syntax is clumsy. In addition, the "reference" set (<code>$set1</code>) is modified in place to become the result.
(All examples assume the variable <code>$set1</code> contains the value <code>@(1,2,3,4)</code>)
<syntaxhighlight lang="powershell">
<lang PowerShell>
[System.Collections.Generic.HashSet[object]]$set1 = 1..4
[System.Collections.Generic.HashSet[object]]$set2 = 3..6
Line 4,097 ⟶ 5,977:
5 -in $set1 # Test membership False
7 -notin $set1 # Test non-membership True
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Works with SWI-Prolog, library(lists).
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(lists)).
 
set :-
Line 4,150 ⟶ 6,030:
select(H1, B, B1),
equal(T1, B1).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- set.
Line 4,179 ⟶ 6,059:
It treats sets as ordered lists of unique elements:
 
<langsyntaxhighlight lang="prolog">
%% Set creation
 
Line 4,235 ⟶ 6,115:
?- ord_del_element($NewA, 3, NewerA).
NewerA = [1, 2, 4, 19].
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
This solution uses PureBasic's maps (hash tables).
<langsyntaxhighlight lang="purebasic">Procedure.s booleanText(b) ;returns 'True' or 'False' for a boolean input
If b: ProcedureReturn "True": EndIf
ProcedureReturn "False"
Line 4,408 ⟶ 6,288:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Set A = (blue green orange red yellow) of cardinality 5.
Line 4,438 ⟶ 6,318:
(For versions prior to 2.7, use <code>set([1, 2, 3, 4])</code> instead of <code>{1, 2, 3, 4}</code>. Even in Python 2.7+ and 3.0+, it is necessary to write <code>set()</code> to express the empty set.)
{{works with|Python|2.7+ and 3.0+}}
<langsyntaxhighlight lang="python">>>> s1, s2 = {1, 2, 3, 4}, {3, 4, 5, 6}
>>> s1 | s2 # Union
{1, 2, 3, 4, 5, 6}
Line 4,486 ⟶ 6,366:
>>> s1
{1, 2, 3, 4, 5, 6}
>>> </langsyntaxhighlight>
 
=={{header|Quackery}}==
 
Sets are not implemented in Quackery, so we start with an implementation of sets as sorted nests of strings without duplicates.
 
This was the first pass at coding sets. I felt that bitmap sets were the way to go, but I wanted to get my head around the problem space and fill in a gap in my understanding, specifically pertaining to bignum bitmaps and the universal set. By the time I had coded an inefficient version that avoided the issue, I realised the solution - we don't need to accommodate everything, just everything we know about so far. So in the second version the ancillary stack <code>elements</code> holds a nest of the names of every set element we know of so far, and the word <code>elementid</code> returns the position of an element in that nest, if it has been encountered before, and adds it to the nest if it is previously unknown, then returns its position.
 
In both versions, a set element is any string of non-whitespace characters apart from "}set". If you desperately need set elements with spaces or carriage returns, or called "}set" there are workarounds.
 
Use the second version, it's a lot more efficient and the set of everything so far encountered is available if wanted. It's <code>[ elements share size bit 1 - ]</code>.
 
The set of everything is -1, just don't try to enumerate it; your program will crash when it gets to naming things it hasn't heard of.
 
===Sorted Nests of Strings===
 
<syntaxhighlight lang="quackery"> [ [] $ "" rot
sort$ witheach
[ tuck != if
[ dup dip
[ nested join ] ] ]
drop ] is -duplicates ( { --> { )
 
[ [] $ "" rot
sort$ witheach
[ tuck = if
[ nested join
$ "" ] ]
drop -duplicates ] is duplicates ( { --> { )
 
 
[ [] $ "" rot
sort$ witheach
[ tuck != iff
[ dup dip [ nested join ] ]
else
[ dip [ -1 pluck ]
over != if
[ nested join $ "" ] ] ]
drop ] is --duplicates ( { --> { )
 
[ [] swap
[ trim
dup $ "" = if
[ $ '"set{" without "}set"'
message put bail ]
nextword
dup $ "}set" != while
nested rot join swap
again ]
drop swap
-duplicates
' [ ' ] swap nested join
swap dip [ nested join ] ] builds set{ ( [ $ --> [ $ )
 
[ -duplicates
say "{ "
witheach [ echo$ sp ]
say "}" ] is echoset ( { --> { )
 
[ join duplicates ] is intersection ( { { --> { )
 
[ join -duplicates ] is union ( { { --> { )
 
[ join --duplicates ] is symmdiff ( { { --> { )
 
[ over intersection symmdiff ] is difference ( { { --> { )
 
[ over intersection = ] is subset ( { { --> b )
 
[ dip nested subset ] is element ( $ { --> b )
 
[ 2dup = iff
[ 2drop false ]
else subset ] is propersubset ( { { --> b )
 
( ------------------------------ demo ------------------------------ )
 
set{ apple peach pear melon
apricot banana orange }set is fruits ( --> { )
 
set{ red orange green blue
purple apricot peach }set is colours ( --> { )
 
fruits dup echoset say " are fruits" cr
 
colours dup echoset say " are colours" cr
2dup intersection echoset say " are both fruits and colours" cr
2dup union echoset say " are fruits or colours" cr
2dup symmdiff echoset say " are fruits or colours but not both" cr
difference echoset say " are fruits that are not colours" cr
set{ red green blue }set dup echoset say " are"
colours subset not if [ say " not" ] say " all colours" cr
say "fruits and colours are" fruits colours = not if [ say " not" ]
say " exactly the same" cr
$ "orange" dup echo$ say " is"
fruits element not if [ say " not" ] say " a fruit" cr
set{ orange }set dup echoset say " is"
fruits propersubset dup if [ say " not" ] say " the only fruit"
not if [ say " or not a fruit" ] cr</syntaxhighlight>
 
{{out}}
 
<pre>{ apple apricot banana melon orange peach pear } are fruits
{ apricot blue green orange peach purple red } are colours
{ apricot orange peach } are both fruits and colours
{ apple apricot banana blue green melon orange peach pear purple red } are fruits or colours
{ apple banana blue green melon pear purple red } are fruits or colours but not both
{ apple banana melon pear } are fruits that are not colours
{ blue green red } are all colours
fruits and colours are not exactly the same
orange is a fruit
{ orange } is not the only fruit</pre>
 
===Indexed Bitmaps===
 
<syntaxhighlight lang="quackery"> [ stack [ ] ] is elements ( --> s )
[ elements share 2dup find
dup rot found iff nip done
swap elements take
swap nested join
elements put ] is elementid ( $ --> n )
[ 0 temp put
[ trim
dup $ "" = if
[ $ '"set{" without "}set"'
message put bail ]
nextword
dup $ "}set" = iff drop done
elementid bit
temp take | temp put
again ]
temp take
swap dip
[ nested nested join ] ] builds set{ ( [ $ --> [ $ )
 
[ [] 0 rot
[ dup while
dup 1 & if
[ over elements share
swap peek nested
swap dip
[ rot join swap ] ]
dip 1+
1 >>
again ]
2drop ] is set->nest ( { --> [ )
[ say "{ "
set->nest witheach [ echo$ sp ]
say "}" ] is echoset ( { --> )
[ & ] is intersection ( { { --> { )
 
[ | ] is union ( { { --> { )
 
[ ^ ] is symmdiff ( { { --> { )
 
[ over intersection symmdiff ] is difference ( { { --> { )
 
[ over intersection = ] is subset ( { { --> b )
 
[ dip [ elementid bit ] subset ] is element ( $ { --> b )
 
[ 2dup = iff
[ 2drop false ]
else subset ] is propersubset ( { { --> b )
 
( ----------------------------- demo ---------------------------- )
 
set{ apple peach pear melon
apricot banana orange }set is fruits ( --> { )
 
set{ red orange green blue
purple apricot peach }set is colours ( --> { )
 
fruits dup echoset say " are fruits" cr
 
colours dup echoset say " are colours" cr
 
2dup intersection echoset say " are both fruits and colours" cr
2dup union echoset say " are fruits or colours" cr
2dup symmdiff echoset say " are fruits or colours but not both" cr
difference echoset say " are fruits that are not colours" cr
set{ red green blue }set dup echoset say " are"
colours subset not if [ say " not" ] say " all colours" cr
say "fruits and colours are" fruits colours = not if [ say " not" ]
say " exactly the same" cr
$ "orange" dup echo$ say " is"
fruits element not if [ say " not" ] say " a fruit" cr
set{ orange }set dup echoset say " is"
fruits propersubset dup if [ say " not" ] say " the only fruit"
not if [ say " or not a fruit" ] cr</syntaxhighlight>
 
{{out}}
 
<pre>{ orange banana apricot melon pear peach apple } are fruits
{ purple blue green red orange apricot peach } are colours
{ orange apricot peach } are both fruits and colours
{ purple blue green red orange banana apricot melon pear peach apple } are fruits or colours
{ purple blue green red banana melon pear apple } are fruits or colours but not both
{ banana melon pear apple } are fruits that are not colours
{ blue green red } are all colours
fruits and colours are not exactly the same
orange is a fruit
{ orange } is not the only fruit</pre>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 4,503 ⟶ 6,605:
(subset? C A) ; gives #f
(subset? C B) ; gives #t
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>use Test;
 
my $a = set <a b c>;
Line 4,525 ⟶ 6,627:
nok $a ⊂ $a, "strict subset; false for equal sets";
ok $a === set(<a b c>), "equality; true if every element of set A is in set B and vice-versa";
nok $a === $b, "equality; false for differing sets";</langsyntaxhighlight>
{{out}}
<pre>ok 1 - c is an element in set A
Line 4,541 ⟶ 6,643:
=={{header|REXX}}==
REXX doesn't have native set support, but can be easily coded to handle lists as sets.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates some common SET functions. */
truth.0= 'false'; truth.1= "true" /*two common names for a truth table. */
set.= /*the order of sets isn't important. */
Line 4,596 ⟶ 6,698:
if eq then if arg()>3 then return 1
else return set$('equal', _2, _1, 1)
return set.t</langsyntaxhighlight>
'''output'''
<pre>
Line 4,619 ⟶ 6,721:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Set
 
Line 4,733 ⟶ 6,835:
next
return flag
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,746 ⟶ 6,848:
Set A is not a subset of set B
Set A is not equal to set B
</pre>
 
=={{header|RPL}}==
RPL can handle lists, which are ordered sets. They can be created either by enumerating them:
{ "Azerty" #4 3.14 }
or by first pushing their components in the stack, then invoking the appropriate function:
"Azerty" #4 3.14 3 →LIST
{{works with|Halcyon Calc|4.2.7}}
We first need a command to remove an item for a list
≪ DUP2 1 + OVER SIZE SUB ROT ROT
IF DUP 1 == THEN DROP2 ELSE
1 SWAP 1 - SUB SWAP +
END
≫ '<span style="color:blue">POPL</span>' STO <span style="color:grey">@ ''( { a1 .. ak .. an } k → { a1 .. an } )''</span>
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ POS SIGN ≫ '<span style="color:blue">IN?</span>' STO
≪ → a b
≪ a 1 b SIZE '''FOR''' j
b j GET '''IF''' a OVER POS '''THEN''' DROP '''ELSE''' + '''END'''
'''NEXT'''
≫ ≫ '<span style="color:blue">UNION</span>' STO
≪ → a b
≪ { } b
1 a SIZE '''FOR''' j
a j GET
'''IF''' DUP2 POS '''THEN'''
LAST ROT SWAP <span style="color:blue">POPL</span>
ROT ROT + SWAP
'''ELSE''' DROP '''END'''
'''NEXT''' DROP
≫ ≫ ‘<span style="color:blue">INTER</span>’ STO
≪ → a b
≪ { } b
1 a SIZE '''FOR''' j
a j GET
'''IF''' DUP2 POS NOT '''THEN'''
LAST ROT SWAP <span style="color:blue">POPL</span>
ROT ROT + SWAP
'''ELSE''' DROP '''END'''
'''NEXT''' DROP
≫ ≫ ‘<span style="color:blue">DIFFL</span>’ STO
≪ → a b
≪ 1 CF 1 a SIZE '''FOR''' j
'''IF''' b a j GET POS NOT '''THEN''' 1 SF a SIZE 'j' STO '''END'''
'''NEXT''' 1 FC?
≫ ≫ '<span style="color:blue">INCL</span>'?' STO
≪ DUP2 '''INCL?''' ROT ROT SWAP '<span style="color:blue">DIFFL</span>' AND
≫ '<span style="color:blue">SAME?</span>' STO
|
<span style="color:blue">IN?</span> ''( {A} m -- boolean )'' // 1 if m ∈ A
<span style="color:blue">UNION</span> ''( {A} {B} -- {A ∪ B} )''
Scan {B}...
... and add to {A} all {B} items not already in {A}
<span style="color:blue">INTER</span> ''( {A} {B} -- {A ∩ B} )''
Put a copy of {B} in stack
Scan {A}
if {A} item in copy of {B}
remove it from copy of {B}
add it to result
<span style="color:blue">DIFFL</span> ''( {A} {B} -- {A ∖ B} )''
Put a copy of {B} in stack
Scan {A}
if {A} item not in copy of {B}
remove it from copy of {B}
add it to result
<span style="color:blue">INCL?</span> ''( {A} {B} -- boolean )'' // true if {A} ⊆ {B}
Scan {A}...
... and break loop if an {A} item is not in {B}
return flag 1, set if loop has been broken
<span style="color:blue">SAME</span> ''( {A} {B} -- boolean )'' // true if {A} = {B}
{A} = {B} <=> {A} ⊆ {B} and {B} ⊆ {A}
|}
 
{{in}}
<pre>
3 {1 2 3 4} IN?
{1 2 3 4} {3 5 6} UNION
{1 2 3 4} {3 5 6} INTER
{1 2 3 4} {3 5 6} DIFFL
{1 2} {1 2 3 4} INCL?
{1 2 3} {3 1 2} SAME?
 
</pre>
{{out}}
<pre>
6: 1
5: { 1 2 3 4 5 6 }
4: { 3 }
3: { 1 2 4 }
2: 1
1: 1
</pre>
 
=={{header|Ruby}}==
Ruby's standard library contains a "set" package, which provides <code>Set</code> and <code>SortedSet</code> classes.
<langsyntaxhighlight lang="ruby">>> require 'set'
=> true
>> s1, s2 = Set[1, 2, 3, 4], [3, 4, 5, 6].to_set # different ways of creating a set
Line 4,792 ⟶ 7,010:
>> s1.subtract(s2) # Mutability
=> #<Set: {1, 2}>
>> </langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">
<lang Runbasic>
A$ = "apple cherry elderberry grape"
B$ = "banana cherry date elderberry fig"
Line 4,865 ⟶ 7,083:
print left$(sets$,1);" is not equal ";right$(sets$,1)
end if
end function</langsyntaxhighlight>Output:
<pre>A = apple cherry elderberry grape
B = banana cherry date elderberry fig
Line 4,888 ⟶ 7,106:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">use std::collections::HashSet;
 
fn main() {
Line 4,902 ⟶ 7,120:
println!("Is A a subset of B? {}", a.is_subset(&b));
println!("Is A equal to B? {}", a == b);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">
object sets {
val set1 = Set(1,2,3,4,5)
Line 4,916 ⟶ 7,134:
println(set1 == set2)
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
Implemented based on lists. Not efficient on large sets.
<langsyntaxhighlight lang="lisp">(define (element? a lst)
(and (not (null? lst))
(or (eq? a (car lst))
Line 4,962 ⟶ 7,180:
(define (set-eq? a b)
(and (subset? a b)
(subset? b a)))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: charSet is set of char;
Line 4,990 ⟶ 7,208:
writeln("A < A -- proper subset: " <& A < A);
writeln("A = B -- equality: " <& A = B);
end func;</langsyntaxhighlight>
 
{{out}}
Line 5,008 ⟶ 7,226:
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">
<lang SETL>
A := {1, 2, 3, 4};
B := {3, 4, 5, 6};
Line 5,019 ⟶ 7,237:
print(C subset B); -- #T
print(C = B); -- #F
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">class MySet(*set) {
 
method init {
Line 5,087 ⟶ 7,305:
set.has(self)
}
}</langsyntaxhighlight>
 
Usage example:
<langsyntaxhighlight lang="ruby">var x = MySet(1, 2, 3)
5..7 -> each { |i| x += i }
 
Line 5,111 ⟶ 7,329:
say ("w = x ^ y = ", w = (x ^ y))
say ("w is ", w ≡ z ? "" : "not ", "equal to z")
say ("w is ", w ≡ x ? "" : "not ", "equal to x")</langsyntaxhighlight>
{{out}}
<pre>
Line 5,133 ⟶ 7,351:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">SIMSET
BEGIN
 
Line 5,335 ⟶ 7,553:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,355 ⟶ 7,573:
=={{header|Smalltalk}}==
{{works with|Pharo|1.3-13315}}
<langsyntaxhighlight lang="smalltalk">
#(1 2 3) asSet union: #(2 3 4) asSet.
"a Set(1 2 3 4)"
Line 5,376 ⟶ 7,594:
#(1 2 3) asSet = #(1 2 4) asSet.
"false"
</syntaxhighlight>
</lang>
 
=={{header|SQL}}==
{{works with|Oracle}}
<langsyntaxhighlight lang="sql">
-- set of numbers is a table
-- create one set with 3 elements
Line 5,464 ⟶ 7,682:
minus
select element from myset2));
</syntaxhighlight>
</lang>
 
<pre>
Line 5,631 ⟶ 7,849:
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<langsyntaxhighlight lang="swift">var s1 : Set<Int> = [1, 2, 3, 4]
let s2 : Set<Int> = [3, 4, 5, 6]
println(s1.union(s2)) // union; prints "[5, 6, 2, 3, 1, 4]"
Line 5,657 ⟶ 7,875:
println(s1) // prints "[2, 1]"
s1.exclusiveOrInPlace(s2) // mutability
println(s1) // prints "[5, 6, 2, 3, 1, 4]"</langsyntaxhighlight>
 
=={{header|Tcl}}==
Sets in Tcl are modeled as lists of items, with operations that preserve uniqueness of membership.
{{tcllib|struct::set}}
<langsyntaxhighlight lang="tcl">package require struct::set
 
# Many ways to build sets
Line 5,682 ⟶ 7,900:
struct::set exclude s3 $item
# Getting the cardinality:
puts "cardinality: [struct::set size $s3]</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">'Implementation of "set" using the built in Collection datatype.
'A collection can hold any object as item. The examples here are only strings.
'A collection stores item, key pairs. With the key you can retrieve the item.
Line 5,808 ⟶ 8,026:
'Add "10" to A
A.Add "10", "10"
End Sub</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-set}}
Note that the Set class in the above module uses a Map internally for storage. Consequently, iteration order is undefined.
<syntaxhighlight lang="wren">import "./set" for Set
 
var fruits = Set.new(["apple", "pear", "orange", "banana"])
System.print("fruits : %(fruits)")
var fruits2 = Set.new(["melon", "orange", "lemon", "gooseberry"])
System.print("fruits2 : %(fruits2)\n")
 
System.print("fruits contains 'banana' : %(fruits.contains("banana"))")
System.print("fruits2 contains 'elderberry' : %(fruits2.contains("elderberry"))\n")
 
System.print("Union : %(fruits.union(fruits2))")
System.print("Intersection : %(fruits.intersect(fruits2))")
System.print("Difference : %(fruits.except(fruits2))\n")
 
System.print("fruits2 is a subset of fruits : %(fruits2.subsetOf(fruits))\n")
var fruits3 = fruits.copy()
System.print("fruits3 : %(fruits3)\n")
System.print("fruits2 and fruits are equal : %(fruits2 == fruits)")
System.print("fruits3 and fruits are equal : %(fruits3 == fruits)\n")
 
var fruits4 = Set.new(["apple", "orange"])
System.print("fruits4 : %(fruits4)\n")
System.print("fruits3 is a proper subset of fruits : %(fruits3.properSubsetOf(fruits))")
System.print("fruits4 is a proper subset of fruits : %(fruits4.properSubsetOf(fruits))\n")
 
var fruits5 = Set.new(["cherry", "blueberry", "raspberry"])
System.print("fruits5 : %(fruits5)\n")
fruits5.add("guava")
System.print("fruits5 + 'guava' : %(fruits5)")
fruits5.remove("cherry")
System.print("fruits5 - 'cherry' : %(fruits5)")</syntaxhighlight>
 
{{out}}
<pre>
fruits : <banana, orange, pear, apple>
fruits2 : <lemon, gooseberry, orange, melon>
 
fruits contains 'banana' : true
fruits2 contains 'elderberry' : false
 
Union : <banana, lemon, gooseberry, orange, melon, pear, apple>
Intersection : <orange>
Difference : <banana, pear, apple>
 
fruits2 is a subset of fruits : false
 
fruits3 : <banana, orange, pear, apple>
 
fruits2 and fruits are equal : false
fruits3 and fruits are equal : true
 
fruits4 : <orange, apple>
 
fruits3 is a proper subset of fruits : false
fruits4 is a proper subset of fruits : true
 
fruits5 : <raspberry, blueberry, cherry>
 
fruits5 + 'guava' : <raspberry, guava, blueberry, cherry>
fruits5 - 'cherry' : <raspberry, guava, blueberry>
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang "XPL0">proc PrintBool(Str, Test);
int Str, Test;
[Text(0, Str);
Text(0, if Test then "true" else "false");
CrLf(0);
];
 
proc PrintSet(Str, Set, Names);
int Str, Set, Names, I;
[Text(0, Str);
for I:= 0 to 31 do
if 1<<I & Set then
[Text(0, Names(I)); ChOut(0, ^ )];
CrLf(0);
];
 
int Names, Fruits, Fruits2, Fruits3, Fruits4, Fruits5;
def Apple=1<<0, Pear=1<<1, Orange=1<<2, Banana=1<<3, Melon=1<<4, Lemon=1<<5,
Gooseberry=1<<6, Elderberry=1<<7, Raspberry=1<<8, Blueberry=1<<9,
Cherry=1<<10, Guava=1<<11;
[Names:= ["Apple", "Pear", "Orange", "Banana", "Melon", "Lemon", "Gooseberry",
"Elderberry", "Raspberry", "Blueberry", "Cherry", "Guava"];
Fruits:= Apple ! Pear ! Orange ! Banana;
PrintSet("Fruits : ", Fruits, Names);
Fruits2:= Melon ! Orange ! Lemon ! Gooseberry;
PrintSet("Fruits2 : ", Fruits2, Names);
CrLf(0);
PrintBool("Fruits contains 'Banana' : ", Fruits & Banana);
PrintBool("Fruits2 contains 'Elderberry' : ", Fruits2 & Elderberry);
CrLf(0);
PrintSet("Union : ", Fruits ! Fruits2, Names);
PrintSet("Intersection : ", Fruits & Fruits2, Names);
PrintSet("Difference : ", Fruits & ~Fruits2, Names);
CrLf(0);
PrintBool("Fruits2 is a subset of Fruits : ",
(Fruits2 & Fruits) # 0 & (Fruits2 & ~Fruits) = 0);
CrLf(0);
Fruits3:= Fruits;
PrintSet("Fruits3 : ", Fruits3, Names);
CrLf(0);
PrintBool("Fruits2 and Fruits are equal : ", Fruits2 = Fruits);
PrintBool("Fruits3 and Fruits are equal : ", Fruits3 = Fruits);
CrLf(0);
Fruits4:= Apple ! Orange;
PrintSet("Fruits4 : ", Fruits4, Names);
CrLf(0);
PrintBool("Fruits3 is a proper subset of Fruits : ",
(Fruits3 & Fruits) # 0 & (Fruits3 & ~Fruits) = 0 & Fruits3 # Fruits);
PrintBool("Fruits4 is a proper subset of Fruits : ",
(Fruits4 & Fruits) # 0 & (Fruits4 & ~Fruits) = 0 & Fruits4 # Fruits);
CrLf(0);
Fruits5:= Cherry ! Blueberry ! Raspberry;
PrintSet("Fruits5 : ", Fruits5, Names);
CrLf(0);
Fruits5:= Fruits5 + Guava;
PrintSet("Fruits5 + 'Guava' : ", Fruits5, Names);
Fruits5:= Fruits5 - Cherry; \Cherry better be present!
PrintSet("Fruits5 - 'Cherry' : ", Fruits5, Names);
]</syntaxhighlight>
{{out}}
<pre>
Fruits : Apple Pear Orange Banana
Fruits2 : Orange Melon Lemon Gooseberry
 
Fruits contains 'Banana' : true
Fruits2 contains 'Elderberry' : false
 
Union : Apple Pear Orange Banana Melon Lemon Gooseberry
Intersection : Orange
Difference : Apple Pear Banana
 
Fruits2 is a subset of Fruits : false
 
Fruits3 : Apple Pear Orange Banana
 
Fruits2 and Fruits are equal : false
Fruits3 and Fruits are equal : true
 
Fruits4 : Apple Orange
 
Fruits3 is a proper subset of Fruits : false
Fruits4 is a proper subset of Fruits : true
 
Fruits5 : Raspberry Blueberry Cherry
 
Fruits5 + 'Guava' : Raspberry Blueberry Cherry Guava
Fruits5 - 'Cherry' : Raspberry Blueberry Guava
</pre>
 
=={{header|zkl}}==
A simplistic implementation that is fine for smallish sets
<langsyntaxhighlight lang="zkl">var [const] unique = Utils.Helpers.listUnique;
class Set {
fcn init { var [const] set = (vm.arglist.copy() : unique(_)) }
Line 5,832 ⟶ 8,207:
}
fcn __opEQ(setB) { ((set.len() == setB.set.len()) and self.isSubset(setB)) }
}</langsyntaxhighlight>
<pre>
A := Set(1,2,3,3,3,4);
9,476

edits