Enumerations: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(7 intermediate revisions by 5 users not shown)
Line 6:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">T.enum TokenCategory
NAME
KEYWORD
CONSTANT
TEST_CATEGORY = 10</langsyntaxhighlight>
 
=={{header|6502 Assembly}}==
Line 17:
 
Keep in mind that these names do not exist at runtime and are just for the programmer's convenience. None of this "code" below actually takes up any space in the assembled program.
<langsyntaxhighlight lang="6502asm">Sunday equ 0
Monday equ 1
Tuesday equ 2
Line 23:
Thursday equ 4
Friday equ 5
Saturday equ 6</langsyntaxhighlight>
 
Some assemblers have an actual <code>ENUM</code> directive, where only the 0th element needs a defined value and the rest follow sequentially. This is often used for allocating RAM locations rather than a [[C]]-style enumeration, however. <code>.DSB</code> is a directive that stands for "data storage byte" and is listed after the label so that the assembler knows how big the variable is. In the example below the variable <code>OBJECT_XPOS</code> begins at $0400 and <code>OBJECT_XPOS</code> begins at $0410:
<langsyntaxhighlight lang="6502asm">enum $0400
OBJECT_XPOS .dsb 16 ;define 16 bytes for object X position
OBJECT_YPOS .dsb 16 ;define 16 bytes for object Y position
ende</langsyntaxhighlight>
 
===Without Explicit Values===
A lookup table is the most common method of enumeration of actual data in assembly. Each element of the table can be accessed by an index, and the starting index is zero. (The index may need to be adjusted for data sizes larger than 1 byte, i.e. doubled for 16-bit data and quadrupled for 32-bit data.) Unlike the above example, these values do indeed take up memory. Using this method when the above enumeration would suffice is incredibly wasteful.
 
<langsyntaxhighlight lang="6502asm">Days_Of_The_Week:
word Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
 
Line 63:
LDY #0 ;clear Y
 
LDA ($00),Y ;Load the "W" of Wednesday into accumulator</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
Line 71:
 
Keep in mind that these names do not exist at runtime and are just for the programmer's convenience. None of this "code" below actually takes up any space in the assembled program.
<langsyntaxhighlight lang="68000devpac">Sunday equ 0
Monday equ 1
Tuesday equ 2
Line 77:
Thursday equ 4
Friday equ 5
Saturday equ 6</langsyntaxhighlight>
 
 
Line 85:
Like in a [[C]]-style enumeration, Sunday would be 0, Monday 1, Tuesday 2, and so on. (Actually, Monday would be 4 and Tuesday would be 8 and so on, since these are 32-bit pointers.) It's a common practice to have the index live in RAM as a one-byte index, load it in a register, and then scale its register copy during the lookup process only. That way if multiple tables with different data sizes have a common index, the program doesn't need to remember which data type the index was last used to access.
 
<langsyntaxhighlight lang="68000devpac">Days_Of_The_Week:
DC.L Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
 
Line 117:
LEA (A0,D0),A1 ;load table offset by D0 into A1
MOVE.L (A1),A1 ;dereference the pointer, now the address of "Thursday" is in A1.
MOVE.B (A1)+,D1 ;Load the "T" of Thursday into D1, auto-increment to next letter for the next load.</langsyntaxhighlight>
 
=={{header|8086 Assembly}}==
Line 123:
===With Explicit Values===
Most assemblers allow the use of an <code>equ</code> directive or something similar, where you can assign a label to a number for later use. These do not take up space in your program.
<langsyntaxhighlight lang="asm">Sunday equ 0
Monday equ 1
Tuesday equ 2
Line 130:
Friday equ 5
Saturday equ 6
Sunday equ 7</langsyntaxhighlight>
 
===Without Explicit Values===
A lookup table is often used to translate data according to a common index. The <code>XLAT</code> instruction can help us with this task, however that instruction only works with 8-bit data, which is not always what we're after. In this example, we're using numbers 0 through 7 to look up a table of pointers to strings. When declaring a table like this, these DO take up space in your program.
<langsyntaxhighlight lang="asm">mov ax,seg DaysOfTheWeek
mov ds,ax
mov si,offset DaysOfTheWeek
Line 146:
 
DaysOfTheWeek word Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
;each is a pointer to a string containing the text you would expect.</langsyntaxhighlight>
 
 
Line 153:
ACL2 doesn't have built-in enumerated types, but these macros add some basic support:
 
<langsyntaxhighlight Lisplang="lisp">(defun symbol-to-constant (sym)
(intern (concatenate 'string "*" (symbol-name sym) "*")
"ACL2"))
Line 174:
 
(defmacro enum (&rest symbols)
`(enum-with-vals ,@(interleave-with-nats symbols)))</langsyntaxhighlight>
 
=={{header|Ada}}==
Ada enumeration types have three distinct attributes, the enumeration literal, the enumeration position, and the representation value. The position value (starting with 0) is implied from the order of specification of the enumeration literals in the type declaration; it provides the ordering for the enumeration values. In the example below, apple (position 0) is less than banana (position 1) which is less than cherry (position 3) due to their positions, not due to their enumeration literal. An enumeration representation, when given, must not violate the order.
<langsyntaxhighlight lang="ada">type Fruit is (apple, banana, cherry); -- No specification of the representation value;
for Fruit use (apple => 1, banana => 2, cherry => 4); -- specification of the representation values</langsyntaxhighlight>
Ada enumeration types are non-numeric discrete types. They can be used to index arrays, but there are no arithmetic operators for enumeration types; instead, there are predecessor and successor operations. Characters are implemented as an enumeration type in Ada.
 
Line 195:
compatible with INT and so FRUITS inherit/share all INT's operators
and procedures.
<langsyntaxhighlight lang="algol68">BEGIN # example 1 #
MODE FRUIT = INT;
FRUIT apple = 1, banana = 2, cherry = 4;
Line 207:
SKIP # other values #
ESAC
END;</langsyntaxhighlight>
{{out}}
<pre>
Line 224:
least REPR (or ABS for INT type) must be defined if anything other then a
'''case''' conditional clause is required.
<langsyntaxhighlight lang="algol68">BEGIN # example 2 #
MODE ENUM = [0]CHAR; # something with minimal size #
MODE APPLE = STRUCT(ENUM apple), BANANA = STRUCT(ENUM banana), CHERRY = STRUCT(ENUM cherry);
Line 247:
SKIP # uninitialised FRUIT #
ESAC
END</langsyntaxhighlight>
{{out}}
<pre>
Line 257:
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">ENUM APPLE, BANANA, CHERRY
 
PROC main()
Line 263:
ForAll({x}, [APPLE, BANANA, CHERRY],
`WriteF('\d\n', x))
ENDPROC</langsyntaxhighlight>
 
writes 0, 1, 2 to the console.
Line 269:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">enum: [apple banana cherry]
print "as a block of words:"
inspect.muted enum
Line 283:
]
print "\nas a dictionary:"
print enum</langsyntaxhighlight>
 
