r/ProgrammingLanguages • u/PitifulTheme411 ... • Mar 01 '26
Discussion Is there an "opposite" to enums?
We all know and love enums, which let you choose one of many possible variants. In some languages, you can add data to variants. Technically these aren't pure enums, but rather tagged unions, but they do follow the idea of enums so it makes sense to consider them as enums imo.
However, is there any kind of type or structure that lets you instead choose 0 or more of the given variants? Or 1 or more? Is there any use for this?
I was thinking about it, and thought it could work as a "flags" type, which you could probably implement with something like a bitflags value internally.
So something like
flags Lunch {
Sandwich,
Pasta,
Salad,
Water,
Milk,
Cookie,
Chip
}
let yummy = Sandwich | Salad | Water | Cookie;But then what about storing data, like the tagged union enums? How'd that work? I'd imagine probably the most useful method would be to have setting a flag allow you to store the associated data, but the determining if the flag is set would probably only care about the flag.
And what about allowing 1 or more? This would allow 0 or more, but perhaps there would be a way to require at least one set value?
But I don't really know. Do you think this has any use? How should something like this work? Are there any things that would be made easier by having this structure?
33
u/anterak13 Mar 01 '26
The opposite of enums are structs (a cartesian product type) both combined they give you algebraic data types (sums of products of sums of products … etc)
29
u/hairytim Mar 01 '26
From the bitvector/flags idea, it sounds like you are interested in constructing values that roughly correspond to sets. Your 'yummy’ could be thought of as having the type Set(Lunch), and a bitvector is one possible implementation of such a type (essentially, storing one boolean for every possible member)
If you try to generalize this to enums that carry data (I.e., algebraic data types), AFAIK, the best you can do is actually just store the members of the set. It’s possible that you might be able to derive something more efficient in particular special cases… not sure.
51
u/xeyalGhost Mar 01 '26
We could call it a cocoproduct.
15
u/cheeze2000 Mar 01 '26
in c#, these are still called enums but with the [Flags] attribute
63
u/sagittarius_ack Mar 01 '26
The generalization of
enums, sometimes calledtagged unions, are calledsum types.Sum typesare also calledcoproduct types. The dual (or opposite) ofcoproduct typesareproduct types.Recordsandtuplesare examples ofproduct types.This can be done by combining sum types and product types.
12
u/michaelquinlan Mar 01 '26
Yes, it is a collection.
9
u/SadPie9474 Mar 01 '26
The opposite is generally going to be a record type, where the fields/keys correspond to what the variants were in enum form
8
u/Hixie Mar 01 '26
Pascal has this as the
setprimitive. It's quite powerful.6
u/CommonNoiter Mar 01 '26
It's a product of bools.
6
u/tmzem Mar 01 '26
It's just a set of enum values. If the enum values are represented by ints which are powers of 2, such a set can be implemented very efficiently. Even with default representation (starting at 0 counting up) you can do such sets pretty efficiently.
For example, if your compiler implicitly implemented appropriate marker interfaces for such enum types, you could even implement it as a proper set type:
5
u/tobega Mar 01 '26
In Java, I have had great use for EnumSet and EnumMap, which I think corresponds well with what you are asking about.
4
u/AdreKiseque Mar 01 '26
You can do this with bitmasking. I don't know any languages that have it as a primitive or standard library type, though.
3
u/theangryepicbanana Star Mar 01 '26
My language Star actually has this!!, including support for enums holding values (really just represented as a hashmap in the vm, but I'll come up with something better eventually)
3
u/glukianets Mar 01 '26
Swift models this with ‘OptionSet’ protocol, which is not strictly a separate kind of type, but I think it’s curious how it combines several other language features to give you the same semantics
3
u/muchadoaboutsodall Mar 01 '26
C# can do this with enums. You just have to add a ‘bitfield’ attribute to the enum.
3
u/Entaloneralie Mar 01 '26 edited Mar 01 '26
Multisets to the rescue!
For example, the number 18(2 * 3 * 3) contains two 3s and one 2. Asking the number 18 if it contains 3s, is
Now you can name each prime a different thing than a number.
3
u/WittyStick Mar 01 '26 edited Mar 01 '26
In the logic/set perspective, a sum type/tagged union represents an exclusive disjunction of its constructors.
An "opposite" to this would be a biconditional type.
Which would represent "All or nothing" - a type which is either both
AandBtogether, or any other value which is neitherAnorB.However, this isn't the kind of type you want. If you want one or more of the value, you just want a union, which isn't an "opposite" of a tagged union, but a supertype of it.
If we consider
Lunchto be a structure like follows:The unions are the values where one or more of the bools are true.
The tagged unions represent the values where only one of the bools is true.
Conversely, the biconditional is the case where all of the bools have the same value.
Which essentially means a value is valid if all of the fields are present, or if none of the fields are present. Which basically implies a product type:
But it also includes a singleton value where all of the bools are false - ie, an uninhabited or uninitialized value of the type, which we might call
null_lunch.2
u/AnArmoredPony Mar 01 '26
it lowkey looks like a set
2
u/nekokattt Mar 01 '26
This looks like EnumSet in Java
2
u/DogObvious5799 Mar 01 '26
This is just a tuple of booleans. The nonzero condition seems like a dependent type
2
u/porky11 Mar 01 '26
I guess that would really be good as a language feature. I always program this myself using bitsets.
2
u/mgruner Mar 01 '26
those are called flags, an are implemented using an enum
2
u/al2o3cr Mar 01 '26
The "0 or more flags with optional data" concept reminds me of Erlang's proplists:
https://www.erlang.org/doc/apps/stdlib/proplists.html
TLDR a proplist is a list of terms that can have two possible shapes:
{atom, value}The first bare-atom form is treated like
{atom, true}by lookup operations.These aren't strictly-typed, but Dialyzer is pretty good at spotting cases where a proplist passed to a function doesn't match its typespec.
2
u/silverscrub Mar 02 '26
Scala has Set and Intersection types. Both can be used depending on what the use-case is.
1
u/l_am_wildthing Mar 01 '26 edited Mar 01 '26
did something like this for my parser:
1
u/Meistermagier Mar 01 '26
Wouldn't purely implementation wise. Syntax Sugar aside this just be a List (or Vector) of the enum type?
1
u/Goobyalus Mar 01 '26
FWIW this is what exists in Python: https://docs.python.org/3/library/enum.html#enum.Flag
Gives:
1
u/Dannyboiii12390 Mar 01 '26
// Source - https://stackoverflow.com/a/1448478 // Posted by eidolon, modified by community. See post 'Timeline' for change history // Retrieved 2026-03-01, License - CC BY-SA 4.0
You could do this. Then to test it in an if statement
if(Seahawk.flags && target_flags == target_flags)1
u/marshaharsha Mar 01 '26
My addled thought: The reason it’s practical to add data to the tag of an enum is that it’s easy for the compiler to compute the max size over all the variants, and that max size becomes the size of the overall type. Even at this unsophisticated level of type design, there is a problem of wasted space when, say, an array of Option<LargeType> that holds mostly Nones is using a LargeType’s space to hold each dataless None.
When you get all so-phist-eye-ca-ted and try to add data to a bitset, you’re going to waste a lot of space, unless you can somehow get some cancellation going on, where “presence” of certain bits causes “departure” of certain data, rather than always accreting data. The best I can do in this line is chemistry, but I can’t work out any useful details. My idea is that setting certain bits means adding certain ingredients to a reaction, which produces both components that you care about and components that you don’t, maybe because they boil off (the ultimate cancellation) or are water or something else boring. So you can still end up with a manageable amount of data after adding bits.
Good luck finding your own sorts of cancellation!
1
u/ern0plus4 Mar 01 '26
Of course, you should take care of word size.
1
u/kaisadilla_ Judith lang Mar 02 '26
That's just a set of values. As in,
var set: Set<Lunch> = [Sandwich, Salad, Water, Cookie]. Bit masks would be the more efficient version of this, but limited to very few options. This is quite common in low level programming. In languages like C#, where enums are just numbers under the hood, you can do exactly what you did with an enum if you ensure the value of each enum is a power of two (because you are literally doing bit masks).1
u/z-shang Mar 02 '26
you will just end up with a n bit int for n variants to check for at least 1 option is set just throw a popcnt to it
1
u/modelithe Mar 02 '26
Modula-2 has the
SETandPACKEDSET, allowing flags to be represented as bits in an efficient matter.Similarily, Rust has the enumset crate, allowing the creation of a set of
enumto be packed as bits in an efficient matter.1
u/yjlom Mar 02 '26
I don't think you can make an efficient representation for scalar payload-carrying bitsets.
For arrays if you're willing to sacrifice random access, you could either have side arrays and increment separate indices (though that'd add a lot of register pressure) or store the payloads behind the bitset and get the field and next element locations either with LUTs (though that gets out of hands if you have many flags) or by making each payload the same size and using masks and popcount (though that might waste a lot of space).
In general though, this is probably a better fit for an ECS architecture.
1
u/pr06lefs Mar 03 '26 edited Mar 03 '26
in elm, could do
thought actually you'd have to make a set with 'comparables', ie Int, String, something with eq and <. You need a fn to go from LunchItem to comparable and back. In rust you'd have a trait for the enum to implement eq and so forth.
Its also possible to make List like data structure that always contains at least one item, a non-empty list.
1
u/lassehp Mar 03 '26
COBOL has level 88 fields. (Disclaimer, I've never actually programmed in COBOL, and I barely understand it, but I find level 88 fascinating, and wonder how it could be implemented in a modern language.)
This example really doesn't do COBOL justice, I found this: https://keyholesoftware.com/from-relic-to-relevance-cobols-88-level-fields-for-modern-coders/ which seems to use the 88 fields to transform 2-digit years to 4-digit years depending on which range the year is in.
If you have a field definition with some 88 level fields attached, like:
the level 88 fields can work as conditions, so I suppose you could do something like:
1
u/Toothpick_Brody Mar 03 '26
Enums/sum types are dual to product types, so a lot of people are answering that. But dual isn’t necessarily the same as opposite.
Personally, I see enums as opposite to ranges/refinement. An enum has form “a or b”, and a range has form “a but not b”
-7
u/Arakela Mar 01 '26 edited Mar 01 '26
Why doesn't my language let data carry its own optionality?
The answer is that data can express its own behaviour. Any data can be converted into a living thing with its own will, step-by-step, traversal-pluggable. Nobody told the monkeys: they don't need an AST.
In the following example, a value yumme is represented as a traversable computation that describes its own optionality. We can pass the value of yumme around as a typed step pointer, fully presenting its nature as a type signature.
To observe yumme and act accordingly, we are required to construct a computation with typed steps that yumme/data dictates. This drags us out of our comfort zone, a composition described as code snippets wired by a single stack return semantic.
The following example demonstrates the computation machine of a concrete value. One of the interesting properties: it defines a universal boundary and gives consumers an exact contract on how to bind itself to interact.
How can we imagine language features that allow the composition of bounded computations with exactly defined cases?
The flag type you were dreaming of already exists. The language is C. It just never told anyone because C doesn't talk. It steps.
5
u/[deleted] Mar 01 '26
[removed] — view removed comment