Cycle index: Difference between revisions

From formulasearchengine
Jump to navigation Jump to search
en>Giftlite
 
en>Bilingsley
Line 1: Line 1:
Hi there, I am Alyson Boon although it is not the name on my beginning certificate. Distributing manufacturing is exactly where her primary earnings comes from. Her family members life in Ohio. To perform lacross is some thing he would by no means give up.<br><br>My blog post; love psychics ([http://Myoceancounty.net/groups/apply-these-guidelines-when-gardening-and-grow/ Myoceancounty.net])
In [[computer programming]], an '''enumerated type''' (also called '''enumeration''' or '''enum''', or '''factor''' in the [[R programming language]], and a [[categorical variable]] in statistics) is a [[data type]] consisting of a set of named [[value (computer science)|values]] called '''elements''', '''members'''  or '''enumerators''' of the type. The enumerator names are usually [[identifier]]s that behave as [[constant (programming)|constants]] in the language. A [[variable (computer science)|variable]] that has been [[declaration (computer science)|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 which are not specified by the programmer  as having any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily.
 
For example, the four [[Suit (cards)|suits]] in a deck of playing cards may be four enumerators named ''CLUB'', ''DIAMOND'', ''HEART'', ''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 [[total order|ordering]] of its members; in others, the enumerators are unordered; in others still, an implicit ordering arises from the compiler concretely representing enumerators as integers.
 
Some enumerator types may be [[built-in type|built into]] the language. The [[Boolean type]], for example is often a pre-defined enumeration of the values ''FALSE'' and ''TRUE''. Many languages allow the user to define new enumerated types.
 
Values and variables of an enumerated type are usually implemented as fixed-length [[bit string]]s, often in a format and size compatible with some [[integer (computer science)|integer]] type. Some languages, especially [[system programming language]]s, allow the user to specify the bit combination to be used for each enumerator. In [[type theory]], enumerated types are often regarded as [[tagged union]]s of [[unit type]]s. Since such types are of the form <math>1 + 1 + \cdots + 1</math>, they may also be written as natural numbers.
 
==Rationale==
Some 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 as [[magic number (programming)|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, made 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:<br>
<code>
myColor = TRIANGLE
</code><br>
can be forbidden, whilst <br>
<code>
myColor = RED
</code><br>
is accepted, even if ''TRIANGLE'' and ''RED'' are both internally represented as ''1''.
 
Conceptually, an enumerated type is similar to a list of [[nominal number|nominals]], 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 number|ordinal]] type.
 
== Conventions ==
 
In some [[Programming style|programming conventions]], enumerators are conventionally written with upper case letters to indicate they are constants.<!-- This is by no means universal, or even common.-->
 
== Pascal and syntactically similar languages ==
 
In [[Pascal programming language|Pascal]], an enumerated type can be implicitly declared by listing the values in a parenthesised list:
  <source lang=Pascal>
  var
    suit: (clubs, diamonds, hearts, spades);
  </source>
The declaration will often appear in a type synonym declaration, such that it can be used for multiple variables:
 
<source lang=Pascal>
  type
    cardsuit = (clubs, diamonds, hearts, spades);
    card = record
            suit: cardsuit;
            value: 1 .. 13;
          end;
  var
    hand: array [ 1 .. 13 ] of card;
    trump: cardsuit;
</source>
 
The order in which the enumeration values are given matters. An enumerated type is an ordinal type, and the <code>pred</code> and <code>succ</code> functions will give the prior or next value of the enumeration, and <code>ord</code> can convert enumeration values to their integer representation. Standard Pascal does not offer a conversion from arithmetic types to enumerations, however. Extended Pascal offers this functionality via an extended <code>succ</code> function. Some other Pascal dialects allow it via type-casts. Some modern descendants of Pascal, such as [[Modula-3]], provide a special conversion syntax using a method called <code>VAL</code>; Modula-3 also treats <code>BOOLEAN</code> and <code>CHAR</code> as special pre-defined enumerated types and uses <code>ORD</code> and <code>VAL</code> for standard [[ASCII]] decoding and encoding.
 
Pascal style languages also allow for enumeration to be used as array index
 
  <source lang=Pascal>
  var
    suitcount: array [cardsuit] of integer;
  </source>
 
=== Ada ===
 
In [[Ada programming language|Ada]], the use of "=" was replaced with "is" leaving the definition quite similar:
 
<source lang=Ada>type Cardsuit is (clubs, diamonds, hearts, spades);</source>
 
In addition to <code>Pred</code>, <code>Succ</code>, <code>Val</code> and <code>Pos</code> Ada also supports simple string conversions via <code>Image</code> and <code>Value</code>.
 
Similar to C-style languages Ada allows the internal representation of the enumeration to be specified:
 
<source lang=Ada>
for Cardsuit use
  (clubs => 1, diamonds => 2, hearts => 4, spades => 8);
</source>
 
Unlike C-style languages Ada also allows the number of bits of the enumeration to be specified:
 
  <source lang=Ada>for Cardsuit'Size use 4;  -- 4 bits</source>
 
Even more, you can use enumerations as indexes for arrays like Pascal, but there are attributes defined for enumerations
<source lang=Ada>
  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
      );
</source>
 
Like [[Modula-3]] Ada treats <code>Boolean</code> and <code>Character</code> as special pre-defined (in package "<code>Standard</code>") enumerated types. Unlike Modula-3 one can also define own character types:
 
<source lang=Ada>type Cards is ('7', '8', '9', 'J', 'Q', 'K', 'A');</source>
 
== C and syntactically similar languages ==
 
The original [[K&R C|K&R]] dialect of the [[C programming language]] did not have enumerated types, but they were added in the [[ANSI]] standard for C, which became [[C89 (C version)|C89]]. In C, enumerations are created by explicit definitions, which use the <code>enum</code> keyword and are reminiscent of struct and union definitions:
 
<source lang=C>
enum cardsuit {
  CLUBS,
  DIAMONDS,
  HEARTS,
  SPADES
};
 
struct card {
  enum cardsuit suit;
  short int value;
} hand[13];
 
enum cardsuit trump;
</source>
 
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 <code>CLUBS</code>, <code>DIAMONDS</code>, <code>HEARTS</code>, and <code>SPADES</code> as constants of type int</code>, which will only be converted (silently) to <code>enum cardsuit</code> if they are stored in a variable of that type.
 
C also allows the programmer to choose the values of the enumeration constants explicitly, even without type. For example,
 
<source lang=C>
enum cardsuit {
    CLUBS    = 1,
    DIAMONDS = 2,
    HEARTS  = 4,
    SPADES  = 8
};
</source>
 
could be used to define a type that allows mathematical sets of suits to be represented as an <code>enum cardsuit</code> by bitwise logic operations.
 
Dynamically typed languages in the syntactic tradition of C (e.g., [[Perl]] or [[JavaScript]]) do not, in general, provide enumerations.  But in Perl programming you can obtain the same result with the shorthand [[String_literal|strings]] [[List_(abstract_data_type)|list]] and [[Hash_table|hashes]] (possibly [[Array_slicing|slices]]):
 
<source lang=C>
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
</source>
 
===C#===
 
Enumerated types in the [[C Sharp (programming language)|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
 
<source lang=CSharp>enum Cardsuit { Clubs, Diamonds, Spades, Hearts };</source>
 
the expressions <code lang=CSharp>CardSuit.Diamonds + 1</code> and <code lang=CSharp>CardSuit.Hearts - CardSuit.Clubs</code> are allowed directly (because it makes sense to step through the sequence of values or ask how many steps there are between two values), but <code lang=CSharp>CardSuit.Hearts*CardSuit.Spades</code> is deemed to make less sense and is only allowed if the values are first converted to integers.
 
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. For example:
 
<source lang=CSharp>
enum Chemical { Hydrogen = 1, Oxygen = 2, Water = 3 };
public static int Main()
{
  Chemical contents = Chemical.Hydrogen | Chemical.Oxygen;
  Console.Write("Chemical Type: ");
  Console.WriteLine(contents.ToString());
  Console.Write("Chemical has Hydrogen: ");
  Console.WriteLine(contents.HasFlag(Chemical.Hydrogen.ToString());
  Console.Write("Chemical has Oxygen: ");
  Console.WriteLine(contents.HasFlag(Chemical.Oxygen.ToString());
  Console.ReadLine();
  return 0;
}
</source>
 
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.<ref name="enum">{{cite web
| url        = http://www.25hoursaday.com/
| title      = A COMPARISON OF MICROSOFT'S C# PROGRAMMING LANGUAGE TO SUN MICROSYSTEMS' JAVA PROGRAMMING LANGUAGE
| author      = Dare Obasanjo
| authorlink  = http://www.25hoursaday.com/weblog
| year        = 2007
| work        =
| publisher  = Dare Obasanjo
| archiveurl  = http://www.25hoursaday.com/CsharpVsJava.html
| archivedate = 2007
| quote      = In Java, enumerated types are a full fledged class which means they are typesafe and can be extended by adding methods, fields or even implementing interfaces. Whereas in C#, an enumerated type is simply syntactic sugar around an integral type (typically an int) meaning they cannot be extended and are not typesafe.
| accessdate  = 2012-09-06
}}</ref><ref>{{cite web
| url        = http://www.cstruter.com/
| title      = Java 5: Taming the Tiger: Syntactic Sugar
| last1      = Prof. Dr. Gruntz
| first1      = Dominik
| date        = 2005-04-08
| language    = German
| publisher  = Fachhochschule Aargau, Nordwestschweiz
| archiveurl  = http://www.gruntz.ch/courses/sem/ss05/Java5_SyntacticSugar.pdf
| archivedate = 2005-04-08
| quote      = Enumerationen sind die heimlichen Sieger von Java 1.5. Nach vielen Beteuerungen durch Sun, Enums seien in Java überflüssig und können einfach nachgebildet werden, wurden sie nun doch eingeführt. Die einfachste Möglichkeit einer Enumeration der Jahreszeiten  sieht wie folgt aus … Das Schlüsselwort  enum steht für eine spezielle Art von Klasse, die eine Enumeration
definiert. … ''Im Gegensatz zu anderen Programmiersprachen wie C/C++ und C# kann man ihnen per Gleichheitszeichen keine ganzen Zahlen zuordnen.''
| accessdate  = 2012-09-10
}}</ref><ref>{{cite web
| url        = http://www.cstruter.com/
| title      = Syntactic sugar (C#): Enum
| last1      = Truter
| first1      = Christoff
| date        = 2011-08-04
| publisher  = CSTrüter
| archiveurl  = http://www.cstruter.com/blog/325
| archivedate = 2011-08-04
| quote      = // Poorly designed enum don't do this … Obviously (like with everything else), we can misuse this piece of sugar ending up with a system suffering from hyperglycemia. … Seeing as the underlying type of our enum is an int (can also use other integral types) it can lead to some interesting issues when using an enum as bit flags via bitwise operators.  
| accessdate  = 2012-09-10
}}</ref>
 
===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 additional compile-time checking. Also (as with structs) the C++ "enum" keyword is automatically combined with a "typedef", so that instead of calling the type "enum name", one simply calls it "name." This can be simulated in C using a typedef: "typedef enum {TYPE1, TYPE2} name;"
 
[[C++11]] provides a second, type-safe enumeration type that is not implicitly converted to an integer type. It allows io streaming to be defined for that type. Additionally the enumerations do not leak, so they have to be used with Enumeration Type::enumeration. This is specified by the phrase "enum class". For example:
 
<source lang="cpp">
enum class Color {Red, Green, Blue};
</source>
 
===Java===
 
The J2SE version 5.0 of the [[Java (programming language)|Java programming language]] added enumerated types whose declaration syntax is
similar to that of [[C (programming language)|C]]:
 
<source lang=Java5>
  enum Cardsuit { CLUBS, DIAMONDS, SPADES, HEARTS };
  ...
  Cardsuit trump;
</source>
 
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 (computer science)|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 {{Javadoc:SE|java/lang|Enum}} abstract class. An enum type cannot be instantiated directly.<ref>{{cite web
| url        = http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
| title      = Enum Types
| language    = English
| publisher  = Oracle
| accessdate  = 2013-12-05
}}</ref>
 
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 {{Javadoc:SE|name=ordinal()|java/lang|Enum|ordinal()}} method, and the list of enum values of an enumeration type can be obtained in order using the <code>values()</code> method. It is generally discouraged for programmers to convert enums to integers and vice versa.<ref>{{Cite book | last=Bloch | first=Joshua | authorlink=Joshua Bloch | coauthors= | title=Effective Java | edition=Second | year=2008 | publisher=Addison-Wesley | location=Upper Saddle River, N.J. | isbn=978-0-321-35668-0 | page=158}}</ref> Enumerated types are <code>Comparable</code>, using the internal integer; as a result, they can be sorted.
 
The Java standard library provides utility classes to use with enumerations. The {{Javadoc:SE|java/util|EnumSet}} class implements a <code>Set</code> of enum values; it is implemented as a [[bit array]], which makes it very compact and as efficient as explicit bit manipulation, but safer. The {{Javadoc:SE|java/util|EnumMap}} class implements a <code>Map</code> of enum values to object. It is implemented as an array, with the integer value of the enum value serving as the index.
 
==Fortran==
 
[[Fortran]] 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
 
<source lang=Fortran>
  enum, bind( C )
    enumerator :: CLUBS = 1, DIAMONDS = 2, HEARTS = 4, SPADES = 8
  end enum
</source>
 
==Visual Basic/VBA==
 
Enumerated datatypes in [[Visual Basic]] (up to version 6) and [[Visual Basic for Applications|VBA]] are automatically assigned the "<code>Long</code>" datatype and also become a datatype themselves:
 
<source lang=VB>
Enum CardSuit
  Clubs
  Diamonds
  Hearts
  Spades
End Enum
 
Sub EnumExample()
    Dim suit As CardSuit
    suit = Diamonds
    MsgBox suit
End Sub
</source>
 
Example Code in vb.Net
 
<source lang=vbNet>
Enum CardSuit
        Clubs
        Diamonds
        Hearts
        Spades
End Enum
 
Sub EnumExample()
        Dim suit As CardSuit
        suit = CardSuit.Diamonds
        MsgBox(suit)
End Sub
</source>
 
== Algebraic data type in functional programming ==
 
In [[functional programming]] languages in the [[ML programming language|ML]] lineage (e.g., [[Standard ML|SML]], [[OCaml]] and [[Haskell (programming language)|Haskell]]), an [[algebraic data type]] with only [[nullary constructor]]s 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 <code>Enum</code> [[type class]] which a type can derive or implement to get a mapping between the type and <code>Int</code>.
 
== Lisp ==
 
[[Common Lisp]] uses the member type specifier, e.g.
 
<source lang=Lisp>
(deftype cardsuit ()
  '(member club diamond heart spade))
</source>
 
that states that object is of type cardsuit if it is <code>#'eql</code> to club, diamond, heart or spade. The member type specifier is not valid as a [[CLOS]] parameter specializer,
however. Instead, <code>(eql atom)</code>, which is the equivalent to <code>(member atom)</code> may be used (that is, only one member of the set may be specified with an eql type specifier, however, it may be used as a CLOS parameter specializer.) In other words, in order to define methods to cover an enumerated type, a method must be defined for each specific element of that type.
 
Additionally,
 
<source lang=Lisp>
(deftype finite-element-set-type (&rest elements)
  `(member ,@elements))
</source>
 
may be used to define arbitrary enumerated types at runtime. For instance
 
<source lang=Lisp>
(finite-element-set-type club diamond heart spade)
</source>
 
would refer to a type equivalent to the prior definition of cardsuit, as of course would simply have been using
 
<source lang=Lisp>
(member club diamond heart spade)
</source>
 
but may be less confusing with the function <code>#'member</code> for stylistic reasons.
 
== Databases ==
 
Some [[database]]s support enumerated types directly. [[MySQL]] provides an enumerated type <code>ENUM</code> with allowable values specified as strings when a table is created. The values are stored as numeric indices with the empty string stored as 0, the first string value stored as 1, the second string value stored as 2, etc. Values can be stored and retrieved as numeric indexes or string values.
 
== XML Schema ==
 
[[XML Schema]] supports enumerated types through the enumeration facet used for constraining most primitive datatypes such as strings.
 
<source lang=XML>
<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>
</source>
 
== References ==
{{Reflist|2}}
 
== External links ==
{{Wikibooks|Ada Programming|Types/Enumeration|Enumeration}}
* [http://www.cppreference.com/keywords/enum.html Enumerated types in C/C++]
* [http://msdn.microsoft.com/en-us/library/cc138362.aspx Enumerated types in C#]
* [http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html Enumerated types in Java]
* [http://dev.mysql.com/doc/refman/5.1/en/enum.html Enumerated types in MySQL]
* [http://www.rps-obix.com/docs/manuals/enumerated_data_type.html Enumerated types in Obix]
* [http://www.w3.org/TR/xmlschema-2/ Enumerated types in XML]
* [http://msdn.microsoft.com/en-us/library/93khb7k9.aspx Enumerated types in Visual Basic]
 
{{data types}}
 
<!--Categories-->
[[Category:Data types]]
[[Category:Type theory]]
[[Category:Articles with example Ada code]]

Revision as of 17:58, 14 January 2014

In computer programming, an enumerated type (also called enumeration or enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. 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 which are not specified by the programmer as having any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily.

For example, the four suits in a deck of playing cards may be four enumerators named CLUB, DIAMOND, HEART, 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; in others, the enumerators are unordered; 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. Many languages allow the user to define new enumerated types.

Values and variables of an enumerated type are usually implemented as fixed-length bit strings, often in a format and size compatible with some integer type. Some languages, especially system programming languages, allow the user to specify the bit combination to be used for each enumerator. 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.

Rationale

Some 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 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, made 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:
myColor = TRIANGLE
can be forbidden, whilst
myColor = RED
is accepted, even if TRIANGLE and RED are both internally represented as 1.

Conceptually, an enumerated type is similar to a list of nominals, 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.

Conventions

In some programming conventions, enumerators are conventionally written with upper case letters to indicate they are constants.

Pascal and syntactically similar languages

In 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 pred and succ functions will give the prior or next value of the enumeration, and ord can convert enumeration values to their integer representation. Standard Pascal does not offer a conversion from arithmetic types to enumerations, however. Extended Pascal offers this functionality via an extended succ function. Some other Pascal dialects allow it via type-casts. Some modern descendants of Pascal, such as Modula-3, provide a special conversion syntax using a method called VAL; Modula-3 also treats BOOLEAN and CHAR as special pre-defined enumerated types and uses ORD and VAL for standard ASCII decoding and encoding.

Pascal style languages also allow for enumeration to be used as array index

  var
    suitcount: array [cardsuit] of integer;

Ada

In Ada, the use of "=" was replaced with "is" leaving the definition quite similar:

type Cardsuit is (clubs, diamonds, hearts, spades);

In addition to Pred, Succ, Val and Pos Ada also supports simple string conversions via Image and Value.

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

Even more, you can use enumerations as indexes for arrays like 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 Boolean and Character as special pre-defined (in package "Standard") enumerated types. Unlike Modula-3 one can also define own character types:

type Cards is ('7', '8', '9', 'J', 'Q', 'K', 'A');

C and syntactically similar languages

The original K&R dialect of the C programming language did not have enumerated types, but they were added in the ANSI standard for C, which became C89. In C, enumerations are created by explicit definitions, which use the enum keyword and are reminiscent of struct and union definitions:

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 CLUBS, DIAMONDS, HEARTS, and SPADES as constants of type int, which will only be converted (silently) to enum cardsuit if they are stored in a variable of that type.

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 enum cardsuit by bitwise logic operations.

Dynamically typed languages in the syntactic tradition of C (e.g., Perl or JavaScript) do not, in general, provide enumerations. But in Perl programming you can obtain the same result 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

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 CardSuit.Diamonds + 1 and CardSuit.Hearts - CardSuit.Clubs are allowed directly (because it makes sense to step through the sequence of values or ask how many steps there are between two values), but CardSuit.Hearts*CardSuit.Spades is deemed to make less sense and is only allowed if the values are first converted to integers.

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. For example:

enum Chemical { Hydrogen = 1, Oxygen = 2, Water = 3 }; 
public static int Main() 
{
  Chemical contents = Chemical.Hydrogen | Chemical.Oxygen;
  Console.Write("Chemical Type: ");
  Console.WriteLine(contents.ToString());
  Console.Write("Chemical has Hydrogen: ");
  Console.WriteLine(contents.HasFlag(Chemical.Hydrogen.ToString());
  Console.Write("Chemical has Oxygen: "); 
  Console.WriteLine(contents.HasFlag(Chemical.Oxygen.ToString());
  Console.ReadLine();
  return 0;
}

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.[1][2][3]

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 additional compile-time checking. Also (as with structs) the C++ "enum" keyword is automatically combined with a "typedef", so that instead of calling the type "enum name", one simply calls it "name." This can be simulated in C using a typedef: "typedef enum {TYPE1, TYPE2} name;"

C++11 provides a second, type-safe enumeration type that is not implicitly converted to an integer type. It allows io streaming to be defined for that type. Additionally the enumerations do not leak, so they have to be used with Enumeration Type::enumeration. This is specified by the phrase "enum class". For example:

enum class Color {Red, Green, Blue};

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 Template:Javadoc:SE abstract class. An enum type cannot be instantiated directly.[4]

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 Template:Javadoc:SE method, and the list of enum values of an enumeration type can be obtained in order using the values() method. It is generally discouraged for programmers to convert enums to integers and vice versa.[5] Enumerated types are Comparable, using the internal integer; as a result, they can be sorted.

The Java standard library provides utility classes to use with enumerations. The Template:Javadoc:SE class implements a Set of enum values; it is implemented as a bit array, which makes it very compact and as efficient as explicit bit manipulation, but safer. The Template:Javadoc:SE class implements a Map of enum values to object. It is implemented as an array, with the integer value of the enum value serving as the index.

Fortran

Fortran 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/VBA

Enumerated datatypes in Visual Basic (up to version 6) and VBA are automatically assigned the "Long" datatype and also become a datatype themselves:

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
        MsgBox(suit)
End Sub

Algebraic data type in functional programming

In functional programming languages in the ML lineage (e.g., 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 Enum type class which a type can derive or implement to get a mapping between the type and Int.

Lisp

Common 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 #'eql to club, diamond, heart or spade. The member type specifier is not valid as a CLOS parameter specializer, however. Instead, (eql atom), which is the equivalent to (member atom) may be used (that is, only one member of the set may be specified with an eql type specifier, however, it may be used as a CLOS parameter specializer.) In other words, in order to define methods to cover an enumerated type, a method must be defined for each specific element of that type.

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 #'member for stylistic reasons.

Databases

Some databases support enumerated types directly. MySQL provides an enumerated type ENUM with allowable values specified as strings when a table is created. The values are stored as numeric indices with the empty string stored as 0, the first string value stored as 1, the second string value stored as 2, etc. Values can be stored and retrieved as numeric indexes or string values.

XML Schema

XML 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>

References

43 year old Petroleum Engineer Harry from Deep River, usually spends time with hobbies and interests like renting movies, property developers in singapore new condominium and vehicle racing. Constantly enjoys going to destinations like Camino Real de Tierra Adentro.

External links

DTZ's auction group in Singapore auctions all types of residential, workplace and retail properties, retailers, homes, accommodations, boarding houses, industrial buildings and development websites. Auctions are at the moment held as soon as a month.

Whitehaven @ Pasir Panjang – A boutique improvement nicely nestled peacefully in serene Pasir Panjang personal estate presenting a hundred and twenty rare freehold private apartments tastefully designed by the famend Ong & Ong Architect. Only a short drive away from Science Park and NUS Campus, Jade Residences, a recent Freehold condominium which offers high quality lifestyle with wonderful facilities and conveniences proper at its door steps. Its fashionable linear architectural fashion promotes peace and tranquility living nestled within the D19 personal housing enclave. Rising workplace sector leads real estate market efficiency, while prime retail and enterprise park segments moderate and residential sector continues in decline International Market Perspectives - 1st Quarter 2014

There are a lot of websites out there stating to be one of the best seek for propertycondominiumhouse, and likewise some ways to discover a low cost propertycondominiumhouse. Owning a propertycondominiumhouse in Singapore is the dream of virtually all individuals in Singapore, It is likely one of the large choice we make in a lifetime. Even if you happen to're new to Property listing singapore funding, we are right here that will help you in making the best resolution to purchase a propertycondominiumhouse at the least expensive value.

Jun 18 ROCHESTER in MIXED USE IMPROVEMENT $1338000 / 1br - 861ft² - (THE ROCHESTER CLOSE TO NORTH BUONA VISTA RD) pic real property - by broker Jun 18 MIXED USE IMPROVEMENT @ ROCHESTER @ ROCHESTER PK $1880000 / 1br - 1281ft² - (ROCHESTER CLOSE TO NORTH BUONA VISTA) pic real estate - by broker Tue 17 Jun Jun 17 Sunny Artwork Deco Gem Near Seashore-Super Deal!!! $103600 / 2br - 980ft² - (Ventnor) pic actual estate - by owner Jun 17 Freehold semi-d for rent (Jalan Rebana ) $7000000 / 5909ft² - (Jalan Rebana ) actual property - by dealer Jun sixteen Ascent @ 456 in D12 (456 Balestier Highway,Singapore) pic real property - by proprietor Jun 16 RETAIL SHOP AT SIM LIM SQUARE FOR SALE, IT MALL, ROCHOR, BUGIS MRT $2000000 / 506ft² - (ROCHOR, BUGIS MRT) pic real estate - by dealer HDB Scheme Any DBSS BTO

In case you are eligible to purchase landed houses (open solely to Singapore residents) it is without doubt one of the best property investment choices. Landed housing varieties solely a small fraction of available residential property in Singapore, due to shortage of land right here. In the long term it should hold its worth and appreciate as the supply is small. In truth, landed housing costs have risen the most, having doubled within the last eight years or so. However he got here back the following day with two suitcases full of money. Typically we've got to clarify to such folks that there are rules and paperwork in Singapore and you can't just buy a home like that,' she said. For conveyancing matters there shall be a recommendedLondon Regulation agency familiar with Singapore London propertyinvestors to symbolize you

Sales transaction volumes have been expected to hit four,000 units for 2012, close to the mixed EC gross sales volume in 2010 and 2011, in accordance with Savills Singapore. Nevertheless the last quarter was weak. In Q4 2012, sales transactions were 22.8% down q-q to 7,931 units, in line with the URA. The quarterly sales discount was felt throughout the board. When the sale just starts, I am not in a hurry to buy. It's completely different from a private sale open for privileged clients for one day solely. Orchard / Holland (D09-10) House For Sale The Tembusu is a singular large freehold land outdoors the central area. Designed by multiple award-profitable architects Arc Studio Architecture + Urbanism, the event is targeted for launch in mid 2013. Post your Property Condos Close to MRT

Template:Data types

  1. Template:Cite web
  2. Template:Cite web
  3. Template:Cite web
  4. Template:Cite web
  5. 20 year-old Real Estate Agent Rusty from Saint-Paul, has hobbies and interests which includes monopoly, property developers in singapore and poker. Will soon undertake a contiki trip that may include going to the Lower Valley of the Omo.

    My blog: http://www.primaboinca.com/view_profile.php?userid=5889534