{{out}}
Line 304:
The wording of the task seems centered on C, where an '''enum''' is a notation for type '''int''', but it is true that the following type will be translated by the ATS compiler to C integers:
 
<langsyntaxhighlight ATSlang="ats">datatype my_enum =
| value_a
| value_b
| value_c</langsyntaxhighlight>
 
Within ATS itself, '''my_enum''' is a special case of recursive type definition. Similar facilities are available in ML dialects and other languages.
 
To "enumerate" with explicit integer values, I would simply define some constants, probably with '''#define''' (so I could use them in static expressions, etc.):
<langsyntaxhighlight ATSlang="ats">#define value_a 1
#define value_b 2
#define value_c 3</langsyntaxhighlight>
 
You could still restrict things so no other values were possible:
 
<langsyntaxhighlight ATSlang="ats">typedef my_enum = [i : int | value_a <= i; i <= value_c] int i</langsyntaxhighlight>
 
The value of a '''my_enum''' would be enforced ''at compile time''.
Line 325:
AutoHotkey doesn't really enforce types. <br>
However you can simulate types like enumeration with associative arrays:
<langsyntaxhighlight AutoHotkeylang="autohotkey">fruit_%apple% = 0
fruit_%banana% = 1
fruit_%cherry% = 2</langsyntaxhighlight>
 
=={{header|AWK}}==
In awk we can use an array, for mapping both ways, or initialize variables:
<langsyntaxhighlight lang="awk">fruit["apple"]=1; fruit["banana"]=2; fruit["cherry"]=3
fruit[1]="apple"; fruit[2]="banana"; fruit[3]="cherry"
i=0; apple=++i; banana=++i; cherry=++i;</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 339:
 
{{works with|PB|7.1}}
<langsyntaxhighlight lang="qbasic">REM Impossible. Can only be faked with arrays of strings.
OPTION BASE 1
DIM SHARED fruitsName$(1 to 3)
Line 354:
apple% = 1
banana% = 2
cherry% = 3</langsyntaxhighlight>
 
==={{header|BaCon}}===
BaCon includes an ENUM statement, with or without fixed values. If no value is given, enumerations start at zero and increase by integer 1.
 
<langsyntaxhighlight lang="freebasic">' Enumerations
' Start at zero
ENUM
Line 376:
sunday=7, monday=1, tuesday, wednesday, thursday, friday, saturday
END ENUM
PRINT sunday, " ", wednesday, " ", saturday</langsyntaxhighlight>
 
{{out}}
Line 389:
'Create a collection of constants that is a complete, ordered listing of all of the constants in that collection, with and without explicit values.'
In Bracmat, each expression is a constant and can be used in situations where one would use an enum in other languages. All expressions have an ordering in sums and products. In the case of non-numeric strings the ordering is alphabetic. It is not possible in Bracmat to have a constant without an explicit value, because the constant is nothing but the value, so only half of the task can be solved.
<langsyntaxhighlight lang="bracmat">fruits=apple+banana+cherry;</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">enum fruits { apple, banana, cherry };
 
enum fruits { apple = 0, banana = 1, cherry = 2 };</langsyntaxhighlight>
 
However, if defined like the above, in C you must use the type as <code>enum fruits</code>, not just <code>fruits</code>. A common practice in C (same with <code>struct</code>s) is to instead typedef the enum so you can refer to the type as a bare name:
 
<langsyntaxhighlight lang="c">typedef enum { apple, banana, cherry } fruits;
 
typedef enum { apple = 0, banana = 1, cherry = 2 } fruits;</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">enum fruits { apple, banana, cherry }
 
enum fruits { apple = 0, banana = 1, cherry = 2 }
Line 410:
 
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }</langsyntaxhighlight>
 
Placing FlagsAttribute before an enum allows you to perform bitwise operations on the value.
Line 416:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">enum fruits { apple, banana, cherry };
 
enum fruits { apple = 0, banana = 1, cherry = 2 };</langsyntaxhighlight>
Note that, unlike in C, you can refer to the type here as <code>fruits</code>.
 
Line 424:
{{works with|C++11}}
C++11 introduced "strongly typed enumerations", enumerations that cannot be implicitly converted to/from integers:
<langsyntaxhighlight lang="cpp">enum class fruits { apple, banana, cherry };
 
enum class fruits { apple = 0, banana = 1, cherry = 2 };</langsyntaxhighlight>
 
These enumeration constants must be referred to as <code>fruits::apple</code>, not just <code>apple</code>.
 
You can explicitly specify an underlying type for the enum; the default is <code>int</code>:
<langsyntaxhighlight lang="cpp">enum class fruits : unsigned int { apple, banana, cherry };</langsyntaxhighlight>
 
You can also explicitly specify an underlying type for old-style enums:
<langsyntaxhighlight lang="cpp">enum fruits : unsigned int { apple, banana, cherry };</langsyntaxhighlight>
 
