RogerBW's Blog

On the Basics of Sets 30 September 2026

Sets (in the computering sense) are a useful thing, but they're a "new" (post-C) thing and so the syntax isn't standardised across languages the way it is for e.g. arrays. (In particular, they aren't available as standard in Perl, which has been my language of choice for many years.) So I thought I'd look at the way they work.

Conceptually they can be seen as a sort of second-class hash (dict, associative array): they have a list of keys, with no duplications, but they don't have values. So for example an easy way to remove duplicates from a list is to turn it into a set, then (since this will usually lose the order they were in) if necessary turn that set's keys back into a list and put them into whatever order is wanted.

In Rust they're std::collections::HashSet and the syntax is very similar to HashMap from the same library.

let mut h = HashSet::new()
h.insert(v);
h.remove(&v);
if h.contains(&v) { … }

What one can also do with a set, which makes less sense with a hash, is operations on the keys of two sets: equivalence, intersection (AND, key is in both), union (OR, key is in either or both), symmetric difference (XOR, key is in just one), difference (keys in A but not in B, A XOR (A AND B)), is-subset (A AND B == A), etc. In Rust again:

let diff: HashSet<_> = a.difference(&b).collect();
let inter: HashSet<_> = a.intersection(&b).collect();

etc.

JavaScript has a Set that has syntax like a hash. Python has a set similarly.

In Ruby one has to require 'set' but it's a core module. Intersection overloads the & operator. In Crystal, no need for the require but the syntax is the same.

In Raku there's a Set (immutable) and a SetHash (mutable), and intersection is (&).

In Kotlin and Scala they're the Set type (Scala gets strange about making them mutable, because really it doesn't like mutable variables at all).

Some languages don't have sets in the core at all (Perl, Lua, PostScript, Typst) but they can be faked by using hashes/dicts and ignoring the values. One does need to write the special extra operations of course. (My PostScript libraries include this.)

One can also extend this concept to a multiset or counter, in which the value for a key is the number of occurrences of that key in the overall set of data. (Which is trivially also a hash, but with its usage restricted in certain ways.) That's even less likely to be a core language feature, though Python has a Counter library.

Tags: computing

Add A Comment

Your Name
Your Email
Your Comment

Note that I will only approve comments that relate to the blog post itself, not ones that relate only to previous comments. This is to ensure that the blog remains outside the scope of the UK's Online Safety Act (2023).

Your submission will be ignored if any field is left blank, but your email address will not be displayed. Comments will be processed through markdown.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 2300ad 3d printing action advent of code adventure aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech bayern beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime crystal cthulhu eternal cycling dead of winter disaster doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 essen 2024 essen 2025 existential risk falklands war fandom fanfic fantasy feminism filk film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror horrorm science fiction hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo 2025 hugo 2026 hugo-nebula reread humour in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow openscad opera parody paul temple perl perl weekly challenge photography podcast poetry politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant review reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense talon television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 typst vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1