Enumerated typeIn computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, a status variable in the JOVIAL programming language, and a categorical variable in statistics) is a data type[a] consisting of a set of named values called elements, members, enumeral, or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. An enumerated type can be seen as a degenerate tagged union of unit type. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. In other words, an enumerated type has values that are different from each other, and that can be compared and assigned, but are not generally[b] specified by the programmer as having any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily. DescriptionFor example, the four suits in a deck of playing cards may be four enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named suit. If a variable V is declared having suit as its data type, one can assign any of those four values to it. Although the enumerators are usually distinct, some languages may allow the same enumerator to be listed twice in the type's declaration. The names of enumerators need not be semantically complete or compatible in any sense. For example, an enumerated type called color may be defined to consist of the enumerators Red, Green, Zebra, Missing, and Bacon. In some languages, the declaration of an enumerated type also intentionally defines an ordering of its members (High, Medium and Low priorities); in others, the enumerators are unordered (English, French, German and Spanish supported languages); in others still, an implicit ordering arises from the compiler concretely representing enumerators as integers. Some enumerator types may be built into the language. The Boolean type, for example is often a pre-defined enumeration of the values False and True. A unit type consisting of a single value may also be defined to represent null. Many languages allow users to define new enumerated types. Values and variables of an enumerated type are usually implemented with some integer type as the underlying representation. Some languages, especially system programming languages, allow the user to specify the bit combination to be used for each enumerator, which can be useful to efficiently represent sets of enumerators as fixed-length bit strings. In type theory, enumerated types are often regarded as tagged unions of unit types. Since such types are of the form , they may also be written as natural numbers. RationaleSome early programming languages did not originally have enumerated types. If a programmer wanted a variable, for example myColor, to have a value of red, the variable red would be declared and assigned some arbitrary value, usually an integer constant. The variable red would then be assigned to myColor. Other techniques assigned arbitrary values to strings containing the names of the enumerators. These arbitrary values were sometimes referred to as magic numbers since there often was no explanation as to how the numbers were obtained or whether their actual values were significant. These magic numbers could make the source code harder for others to understand and maintain. Enumerated types, on the other hand, make the code more self-documenting. Depending on the language, the compiler could automatically assign default values to the enumerators thereby hiding unnecessary detail from the programmer. These values may not even be visible to the programmer (see information hiding). Enumerated types can also prevent a programmer from writing illogical code such as performing mathematical operations on the values of the enumerators. If the value of a variable that was assigned an enumerator were to be printed, some programming languages could also print the name of the enumerator rather than its underlying numerical value. A further advantage is that enumerated types can allow compilers to enforce semantic correctness. For instance:
Conceptually, an enumerated type is similar to a list of nominals (numeric codes), since each possible value of the type is assigned a distinctive natural number. A given enumerated type is thus a concrete implementation of this notion. When order is meaningful and/or used for comparison, then an enumerated type becomes an ordinal type. ConventionsProgramming languages tend to have their own, oftentimes multiple, programming styles and naming conventions. The variable assigned to an enumeration is usually a noun in singular form, and frequently follows either a PascalCase or uppercase convention, while lowercase and others are seen less frequently. Syntax in several programming languagesPascal and syntactically similar languagesPascalIn Pascal, an enumerated type can be implicitly declared by listing the values in a parenthesised list: var
suit: (clubs, diamonds, hearts, spades);
The declaration will often appear in a type synonym declaration, such that it can be used for multiple variables: type
cardsuit = (clubs, diamonds, hearts, spades);
card = record
suit: cardsuit;
value: 1 .. 13;
end;
var
hand: array [ 1 .. 13 ] of card;
trump: cardsuit;
The order in which the enumeration values are given matters. An enumerated type is an ordinal type, and the Pascal style languages also allow enumeration to be used as array index: var
suitcount: array [cardsuit] of integer;
AdaIn Ada, the use of "=" was replaced with "is" leaving the definition quite similar: type Cardsuit is (clubs, diamonds, hearts, spades);
In addition to Similar to C-style languages Ada allows the internal representation of the enumeration to be specified: for Cardsuit use
(clubs => 1, diamonds => 2, hearts => 4, spades => 8);
Unlike C-style languages Ada also allows the number of bits of the enumeration to be specified: for Cardsuit'Size use 4; -- 4 bits
Additionally, one can use enumerations as indexes for arrays, like in Pascal, but there are attributes defined for enumerations Shuffle : constant array(Cardsuit) of Cardsuit :=
(Clubs => Cardsuit'Succ(Clubs), -- see attributes of enumerations 'First, 'Last, 'Succ, 'Pred
Diamonds => Hearts, --an explicit value
Hearts => Cardsuit'Last, --first enumeration value of type Cardsuit e.g., clubs
Spades => Cardsuit'First --last enumeration value of type Cardsuit e.g., spades
);
Like Modula-3 Ada treats type Cards is ('7', '8', '9', 'X', 'J', 'Q', 'K', 'A');
C and syntactically similar languagesCThe original K&R dialect of the programming language C had no enumerated types.[1] In C, enumerations are created by explicit definitions (the enum cardsuit {
Clubs,
Diamonds,
Hearts,
Spades
};
struct card {
enum cardsuit suit;
short int value;
} hand[13];
enum cardsuit trump;
C exposes the integer representation of enumeration values directly to the programmer. Integers and enum values can be mixed freely, and all arithmetic operations on enum values are permitted. It is even possible for an enum variable to hold an integer that does not represent any of the enumeration values. In fact, according to the language definition, the above code will define C also allows the programmer to choose the values of the enumeration constants explicitly, even without type. For example, enum cardsuit {
Clubs = 1,
Diamonds = 2,
Hearts = 4,
Spades = 8
};
could be used to define a type that allows mathematical sets of suits to be represented as an Since C23, the underlying type of an enumeration can be specified by the programmer:[2] enum cardsuit : char {
Clubs = 1,
Diamonds = 2,
Hearts = 4,
Spades = 8
};
C#Enumerated types in the C# programming language preserve most of the "small integer" semantics of C's enums. Some arithmetic operations are not defined for enums, but an enum value can be explicitly converted to an integer and back again, and an enum variable can have values that were not declared by the enum definition. For example, given enum Cardsuit
{
Clubs,
Diamonds,
Spades,
Hearts
}
the expressions C# also provides the C-like feature of being able to define specific integer values for enumerations. By doing this it is possible to perform binary operations on enumerations, thus treating enumeration values as sets of flags. These flags can be tested using binary operations or with the enum type's builtin 'HasFlag' method.[3] The enumeration definition defines names for the selected integer values and is syntactic sugar, as it is possible to assign to an enum variable other integer values that are not in the scope of the enum definition.[4][5][6] C++C++ has enumeration types that are directly inherited from C's and work mostly like these, except that an enumeration is a real type in C++, giving added compile-time checking. Also (as with structs), the C++ C++11 also provides a second kind of enumeration, called a scoped enumeration. These are type-safe: the enumerators are not implicitly converted to an integer type. Among other things, this allows I/O streaming to be defined for the enumeration type. Another feature of scoped enumerations is that the enumerators do not leak, so usage requires prefixing with the name of the enumeration (e.g., enum class Color {Red, Green, Blue};
The underlying type of an enumeration is an implementation-defined integral type that is large enough to hold all enumerated values; it does not have to be the smallest possible type. The underlying type can be specified directly, which allows "forward declarations" of enumerations: enum class Color : long {Red, Green, Blue}; // must fit in size and memory layout the type 'long'
enum class Shapes : char; // forward declaration. If later there are values defined that don't fit in 'char' it is an error.
GoGo uses the type ByteSize int
const (
_ = iota // ignore first value by assigning to blank identifier; 0
KB ByteSize = 1 << (10 * iota) // 1 << (10 * 1) == 1 << 10 == 1024; in binary 10000000000
MB // 1 << (10 * 2) == 1048576; in binary 100000000000000000000
GB // 1 << (10 * 3) == 1073741824; in binary 1000000000000000000000000000000
)
Java![]() The J2SE version 5.0 of the Java programming language added enumerated types whose declaration syntax is similar to that of C: enum Cardsuit { CLUBS, DIAMONDS, SPADES, HEARTS };
...
Cardsuit trump;
The Java type system, however, treats enumerations as a type separate from integers, and intermixing of enum and integer values is not allowed. In fact, an enum type in Java is actually a special compiler-generated class rather than an arithmetic type, and enum values behave as global pre-generated instances of that class. Enum types can have instance methods and a constructor (the arguments of which can be specified separately for each enum value). All enum types implicitly extend the Internally, each enum value contains an integer, corresponding to the order in which they are declared in the source code, starting from 0. The programmer cannot set a custom integer for an enum value directly, but one can define overloaded constructors that can then assign arbitrary values to self-defined members of the enum class. Defining getters allows then access to those self-defined members. The internal integer can be obtained from an enum value using the The Java standard library provides utility classes to use with enumerations. The PerlDynamically typed languages in the syntactic tradition of C (e.g., Perl or JavaScript) do not, in general, provide enumerations. But in Perl programming the same result can be obtained with the shorthand strings list and hashes (possibly slices): my @enum = qw(Clubs Diamonds Hearts Spades);
my( %set1, %set2 );
@set1{@enum} = (); # all cleared
@set2{@enum} = (1) x @enum; # all set to 1
$set1{Clubs} ... # false
$set2{Diamonds} ... # true
RakuRaku (formerly known as Perl 6) supports enumerations. There are multiple ways to declare enumerations in Raku, all creating a back-end Map. enum Cat <sphynx siamese bengal shorthair other>; # Using "quote-words"
enum Cat ('sphynx', 'siamese', 'bengal', 'shorthair', 'other'); # Using a list
enum Cat (sphynx => 0, siamese => 1, bengal => 2, shorthair => 3, other => 4); # Using Pair constructors
enum Cat (:sphynx(0), :siamese(1), :bengal(2), shorthair(3), :other(4)); # Another way of using Pairs, you can also use `:0sphynx`
PHPEnums were added in PHP version 8.1. enum CardSuit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
Enumerators may be backed by string or integer values to aid serialization: enum CardSuit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
The Enum's interface exposes a method that gives a collection of its enumerators and their names. String/integer-backed Enums also expose the backing value and methods to (attempt) deserialization. Users may add further methods. RustThough Rust uses the enum Message {
Quit,
Move { x: i32, y: i32 }, // struct
Write(String), // single-element tuple
ChangeColor(i32, i32, i32), // three-element tuple
}
Like C, Rust also supports specifying the values of each variant, pub enum Weekday {
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
}
SwiftIn C, enumerations assign related names to a set of integer values. In Swift, enumerations are much more flexible and need not provide a value for each case of the enumeration. If a value (termed a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type. Alternatively, enumeration cases can specify associated values of any type to be stored along with each different case value, much as unions or variants do in other languages. One can define a common set of related cases as part of one enumeration, each of which has a different set of values of appropriate types associated with it. In Swift, enumerations are a first-class type. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration's current value, and instance methods to provide functionality related to the values the enumeration represents. Enumerations can also define initializers to provide an initial case value and can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality. enum CardSuit {
case clubs
case diamonds
case hearts
case spades
}
Unlike C and Objective-C, Swift enumeration cases are not assigned a default integer value when they are created. In the CardSuit example above, clubs, diamonds, hearts, and spades do not implicitly equal 0, 1, 2 and 3. Instead, the different enumeration cases are fully-fledged values in their own right, with an explicitly-defined type of CardSuit. Multiple cases can appear on a single line, separated by commas: enum CardSuit {
case clubs, diamonds, hearts, spades
}
When working with enumerations that store integer or string raw values, one doesn't need to explicitly assign a raw value for each case because Swift will automatically assign the values. For instance, when integers are used for raw values, the implicit value for each case is one more than the previous case. If the first case doesn't have a value set, its value is 0. For the CardSuit example, suits can be numbered starting from 1 by writing: enum CardSuit {
case clubs = 1, diamonds, hearts, spades
}
TypeScriptTypeScript adds an 'enum' data type to JavaScript. enum Cardsuit {Clubs, Diamonds, Hearts, Spades};
var c: Cardsuit = Cardsuit.Diamonds;
By default, enums number members starting at 0; this can be overridden by setting the value of the first: enum Cardsuit {Clubs = 1, Diamonds, Hearts, Spades};
var c: Cardsuit = Cardsuit.Diamonds;
All the values can be set: enum Cardsuit {Clubs = 1, Diamonds = 2, Hearts = 4, Spades = 8};
var c: Cardsuit = Cardsuit.Diamonds;
TypeScript supports mapping the numeric value to its name. For example, this finds the name of the value 2: enum Cardsuit {Clubs = 1, Diamonds, Hearts, Spades};
var suitName: string = Cardsuit[2];
alert(suitName);
Python
An from enum import Enum
class Cards(Enum):
CLUBS = 1
DIAMONDS = 2
HEARTS = 3
SPADES = 4
There is also a functional API for creating enumerations with automatically generated indices (starting with one): Cards = Enum("Cards", "CLUBS DIAMONDS HEARTS SPADES")
Python enumerations do not enforce semantic correctness (a meaningless comparison to an incompatible enumeration always returns False rather than raising a TypeError): >>> Color = Enum("Color", "RED GREEN BLUE")
>>> Shape = Enum("Shape", ["CIRCLE", "TRIANGLE", "SQUARE", "HEXAGON"])
>>> def has_vertices(shape):
... return shape != Shape.CIRCLE
...
>>> has_vertices(Color.GREEN)
True
FortranFortran only has enumerated types for interoperability with C; hence, the semantics is similar to C and, as in C, the enum values are just integers and no further type check is done. The C example from above can be written in Fortran as enum, bind( C )
enumerator :: CLUBS = 1, DIAMONDS = 2, HEARTS = 4, SPADES = 8
end enum
Visual Basic/VBAEnumerated datatypes in Visual Basic (up to version 6) and VBA are automatically assigned the " 'Zero-based
Enum CardSuit
Clubs
Diamonds
Hearts
Spades
End Enum
Sub EnumExample()
Dim suit As CardSuit
suit = Diamonds
MsgBox suit
End Sub
Example Code in VB.NET Enum CardSuit
Clubs
Diamonds
Hearts
Spades
End Enum
Sub EnumExample()
Dim suit As CardSuit
suit = CardSuit.Diamonds
MessageBox.show(suit)
End Sub
LispCommon Lisp uses the member type specifier, e.g., (deftype cardsuit ()
'(member club diamond heart spade))
that states that object is of type cardsuit if it is Additionally, (deftype finite-element-set-type (&rest elements)
`(member ,@elements))
may be used to define arbitrary enumerated types at runtime. For instance (finite-element-set-type club diamond heart spade)
would refer to a type equivalent to the prior definition of cardsuit, as of course would simply have been using (member club diamond heart spade)
but may be less confusing with the function DartDart has a support for the most basic form of enums and has a syntax that is a lot similar with other languages supporting enums. enum CardSuite {
Clubs,
Diamonds,
Hearts,
Spades
}
void main() {
CardSuite card = CardSuite.Clubs;
// Dart uses the "switch" operator to match the value of an enum with the desired output.
switch (card) {
case CardSuite.Clubs: {
print("Clubs");
}
break;
case CardSuite.Diamonds: {
print("Diamonds");
}
break;
case CardSuite.Hearts: {
print("Hearts");
}
break;
case CardSuite.Spades: {
print("Spades");
}
break;
default: {
print("Unknown");
}
break;
}
}
Note that before Dart 3[11], the switch operator did not guarantee the completeness of the cases. This means if you omit one case, the compiler will not raise an error. Algebraic data type in functional programmingIn functional programming languages in the ML lineage (e.g., Standard ML (SML), OCaml, and Haskell), an algebraic data type with only nullary constructors can be used to implement an enumerated type. For example (in the syntax of SML signatures): datatype cardsuit = Clubs | Diamonds | Hearts | Spades
type card = { suit: cardsuit; value: int }
val hand : card list
val trump : cardsuit
In these languages the small-integer representation is completely hidden from the programmer, if indeed such a representation is employed by the implementation. However, Haskell has the DatabasesSome databases support enumerated types directly. MySQL provides an enumerated type Example: CREATE TABLE shirts (
name VARCHAR(40),
size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);
JSON SchemaCan be defined in JSON schema using the "enum" keyword.[13] {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"cardsuit": {
"type": "string",
"enum": ["Clubs", "Diamonds", "Hearts", Spades"]
}
},
"required": ["cardsuit"]
}
XML SchemaXML Schema supports enumerated types through the enumeration facet used for constraining most primitive datatypes such as strings. <xs:element name="cardsuit">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Clubs"/>
<xs:enumeration value="Diamonds"/>
<xs:enumeration value="Hearts"/>
<xs:enumeration value="Spades"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
See alsoNotesReferences
External linksThe Wikibook Ada Programming has a page on the topic of: Enumeration |
Portal di Ensiklopedia Dunia