=={{header|Clojure}}==
In Clojure you will typically use keywords when you would use enums in other languages. Keywords are symbols that start with a colon and evaluate to themselves. For example:
<langsyntaxhighlight lang="clojure">; a set of keywords
(def fruits #{:apple :banana :cherry})
 
Line 448:
 
(println (fruit? :apple))
(println (fruit-value :banana))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Values:
 
<langsyntaxhighlight lang="lisp">;; symbol to number
(defconstant +apple+ 0)
(defconstant +banana+ 1)
Line 460:
;; number to symbol
(defun index-fruit (i)
(aref #(+apple+ +banana+ +cherry+) i))</langsyntaxhighlight>
Of course, the two definitions above can be produced by a single macro, if desired.
 
Defining a type for documentation or checking purposes:
 
<langsyntaxhighlight lang="lisp">(deftype fruit ()
'(member +apple+ +banana+ +cherry+))</langsyntaxhighlight>
=={{header|Computer/zero Assembly}}==
Constants can be defined by simply storing their binary representation into memory. You've only got 32 bytes of RAM so don't waste them. This is the only way to use numeric values, as all instructions on the CPU take memory addresses as operands, not constants.
<langsyntaxhighlight lang="6502asm">LDA 4 ;load from memory address 4
STP
NOP
NOP
byte 1</langsyntaxhighlight>
The <code>NOP</code> and <code>STP</code> instructions ignore their operands, which means you can store arbitrary data inside those instructions that you can load from. This can save a little bit of memory.
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
// Named enumeration (commonly used enum in D).
// The underlying type is a 32 bit int.
Line 526:
// Use the & operator between BitFlags for intersection.
assert (flagsGreen == (flagsRedGreen & flagsBlueGreen));
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
In addition to [[#Pascal|standard Pascal]], one may explicitly specify an index:
<syntaxhighlight lang="delphi">type
<lang Delphi>type
fruit = (apple, banana, cherry);
ape = (gorilla = 0, chimpanzee = 1, orangutan = 5);</langsyntaxhighlight>
Note, explicit indices ''have'' to be in ascending order.
You can also just specify explicit indices for ''some'' items.
 
=={{header|Diego}}==
Enumerations can have extra information appended such as <code>static</code> (static variable name); <code>colour</code> (human friendly colour name); <code>color</code> (robot friendly colour name); and <code>desc</code> (description used for robots to communicate with humans).
 
With explicit values:
<syntaxhighlight lang="diego">add_enum(⟪{int}⟫,⟦{str}⟧,urgency)
()_enum(⟪4⟫,⟦emergent⟧)_static(URGENCY_EMERGENT)_colour(red)_color({hex},#ca0031)_desc(The most urgent (critical) state, severe risk.);
()_enum(⟪3⟫,⟦exigent⟧)_static(URGENT_EXIGENT)_colour(orange)_color({hex},#ff6400)_desc(The high urgent state, high risk.);
()_enum(⟪2⟫,⟦urgent⟧)_static(URGENT_URGENT)_colour(yellow)_color({hex},#fce001)_desc(The elevated urgent state, elevated risk.);
()_enum(⟪1⟫,⟦infergent⟧)_static(URGENT_INFERGENT)_colour(blue)_color({hex},#3566cd)_desc(The low urgent state, low / guarded risk.);
()_enum(⟪0⟫,⟦nonurgent⟧)_static(URGENT_NON)_colour(green)_color({hex},#009a66)_desc(The non-urgent state, negligible risk.);
;</syntaxhighlight>
 
Without explicit values (and dynamic typing):
<syntaxhighlight lang="diego">add_enum(fruits,⟦apple,banana,cherry⟧);</syntaxhighlight>
 
Flag enumerations (multi-selectable enumerations) can be created using <code>enum</code>, however, there is an primitive <code>flag</code> object available. This is similar to <code>[Flags]</code> and <code>&lt;Flags&gt; _</code> flag attributes in C# and VB.Net respectively.
 
<syntaxhighlight lang="diego">add_flag(ape,⟦gorilla,chimpanzee,orangutan⟧);
log_console()_(ape);</syntaxhighlight>
 
Output:
 
<pre>⟪1⟫,⟦gorilla⟧,⟪2⟫,⟦chimpanzee⟧,⟪4⟫,⟦orangutan⟧</pre>
 
=={{header|DWScript}}==
 
<langsyntaxhighlight Delphilang="delphi">type TFruit = (Apple, Banana, Cherry);
type TApe = (Gorilla = 0, Chimpanzee = 1, Orangutan = 5);</langsyntaxhighlight>
 
=={{header|E}}==
Simple group of object definitions (value methods could be left out if appropriate):
 
<langsyntaxhighlight lang="e">def apple { to value() { return 0 } }
def banana { to value() { return 1 } }
def cherry { to value() { return 2 } }</langsyntaxhighlight>
With a guard for type checks:
<langsyntaxhighlight lang="e">interface Fruit guards FruitStamp {}
def apple implements FruitStamp {}
def banana implements FruitStamp {}
def cherry implements FruitStamp {}
 
def eat(fruit :Fruit) { ... }</langsyntaxhighlight>
With and without values, using a hypothetical enumeration library:
<langsyntaxhighlight lang="e">def [Fruit, [=> apple, => banana, => cherry]] := makeEnumeration()
 
def [Fruit, [=> apple, => banana, => cherry]] :=
makeEnumeration(0, ["apple", "banana", "cherry"])</langsyntaxhighlight>
 
=={{header|EGL}}==
{{works with|EDT}}
<langsyntaxhighlight EGLlang="egl">// Without explicit values
enumeration FruitsKind
APPLE,
Line 588 ⟶ 612:
end
 
end</langsyntaxhighlight>
{{works with|EDT}}
-and-
{{works with|RBD}}
<langsyntaxhighlight EGLlang="egl">// With explicit values
library FruitsKind type BasicLibrary {}
const APPLE int = 0;
Line 619 ⟶ 643:
end
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
It is possible to use a atom if the value is unrelated.
<langsyntaxhighlight lang="elixir">fruits = [:apple, :banana, :cherry]
fruits = ~w(apple banana cherry)a # Above-mentioned different notation
val = :banana
Enum.member?(fruits, val) #=> true
val in fruits #=> true</langsyntaxhighlight>
 
If they have to have a specific value
<langsyntaxhighlight lang="elixir">fruits = [{:apple, 1}, {:banana, 2}, {:cherry, 3}] # Keyword list
fruits = [apple: 1, banana: 2, cherry: 3] # Above-mentioned different notation
fruits[:apple] #=> 1
Line 639 ⟶ 663:
fruits[:apple] #=> 1
fruits.apple #=> 1 (Only When the key is Atom)
Map.has_key?(fruits, :banana) #=> true</langsyntaxhighlight>
 
To give a number in turn, there is the following method.
<langsyntaxhighlight lang="elixir"># Keyword list
fruits = ~w(apple banana cherry)a |> Enum.with_index
#=> [apple: 0, banana: 1, cherry: 2]
Line 648 ⟶ 672:
# Map
fruits = ~w(apple banana cherry)a |> Enum.with_index |> Map.new
#=> %{apple: 0, banana: 1, cherry: 2}</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
in Org:RosettaCode
type Fruits
enum
int APPLE, BANANA, CHERRY
end
type ExplicitFruits
enum
int APPLE = 10
int BANANA = 20
int CHERRY = 1
end
type Main
for each generic enumeration in generic[Fruits, ExplicitFruits]
writeLine("[" + Generic.name(enumeration) + "]")
writeLine("getting an object with value = 1:")
writeLine(:enumeration.byValue(1))
writeLine("iterating over the items:")
for each var fruit in :enumeration
writeLine(fruit)
end
writeLine()
end
</syntaxhighlight>
{{out}}
<pre>
[Org:RosettaCode:Fruits]
getting an object with value = 1:
BANANA(1)
iterating over the items:
APPLE(0)
BANANA(1)
CHERRY(2)
 
[Org:RosettaCode:ExplicitFruits]
getting an object with value = 1:
CHERRY(1)
iterating over the items:
APPLE(10)
BANANA(20)
CHERRY(1)
</pre>
 
=={{header|Erlang}}==
Line 656 ⟶ 724:
=={{header|F_Sharp|F#}}==
Enumerations in F# always have explicit values:
<langsyntaxhighlight lang="fsharp">type Fruit =
| Apple = 0
| Banana = 1
Line 662 ⟶ 730:
 
let basket = [ Fruit.Apple ; Fruit.Banana ; Fruit.Cherry ]
Seq.iter (printfn "%A") basket</langsyntaxhighlight>
 
If the initialization values are omitted, the resulting type is a discriminated union (algebraic data type) instead.
Simple discriminated unions can be used similarly to enumerations, but they are never convertible from and to integers, and their internal representation is quite different.
 
<langsyntaxhighlight lang="fsharp">type Fruit =
| Apple
| Banana
| Cherry
let basket = [ Apple ; Banana ; Cherry ]
Seq.iter (printfn "%A") basket</langsyntaxhighlight>
 
=={{header|Factor}}==
 
Enumerations are essentially association lists with values (keys) assigned sequentially from constants (values) provided by an initial sequence.
<langsyntaxhighlight lang="factor">IN: scratchpad { "sun" "mon" "tue" "wed" "thur" "fri" "sat" } <enum>
 
--- Data stack:
Line 685 ⟶ 753:
--- Data stack:
"mon"
{ 0 1 2 3 4 5 6 }</langsyntaxhighlight>
Factor also provides C-like enumerations in its C library interface. These enumerations may have explicit values.
<langsyntaxhighlight lang="factor">IN: scratchpad USE: alien.syntax
IN: scratchpad ENUM: day sun mon { tue 42 } wed thur fri sat ;
IN: scratchpad 1 <day>
Line 697 ⟶ 765:
--- Data stack:
mon
tue</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 703 ⟶ 771:
Enumerations with named constants:
 
<langsyntaxhighlight lang="fantom">
// create an enumeration with named constants
enum class Fruits { apple, banana, orange }
</syntaxhighlight>
</lang>
 
A private constructor can be added to initialise internal fields, which must be constant.
 
<syntaxhighlight lang="fantom">
<lang Fantom>
// create an enumeration with explicit values
enum class Fruits_
Line 718 ⟶ 786:
private new make (Int value) { this.value = value }
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Forth has no types, and therefore no enumeration type. To define sequential constants, a programmer might write code like this:
 
<langsyntaxhighlight lang="forth">0 CONSTANT apple
1 CONSTANT banana
2 CONSTANT cherry
...</langsyntaxhighlight>
However, a common idiom in forth is to define a defining word, such as:
<langsyntaxhighlight lang="forth">: ENUM ( n -<name>- n+1 ) DUP CONSTANT 1+ ;</langsyntaxhighlight>
This word defines a new constant of the value specified and returns the next value in sequence.
It would be used like this:
 
<langsyntaxhighlight lang="forth">0 ENUM APPLE ENUM BANANA ENUM CHERRY DROP</langsyntaxhighlight>
 
Or you can use CONSTANT to capture the "end" value instead of dropping it:
 
<langsyntaxhighlight lang="forth">0 ENUM FIRST ENUM SECOND ... CONSTANT LAST</langsyntaxhighlight>
 
A variation of this idea is the "stepped enumeration" that increases the value by more than 1, such as:
 
<langsyntaxhighlight lang="forth">: SIZED-ENUM ( n s -<name>- n+s ) OVER CONSTANT + ;
: CELL-ENUM ( n -<name>- n+cell ) CELL SIZED-ENUM ;</langsyntaxhighlight>
 
A programmer could combine these enum definers in any way desired:
 
<langsyntaxhighlight lang="forth">0 ENUM FIRST \ value = 0
CELL-ENUM SECOND \ value = 1
ENUM THIRD \ value = 5
3 SIZED-ENUM FOURTH \ value = 6
ENUM FIFTH \ value = 9
CONSTANT SIXTH \ value = 10</langsyntaxhighlight>
 
Note that a similar technique is often used to implement structures in Forth.
 
For a simple zero-based sequence of constants, one could use a loop in the defining word:
<langsyntaxhighlight lang="forth">: CONSTANTS ( n -- ) 0 DO I CONSTANT LOOP ;
 
\ resistor digit colors
10 CONSTANTS black brown red orange yellow green blue violet gray white</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|2003}}
<langsyntaxhighlight lang="fortran">enum, bind(c)
enumerator :: one=1, two, three, four, five
enumerator :: six, seven, nine=9
end enum</langsyntaxhighlight>
 
The syntax
 
<langsyntaxhighlight lang="fortran">enum, bind(c) :: nametype
enumerator :: one=1, two, three
end enum nametype</langsyntaxhighlight>
 
does not work with gfortran; it is used in some [http://docs.cray.com/books/S-3692-51/html-S-3692-51/z970507905n9123.html Cray docs] about Fortran, but the syntax shown at [http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlf101a.doc/xlflr/enum.htm IBM] is the one gfortran can understand. (Cray's docs refer to Fortran 2003 draft, IBM docs refers to Fortran 2003 standard, but read the brief [http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlf101a.doc/xlflr/languagestandards.htm#wq17 Fortran 2003 Standard] section to understand why differences may exist...)
Line 782 ⟶ 850:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Enum Animals
Line 798 ⟶ 866:
Print Cat, Dog, Zebra
Print Bulldog, Terrier, WolfHound
Sleep</langsyntaxhighlight>
 
{{out}}
Line 807 ⟶ 875:
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="text">window 1, @"Enumerations", (0,0,480,270)
 
begin enum 1
Line 829 ⟶ 897:
print "_cherryExplicit = "; _cherryExplicit
 
HandleEvents</langsyntaxhighlight>
 
Output
Line 844 ⟶ 912:
=={{header|Go}}==
Go's enumeration-like feature is called iota. It generates sequential integer constants.
<langsyntaxhighlight lang="go">const (
apple = iota
banana
cherry
)</langsyntaxhighlight>
The above is equivalent to,
<langsyntaxhighlight lang="go">const (
apple = 0
banana = 1
cherry = 2
)</langsyntaxhighlight>
Constants in Go are not typed they way variables are, they are typed when used just like literal constants.
Here is an example of a type safe enumeration:
<langsyntaxhighlight lang="go">type fruit int
 
const (
Line 863 ⟶ 931:
banana
cherry
)</langsyntaxhighlight>
And using explicit values (note each constant must be individual typed here unlike with iota):
<langsyntaxhighlight lang="go">type fruit int
 
const (
Line 871 ⟶ 939:
banana fruit = 1
cherry fruit = 2
)</langsyntaxhighlight>
 
=={{header|Groovy}}==
Enumerations:
<langsyntaxhighlight lang="groovy">enum Fruit { apple, banana, cherry }
 
enum ValuedFruit {
Line 885 ⟶ 953:
 
println Fruit.values()
println ValuedFruit.values()</langsyntaxhighlight>
 
{{out}}
Line 892 ⟶ 960:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">data Fruit = Apple | Banana | Cherry deriving Enum</langsyntaxhighlight>
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">enum FRUIT {
APPLE,
BANANA,
CHERRY
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Nether Icon nor Unicon has an explicit enumeration type; however, there are several approaches that can be used for this purpose:
 
<langsyntaxhighlight Iconlang="icon"> fruits := [ "apple", "banana", "cherry", "apple" ] # a list keeps ordered data
fruits := set("apple", "banana", "cherry") # a set keeps unique data
fruits := table() # table keeps an unique data with values
fruits["apple"] := 1
fruits["banana"] := 2
fruits["cherry"] := 3</langsyntaxhighlight>
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">Fruit is a kind of value. The fruits are apple, banana, and cherry.</langsyntaxhighlight>
 
Inform 7 doesn't have conversions between enumerated values and numbers, but you can assign properties to enumerated values:
<langsyntaxhighlight lang="inform7">[sentence form]
Fruit is a kind of value. The fruits are apple, banana, and cherry.
A fruit has a number called numeric value.
The numeric value of apple is 1.
The numeric value of banana is 2.
The numeric value of cherry is 3.</langsyntaxhighlight>
<langsyntaxhighlight lang="inform7">[table form]
Fruit is a kind of value. The fruits are defined by the Table of Fruits.
 
Line 928 ⟶ 996:
apple 1
banana 2
cherry 3</langsyntaxhighlight>
 
=={{header|J}}==
 
J's typing system is fixed, and so extensions occur at the application level. For example, one could create an object
<langsyntaxhighlight lang="j"> enum =: cocreate''
( (;:'apple banana cherry') ,L:0 '__enum' ) =: i. 3
cherry__enum
2</langsyntaxhighlight>
 
But this is more akin to a "methodless class or object" than an enum in other languages.
 
That said, note that the "natural way", in J, of dealing with issues treated in other languages through enums is to use an array of names.
<langsyntaxhighlight lang="j"> fruit=: ;:'apple banana cherry'</langsyntaxhighlight>
 
Now you can get the name associated with an index:
 
<langsyntaxhighlight lang="j"> 2 { fruit
+------+
|cherry|
+------+</langsyntaxhighlight>
 
And you can get the index associated with a name:
 
<langsyntaxhighlight lang="j"> fruit i.<'banana'
1</langsyntaxhighlight>
 
And you can define an arithmetic with the enum for its domain and range. Here, for example, is 2=1+1:
 
<langsyntaxhighlight lang="j"> (<'banana') +&.(fruit&i.) <'banana'
+------+
|cherry|
+------+</langsyntaxhighlight>
 
And, you can iterate over the values (though an example of that is probably beyond the scope of this task), along with numerous other variations on these themes.<syntaxhighlight lang="j"> {{for_example. fruit do. echo;example end.}} ''
apple
banana
cherry</syntaxhighlight>
 
(A person could reasonably argue that enums were introduced in some languages to work around deficiencies in array handling in those languages. But this would be a part of a larger discussion about type systems and the use of systems of bit patterns to represent information.)
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">enum Fruits{
APPLE, BANANA, CHERRY
}</langsyntaxhighlight>
Or:
<langsyntaxhighlight lang="java5">enum Fruits{
APPLE(0), BANANA(1), CHERRY(2)
private final int value;
fruits(int value) { this.value = value; }
public int value() { return value; }
}</langsyntaxhighlight>
Conventionally, enums have the same case rules as classes, while enum values are in all caps (like other constants). All cases are allowed for both names, though, as long as they don't conflict with other classes in the same package.
 
Line 983 ⟶ 1,054:
In javascript, usually used for this a strings.
 
<langsyntaxhighlight lang="javascript">
// enum fruits { apple, banana, cherry }
 
Line 991 ⟶ 1,062:
f = "banana";
}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 1,008 ⟶ 1,079:
 
=={{header|JScript.NET}}==
<langsyntaxhighlight lang="jscript">enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }</langsyntaxhighlight>
 
=={{header|JSON}}==
<langsyntaxhighlight lang="json">{"fruits" : { "apple" : null, "banana" : null, "cherry" : null }
{"fruits" : { "apple" : 0, "banana" : 1, "cherry" : 2 }</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
@enum Fruits APPLE BANANA CHERRY
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,031 ⟶ 1,102:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
enum class Animals {
Line 1,045 ⟶ 1,116:
println()
for (value in Dogs.values()) println("${value.name.padEnd(9)} : ${value.id}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,061 ⟶ 1,132:
Lingo neither knows the concept of enumerations nor of constants. But an enumeration-like hash (property list) that is immutable concerning standard list methods and operators can be created by sub-classing a property list and overwriting list/property list access methods (which also overwrites bracket access operators on the fly):
 
<langsyntaxhighlight lang="lingo">-- parent script "Enumeration"
 
property ancestor
Line 1,092 ⟶ 1,163:
on addProp (me)
-- do nothing
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">enumeration = script("Enumeration").new("APPLE", "BANANA", "CHERRY")
 
put enumeration["BANANA"]
Line 1,127 ⟶ 1,198:
enumeration.addProp("FOO", 666)
put enumeration["FOO"]
-- <Void></langsyntaxhighlight>
 
=={{header|Lua}}==
An explicit enum can be formed by mapping strings to numbers
 
<langsyntaxhighlight lang="lua">
local fruit = {apple = 0, banana = 1, cherry = 2}
</syntaxhighlight>
</lang>
 
or simply by local variables.
 
<langsyntaxhighlight lang="lua">
local apple, banana, cherry = 0,1,2
</syntaxhighlight>
</lang>
 
Although since Lua strings are interned, there is as much benefit to simply using strings.
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
\\ need revision 15, version 9.4
Line 1,202 ⟶ 1,273:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`enums',
`define(`$2',$1)`'ifelse(eval($#>2),1,`enums(incr($1),shift(shift($@)))')')
define(`enum',
`enums(1,$@)')
enum(a,b,c,d)
`c='c</langsyntaxhighlight>
 
{{out}}
Line 1,219 ⟶ 1,290:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Enumerations are not very useful in a symbolic language like Mathematica. If desired, an 'enum' function could be defined :
<langsyntaxhighlight Mathematicalang="mathematica">MapIndexed[Set, {A, B, F, G}]
->{{1}, {2}, {3}, {4}}
 
Line 1,229 ⟶ 1,300:
 
G
->{4}</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,235 ⟶ 1,306:
 
Example:
<langsyntaxhighlight MATLABlang="matlab">stuff = {'apple', [1 2 3], 'cherry',1+2i}
 
stuff =
 
'apple' [1x3 double] 'cherry' [1.000000000000000 + 2.000000000000000i]</langsyntaxhighlight>
 
=={{header|Metafont}}==
Metafont has no an enumeration type. However we can define an useful macro to simulate an enumeration. E.g.
<langsyntaxhighlight lang="metafont">vardef enum(expr first)(text t) =
save ?; ? := first;
forsuffixes e := t: e := ?; ?:=?+1; endfor
enddef;</langsyntaxhighlight>
 
Usage example:
 
<langsyntaxhighlight lang="metafont">enum(1, Apple, Banana, Cherry);
enum(5, Orange, Pineapple, Qfruit);
show Apple, Banana, Cherry, Orange, Pineapple, Qfruit;
 
end</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">TYPE Fruit = {Apple, Banana, Cherry};</langsyntaxhighlight>
The values are accessed by qualifying their names.
<langsyntaxhighlight lang="modula3">fruit := Fruit.Apple;</langsyntaxhighlight>
You can get an element's position in the enumeration by using <code>ORD</code> and get the element given the position by using <code>VAL</code>.
<langsyntaxhighlight lang="modula3">ORD(Fruit.Apple); (* Returns 0 *)
VAL(0, Fruit); (* Returns Fruit.Apple *)</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">enum Fruit {
|apple
|banana
Line 1,276 ⟶ 1,347:
|summer = 3
|autumn = 4
}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim"># Simple declaration.
type Fruits1 = enum aApple, aBanana, aCherry
 
Line 1,301 ⟶ 1,372:
Apple = (1, "apple")
Banana = 3 # implicit name is "Banana".
Cherry = "cherry" # implicit value is 4.</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
enum Color := -3 {
Red,
Line 1,316 ⟶ 1,387:
Terrier
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
With iOS 6+ SDK / Mac OS X 10.8+ SDK:
<langsyntaxhighlight lang="objc">typedef NS_ENUM(NSInteger, fruits) { apple, banana, cherry };
 
typedef NS_ENUM(NSInteger, fruits) { apple = 0, banana = 1, cherry = 2 };</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">type fruit =
| Apple
| Banana
| Cherry</langsyntaxhighlight>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
Fruit :: enum {
Apple,
Banana,
Cherry,
}
 
FruitWithNumber :: enum {
Strawberry = 0,
Pear = 27,
}
 
main :: proc() {
b := Fruit.Banana
assert(int(b) == 1) // Enums always have implicit values
 
p := FruitWithNumber.Pear
assert(int(p) == 27)
}</syntaxhighlight>
 
=={{header|Oforth}}==
Line 1,338 ⟶ 1,432:
Symbols begin with $. If the symbol does not exists yet, it is created.
 
<langsyntaxhighlight Oforthlang="oforth">[ $apple, $banana, $cherry ] const: Fruits</langsyntaxhighlight>
 
=={{header|Ol}}==
Ol enumerations is an builtin "ff"s as a simple fast dictionaries with number, constant or symbol keys and any typed values.
 
<langsyntaxhighlight lang="scheme">
(define fruits '{
apple 0
Line 1,371 ⟶ 1,465:
(print (make-enumeration 'apple 'banana 'cherry))
; ==> '#ff((apple . 0) (banana . 1) (cherry . 2))
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
 
<syntaxhighlight lang="text">
enum fruits
apple
Line 1,392 ⟶ 1,486:
' banana 15
' mango 16
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
Most of the time you will just use atoms where you would use enums in C. Atoms start with a lower-case letter and are just symbols that evaluate to themselves. For example:
<langsyntaxhighlight lang="oz">declare
fun {IsFruit A}
{Member A [apple banana cherry]}
end
in
{Show {IsFruit banana}}</langsyntaxhighlight>
 
If you need constants with increasing values, you could just enumerate them manually:
<langsyntaxhighlight lang="oz">declare
Apple = 1
Banana = 2
Cherry = 3</langsyntaxhighlight>
 
Or you could write a procedure that does the job automatically:
<langsyntaxhighlight lang="oz">declare
proc {Enumeration Xs}
Xs = {List.number 1 {Length Xs} 1}
Line 1,417 ⟶ 1,511:
[Apple Banana Cherry] = {Enumeration}
in
{Show Cherry}</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,423 ⟶ 1,517:
An explicit index may not be specified, but [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]] allow this.
However, it is guaranteed, that the <tt>ord</tt>inal value will correspond to the member’s position in the list (<tt>0</tt>-based).
<langsyntaxhighlight lang="pascal">type
phase = (red, green, blue);</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl"># Using an array
my @fruits = qw(apple banana cherry);
 
# Using a hash
my %fruits = ( apple => 0, banana => 1, cherry => 2 );</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">enum</span> <span style="color: #000000;">apple<span style="color: #0000FF;">,</span> <span style="color: #000000;">banana<span style="color: #0000FF;">,</span> <span style="color: #000000;">orange</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">apple<span style="color: #0000FF;">=<span style="color: #000000;">5<span style="color: #0000FF;">,</span> <span style="color: #000000;">banana<span style="color: #0000FF;">=<span style="color: #000000;">10<span style="color: #0000FF;">,</span> <span style="color: #000000;">orange<span style="color: #0000FF;">=
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">// Using an array/hash
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );
Line 1,458 ⟶ 1,552:
define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);</langsyntaxhighlight>
 
=={{header|Picat}}==
Line 1,464 ⟶ 1,558:
Picat doesn't have enumerations but they can be simulated by facts.
 
<langsyntaxhighlight Picatlang="picat">fruit(apple,1).
fruit(banana,2).
fruit(cherry,4).
Line 1,470 ⟶ 1,564:
print_fruit_name(N) :-
fruit(Name,N),
printf("It is %w\nn", Name).</langsyntaxhighlight>
 
 
Line 1,476 ⟶ 1,570:
Enumerations are not very useful in a symbolic language like PicoLisp. If
desired, an 'enum' function could be defined:
<langsyntaxhighlight PicoLisplang="picolisp">(de enum "Args"
(mapc def "Args" (range 1 (length "Args"))) )</langsyntaxhighlight>
And used in this way:
<langsyntaxhighlight PicoLisplang="picolisp">: (enum A B C D E F)
-> F</langsyntaxhighlight>
<pre>: A
-> 1
Line 1,489 ⟶ 1,583:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
define ordinal animal (frog, gnu, elephant, snake);
 
define ordinal color (red value (1), green value (3), blue value (5));
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Without explicit values.
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Enum fruits {
Apple
Line 1,507 ⟶ 1,601:
[fruits]::Apple + 1
[fruits]::Banana + 1
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 1,516 ⟶ 1,610:
With explicit values.
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Enum fruits {
Apple = 10
Line 1,525 ⟶ 1,619:
[fruits]::Apple + 1
[fruits]::Banana + 1
</syntaxhighlight>
</lang>
<pre>
Apple
Line 1,535 ⟶ 1,629:
Prolog doesn't have enums, but they can be simulated using a set of facts.
 
<langsyntaxhighlight lang="prolog">fruit(apple,1).
fruit(banana,2).
fruit(cherry,4).
Line 1,541 ⟶ 1,635:
write_fruit_name(N) :-
fruit(Name,N),
format('It is a ~p~n', Name).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Basic Enumeration is defined as
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
#Apple
#Banana
#Cherry
EndEnumeration</langsyntaxhighlight>
This can also be adjusted to the form
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration 10200 Step 12
#Constant1 ; 10200
#Constant2 ; 10212
Line 1,557 ⟶ 1,651:
#Constant4 = 10117 ; 10117
#Constant5 ; 10229
EndEnumeration</langsyntaxhighlight>
The system constant "#PB_Compiler_EnumerationValue" holds last defined value and can be used to chain to a previously started series.
 
E.g. in combination with the code above;
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration #PB_Compiler_EnumerationValue
#Constant_A ; 10241
#Constant_B ; 10242
EndEnumeration</langsyntaxhighlight>
 
Enumeration groups can also be named to allow continuation where a previous named group left off.
<langsyntaxhighlight PureBasiclang="purebasic">;This starts the enumeration of a named group 'NamedGroup'.
Enumeration NamedGroup 5
#Green ; 5
Line 1,585 ⟶ 1,679:
#Yellow ; 7
#Red ; 8
EndEnumeration</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,591 ⟶ 1,685:
Note: [http://www.python.org/dev/peps/pep-0435/ enumerations have come to Python version 3.4].
 
<langsyntaxhighlight lang="python">>>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
Line 1,605 ⟶ 1,699:
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>> </langsyntaxhighlight>
 
===Python: Pre version 3.4===
{{works with|Python|2.5}}
There is no special syntax, typically global variables are used with range:
<langsyntaxhighlight lang="python">FIRST_NAME, LAST_NAME, PHONE = range(3)</langsyntaxhighlight>
Alternately, the above variables can be enumerated from a list with no predetermined length.
<langsyntaxhighlight lang="python">vars().update((key,val) for val,key in enumerate(("FIRST_NAME","LAST_NAME","PHONE")))</langsyntaxhighlight>
 
=={{header|R}}==
R does not have an enumeration type, though factors provide a similar functionality.
<langsyntaxhighlight Rlang="r"> factor(c("apple", "banana", "cherry"))
# [1] apple banana cherry
# Levels: apple banana cherry</langsyntaxhighlight>
[http://tolstoy.newcastle.edu.au/R/help/04/07/0368.html This thread] in the R mail archive contains code for an enum-like class for traffic light colours.
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,665 ⟶ 1,759:
((ctype-c->scheme _fruits) 4) ; -> '(CHERRY)
((ctype-c->scheme _fruits) 5) ; -> '(APPLE CHERRY)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,671 ⟶ 1,765:
{{works with|Rakudo|2016.01}}
 
<syntaxhighlight lang="raku" perl6line>enum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.
 
enum ClassicalElement (
Line 1,678 ⟶ 1,772:
'Fire', # gets the value 7
Water => 10,
);</langsyntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight lang="raven">{ 'apple' 0 'banana' 1 'cherry' 2 } as fruits</langsyntaxhighlight>
 
=={{header|Retro}}==
Retro has a library named '''enum'''' for creation of enumerated values.
 
<langsyntaxhighlight Retrolang="retro">'/examples/enum.retro include
 
{ 'a=10 'b 'c 'd=998 'e 'f } a:enum
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Line 1,696 ⟶ 1,790:
<br>This REXX entry was kinda modeled after the '''BASIC''', '''Forth''', and
'''VBA''' [which does its own enumeration, as does REXX below (as an inventory count)].
<langsyntaxhighlight lang="rexx">/*REXX program illustrates a method of enumeration of constants via stemmed arrays. */
fruit.=0 /*the default for all possible "FRUITS." (zero). */
fruit.apple = 65
Line 1,750 ⟶ 1,844:
end /*j*/
end /*p*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output'''
<pre>
Line 1,771 ⟶ 1,865:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
apple = 0
banana = 1
Line 1,778 ⟶ 1,872:
see "banana : " + banana + nl
see "cherry : " + cherry + nl
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
There are plenty of ways to represent '''enum''' in Ruby. Here it is just one example:
<langsyntaxhighlight lang="ruby">module Fruits
APPLE = 0
BANANA = 1
Line 1,792 ⟶ 1,886:
FRUITS = [:apple, :banana, :cherry]
val = :banana
FRUITS.include?(val) #=> true</langsyntaxhighlight>
To give a number in turn, there is the following method.
<langsyntaxhighlight lang="ruby">module Card
# constants
SUITS = %i(Clubs Hearts Spades Diamonds)
Line 1,805 ⟶ 1,899:
# PIP_VALUE = Hash[ PIPS.each.with_index(2).to_a ] # before it
#=> {:"2"=>2, :"3"=>3, :"4"=>4, :"5"=>5, :"6"=>6, :"7"=>7, :"8"=>8, :"9"=>9, :"10"=>10, :Jack=>11, :Queen=>12, :King=>13, :Ace=>14}
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">enum Fruits {
Apple,
Banana,
Line 1,822 ⟶ 1,916:
// Access to numerical value by conversion
println!("{}", FruitsWithNumbers::Pear as u8);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
'''1. Using Algebraic Data Types:'''
<langsyntaxhighlight lang="actionscript">sealed abstract class Fruit
case object Apple extends Fruit
case object Banana extends Fruit
case object Cherry extends Fruit
</syntaxhighlight>
</lang>
'''2. Using scala.Enumeration:'''
<langsyntaxhighlight lang="actionscript">object Fruit extends Enumeration {
val Apple, Banana, Cherry = Value
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define apple 0)
(define banana 1)
(define cherry 2)
Line 1,845 ⟶ 1,939:
(or (equal? 'apple atom)
(equal? 'banana atom)
(equal? 'cherry atom)))</langsyntaxhighlight>
(This section needs attention from someone familiar with Scheme idioms.)
===Using syntax extension===
{{works with|Chez Scheme}}
'''The Implementation'''
<langsyntaxhighlight lang="scheme">; Syntax that implements a C-like enum; items without assignment take next value.
; Form: (enum <name> <item>...)
; Where <name> is a symbol that will be the name of the enum; <item> are one or
Line 1,889 ⟶ 1,983:
(define sym nxint)
(set! name (cons (cons 'sym nxint) name))
(enum-help name (1+ nxint) rest ...)))))))</langsyntaxhighlight>
'''Example Use'''
<langsyntaxhighlight lang="scheme">(define-syntax test
(syntax-rules ()
((_ e)
Line 1,918 ⟶ 2,012:
(test y)
(test z)
(test bar)</langsyntaxhighlight>
{{out}}
<pre>The 'foo' enum:
Line 1,939 ⟶ 2,033:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const type: fruits is new enum
apple, banana, cherry
end enum;</langsyntaxhighlight>
 
=={{header|Shen}}==
<langsyntaxhighlight lang="shen">(tc +)
 
(datatype fruit
Line 1,950 ⟶ 2,044:
if (element? Fruit [apple banana cherry])
_____________
Fruit : fruit;)</langsyntaxhighlight>
 
=={{header|Sidef}}==
Implicit:
<langsyntaxhighlight lang="ruby">enum {Apple, Banana, Cherry}; # numbered 0 through 2</langsyntaxhighlight>
Explicit:
<langsyntaxhighlight lang="ruby">enum {
Apple=3,
Banana, # gets the value 4
Cherry="a",
Orange, # gets the value "b"
};</langsyntaxhighlight>
 
=={{header|Slate}}==
As just unique objects:
<langsyntaxhighlight lang="slate">define: #Fruit &parents: {Cloneable}.
Fruit traits define: #Apple -> Fruit clone.
Fruit traits define: #Banana -> Fruit clone.
Fruit traits define: #Cherry -> Fruit clone.</langsyntaxhighlight>
 
As labels for primitive values:
<langsyntaxhighlight lang="slate">define: #Apple -> 1.
define: #Banana -> 2.
define: #Cherry -> 3.</langsyntaxhighlight>
 
As a namespace:
<langsyntaxhighlight lang="slate">ensureNamespace: #fruit &slots: {#Apple -> 1. #Banana -> 2. #Cherry -> 3}.</langsyntaxhighlight>
 
Using a dictionary:
<langsyntaxhighlight lang="slate">define: #fruit &builder: [{#Apple -> 1. #Banana -> 2. #Cherry -> 3} as: Dictionary].</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">datatype fruit =
Apple
| Banana
| Cherry</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">enum Fruit {
case Apple
case Banana
Line 2,003 ⟶ 2,097:
case Summer = 3
case Autumn = 4
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
It is normal in Tcl to use strings from a set directly rather than treating them as an enumeration, but enumerations can be simulated easily. The following elegant example comes straight from the [[http://wiki.tcl.tk/1308 Tcl wiki:]]
 
<langsyntaxhighlight lang="tcl">proc enumerate {name values} {
interp alias {} $name: {} lsearch $values
interp alias {} $name@ {} lindex $values
}</langsyntaxhighlight>
 
it would be used like this:
 
<langsyntaxhighlight lang="tcl">enumerate fruit {apple blueberry cherry date elderberry}
fruit: date
# ==> prints "3"
fruit@ 2
# ==> prints "cherry"</langsyntaxhighlight>
 
=={{header|Toka}}==
Line 2,027 ⟶ 2,121:
This library function takes a starting value and a list of names as shown in the example below.
 
<langsyntaxhighlight lang="toka">needs enum
0 enum| apple banana carrot |
10 enum| foo bar baz |</langsyntaxhighlight>
 
=={{header|VBA}}==
Like Visual Basic .NET, actually:
<syntaxhighlight lang="vb">
<lang vb>
'this enumerates from 0
Enum fruits
Line 2,057 ⟶ 2,151:
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,067 ⟶ 2,161:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">' Is this valid?!
Enum fruits
apple
Line 2,079 ⟶ 2,173:
banana = 1
cherry = 2
End Enum</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 2,085 ⟶ 2,179:
 
The only way to give such a variable a value without setting it explicitly is to add one to the previous such variable which (in effect) is what a C-style enum does. If you declare a variable in Wren without giving it a value, then it is set to the special value ''null'' which is no help here.
<langsyntaxhighlight ecmascriptlang="wren">var APPLE = 1
var ORANGE = 2
var PEAR = 3
Line 2,093 ⟶ 2,187:
var GRAPE = BANANA + 1
 
System.print([APPLE, ORANGE, PEAR, CHERRY, BANANA, GRAPE])</langsyntaxhighlight>
 
{{out}}
Line 2,103 ⟶ 2,197:
<br>
{{libheader|Wren-dynamic}}
<langsyntaxhighlight ecmascriptlang="wren">import "./dynamic" for Enum
 
var Fruit = Enum.create("Fruit", ["apple", "orange", "pear", "cherry", "banana", "grape"], 1)
System.print(Fruit.orange)
System.print(Fruit.members[Fruit.cherry - 1])</langsyntaxhighlight>
 
{{out}}
Line 2,116 ⟶ 2,210:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">def \Fruit\ Apple, Banana, Cherry; \Apple=0, Banana=1, Cherry=2
def Apple=1, Banana=2, Cherry=4;
</syntaxhighlight>
</lang>
 
=={{header|Z80 Assembly}}==
Line 2,126 ⟶ 2,220:
 
Keep in mind that these names do not exist at runtime and are just for the programmer's convenience. None of this "code" below actually takes up any space in the assembled program.
<langsyntaxhighlight lang="z80">Sunday equ 0
Monday equ 1
Tuesday equ 2
Line 2,132 ⟶ 2,226:
Thursday equ 4
Friday equ 5
Saturday equ 6</langsyntaxhighlight>
 
===Without Explicit Values===
A lookup table is the most common method of enumeration of actual data in assembly. Each element of the table can be accessed by an index, and the starting index is zero. (The index may need to be adjusted for data sizes larger than 1 byte, i.e. doubled for 16-bit data and quadrupled for 32-bit data.) Unlike the above example, these values do indeed take up memory. Using this method when the above enumeration would suffice is incredibly wasteful.
 
<langsyntaxhighlight lang="z80">align 8 ;aligns "Days_Of_The_Week" to the next 256-byte boundary. The low byte of "Sunday" will be at memory location &XX00.
;this simplifies the lookup process significantly.
Days_Of_The_Week:
Line 2,170 ⟶ 2,264:
call PrintString ;prints a null-terminated string to the screen.
ret ;return to basic
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,179 ⟶ 2,273:
=={{header|zkl}}==
Enums as thing or type is not supported but they can be simulated by running code at parse time (ie modify the AST before the compiler compiles it).
<langsyntaxhighlight lang="zkl">const RGB_COLOR{ // put color names in a name space
const RED =0xf00;
const BLUE=0x0f0, GREEN = 0x00f;
const CYAN=BLUE + GREEN; // → 0x0ff
}
println(RGB_COLOR.BLUE);</langsyntaxhighlight>
{{out}}
<pre>240</pre>
 
<langsyntaxhighlight lang="zkl">const X0=N; // --> 0
const A=N,B=N,C=N; // --> 1,2,3
const{ _n=-1; } // reset Enum, this should be a const space function
const X=N; // -->0</langsyntaxhighlight>
Since const space runs at a different time [vs compile space], you need to really careful if you mix the two [spaces]:
<langsyntaxhighlight lang="zkl">#continuing ...
z:=N; // -->2 NOT 1 as it is set AFTER Y (compile time vs parse time)
const Y=N; // -->1! because it is set before z</langsyntaxhighlight>
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module Enumerations;
type
Line 2,214 ⟶ 2,308:
end
end Enumerations.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
9,476

edits