Enumerations: Difference between revisions

Content added Content deleted
m (sntax highlighting fixup automation)
Line 6: Line 6:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>T.enum TokenCategory
<syntaxhighlight lang="11l">T.enum TokenCategory
NAME
NAME
KEYWORD
KEYWORD
CONSTANT
CONSTANT
TEST_CATEGORY = 10</lang>
TEST_CATEGORY = 10</syntaxhighlight>


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
Line 17: 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.
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.
<lang 6502asm>Sunday equ 0
<syntaxhighlight lang="6502asm">Sunday equ 0
Monday equ 1
Monday equ 1
Tuesday equ 2
Tuesday equ 2
Line 23: Line 23:
Thursday equ 4
Thursday equ 4
Friday equ 5
Friday equ 5
Saturday equ 6</lang>
Saturday equ 6</syntaxhighlight>


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:
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:
<lang 6502asm>enum $0400
<syntaxhighlight lang="6502asm">enum $0400
OBJECT_XPOS .dsb 16 ;define 16 bytes for object X position
OBJECT_XPOS .dsb 16 ;define 16 bytes for object X position
OBJECT_YPOS .dsb 16 ;define 16 bytes for object Y position
OBJECT_YPOS .dsb 16 ;define 16 bytes for object Y position
ende</lang>
ende</syntaxhighlight>


===Without Explicit Values===
===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.
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.


<lang 6502asm>Days_Of_The_Week:
<syntaxhighlight lang="6502asm">Days_Of_The_Week:
word Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
word Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday


Line 63: Line 63:
LDY #0 ;clear Y
LDY #0 ;clear Y


LDA ($00),Y ;Load the "W" of Wednesday into accumulator</lang>
LDA ($00),Y ;Load the "W" of Wednesday into accumulator</syntaxhighlight>


=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
Line 71: 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.
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.
<lang 68000devpac>Sunday equ 0
<syntaxhighlight lang="68000devpac">Sunday equ 0
Monday equ 1
Monday equ 1
Tuesday equ 2
Tuesday equ 2
Line 77: Line 77:
Thursday equ 4
Thursday equ 4
Friday equ 5
Friday equ 5
Saturday equ 6</lang>
Saturday equ 6</syntaxhighlight>




Line 85: 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.
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.


<lang 68000devpac>Days_Of_The_Week:
<syntaxhighlight lang="68000devpac">Days_Of_The_Week:
DC.L Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
DC.L Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday


Line 117: Line 117:
LEA (A0,D0),A1 ;load table offset by D0 into A1
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.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.</lang>
MOVE.B (A1)+,D1 ;Load the "T" of Thursday into D1, auto-increment to next letter for the next load.</syntaxhighlight>


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
Line 123: Line 123:
===With Explicit Values===
===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.
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.
<lang asm>Sunday equ 0
<syntaxhighlight lang="asm">Sunday equ 0
Monday equ 1
Monday equ 1
Tuesday equ 2
Tuesday equ 2
Line 130: Line 130:
Friday equ 5
Friday equ 5
Saturday equ 6
Saturday equ 6
Sunday equ 7</lang>
Sunday equ 7</syntaxhighlight>


===Without Explicit Values===
===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.
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.
<lang asm>mov ax,seg DaysOfTheWeek
<syntaxhighlight lang="asm">mov ax,seg DaysOfTheWeek
mov ds,ax
mov ds,ax
mov si,offset DaysOfTheWeek
mov si,offset DaysOfTheWeek
Line 146: Line 146:


DaysOfTheWeek word Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
DaysOfTheWeek word Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
;each is a pointer to a string containing the text you would expect.</lang>
;each is a pointer to a string containing the text you would expect.</syntaxhighlight>




Line 153: Line 153:
ACL2 doesn't have built-in enumerated types, but these macros add some basic support:
ACL2 doesn't have built-in enumerated types, but these macros add some basic support:


<lang Lisp>(defun symbol-to-constant (sym)
<syntaxhighlight lang="lisp">(defun symbol-to-constant (sym)
(intern (concatenate 'string "*" (symbol-name sym) "*")
(intern (concatenate 'string "*" (symbol-name sym) "*")
"ACL2"))
"ACL2"))
Line 174: Line 174:


(defmacro enum (&rest symbols)
(defmacro enum (&rest symbols)
`(enum-with-vals ,@(interleave-with-nats symbols)))</lang>
`(enum-with-vals ,@(interleave-with-nats symbols)))</syntaxhighlight>


=={{header|Ada}}==
=={{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.
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.
<lang ada>type Fruit is (apple, banana, cherry); -- No specification of the representation value;
<syntaxhighlight 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</lang>
for Fruit use (apple => 1, banana => 2, cherry => 4); -- specification of the representation values</syntaxhighlight>
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.
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: Line 195:
compatible with INT and so FRUITS inherit/share all INT's operators
compatible with INT and so FRUITS inherit/share all INT's operators
and procedures.
and procedures.
<lang algol68>BEGIN # example 1 #
<syntaxhighlight lang="algol68">BEGIN # example 1 #
MODE FRUIT = INT;
MODE FRUIT = INT;
FRUIT apple = 1, banana = 2, cherry = 4;
FRUIT apple = 1, banana = 2, cherry = 4;
Line 207: Line 207:
SKIP # other values #
SKIP # other values #
ESAC
ESAC
END;</lang>
END;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 224: Line 224:
least REPR (or ABS for INT type) must be defined if anything other then a
least REPR (or ABS for INT type) must be defined if anything other then a
'''case''' conditional clause is required.
'''case''' conditional clause is required.
<lang algol68>BEGIN # example 2 #
<syntaxhighlight lang="algol68">BEGIN # example 2 #
MODE ENUM = [0]CHAR; # something with minimal size #
MODE ENUM = [0]CHAR; # something with minimal size #
MODE APPLE = STRUCT(ENUM apple), BANANA = STRUCT(ENUM banana), CHERRY = STRUCT(ENUM cherry);
MODE APPLE = STRUCT(ENUM apple), BANANA = STRUCT(ENUM banana), CHERRY = STRUCT(ENUM cherry);
Line 247: Line 247:
SKIP # uninitialised FRUIT #
SKIP # uninitialised FRUIT #
ESAC
ESAC
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 257: Line 257:


=={{header|AmigaE}}==
=={{header|AmigaE}}==
<lang amigae>ENUM APPLE, BANANA, CHERRY
<syntaxhighlight lang="amigae">ENUM APPLE, BANANA, CHERRY


PROC main()
PROC main()
Line 263: Line 263:
ForAll({x}, [APPLE, BANANA, CHERRY],
ForAll({x}, [APPLE, BANANA, CHERRY],
`WriteF('\d\n', x))
`WriteF('\d\n', x))
ENDPROC</lang>
ENDPROC</syntaxhighlight>


writes 0, 1, 2 to the console.
writes 0, 1, 2 to the console.
Line 269: Line 269:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>enum: [apple banana cherry]
<syntaxhighlight lang="rebol">enum: [apple banana cherry]
print "as a block of words:"
print "as a block of words:"
inspect.muted enum
inspect.muted enum
Line 283: Line 283:
]
]
print "\nas a dictionary:"
print "\nas a dictionary:"
print enum</lang>
print enum</syntaxhighlight>


{{out}}
{{out}}
Line 304: 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:
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:


<lang ATS>datatype my_enum =
<syntaxhighlight lang="ats">datatype my_enum =
| value_a
| value_a
| value_b
| value_b
| value_c</lang>
| value_c</syntaxhighlight>


Within ATS itself, '''my_enum''' is a special case of recursive type definition. Similar facilities are available in ML dialects and other languages.
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.):
To "enumerate" with explicit integer values, I would simply define some constants, probably with '''#define''' (so I could use them in static expressions, etc.):
<lang ATS>#define value_a 1
<syntaxhighlight lang="ats">#define value_a 1
#define value_b 2
#define value_b 2
#define value_c 3</lang>
#define value_c 3</syntaxhighlight>


You could still restrict things so no other values were possible:
You could still restrict things so no other values were possible:


<lang ATS>typedef my_enum = [i : int | value_a <= i; i <= value_c] int i</lang>
<syntaxhighlight lang="ats">typedef my_enum = [i : int | value_a <= i; i <= value_c] int i</syntaxhighlight>


The value of a '''my_enum''' would be enforced ''at compile time''.
The value of a '''my_enum''' would be enforced ''at compile time''.
Line 325: Line 325:
AutoHotkey doesn't really enforce types. <br>
AutoHotkey doesn't really enforce types. <br>
However you can simulate types like enumeration with associative arrays:
However you can simulate types like enumeration with associative arrays:
<lang AutoHotkey>fruit_%apple% = 0
<syntaxhighlight lang="autohotkey">fruit_%apple% = 0
fruit_%banana% = 1
fruit_%banana% = 1
fruit_%cherry% = 2</lang>
fruit_%cherry% = 2</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
In awk we can use an array, for mapping both ways, or initialize variables:
In awk we can use an array, for mapping both ways, or initialize variables:
<lang awk>fruit["apple"]=1; fruit["banana"]=2; fruit["cherry"]=3
<syntaxhighlight lang="awk">fruit["apple"]=1; fruit["banana"]=2; fruit["cherry"]=3
fruit[1]="apple"; fruit[2]="banana"; fruit[3]="cherry"
fruit[1]="apple"; fruit[2]="banana"; fruit[3]="cherry"
i=0; apple=++i; banana=++i; cherry=++i;</lang>
i=0; apple=++i; banana=++i; cherry=++i;</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 339: Line 339:


{{works with|PB|7.1}}
{{works with|PB|7.1}}
<lang qbasic>REM Impossible. Can only be faked with arrays of strings.
<syntaxhighlight lang="qbasic">REM Impossible. Can only be faked with arrays of strings.
OPTION BASE 1
OPTION BASE 1
DIM SHARED fruitsName$(1 to 3)
DIM SHARED fruitsName$(1 to 3)
Line 354: Line 354:
apple% = 1
apple% = 1
banana% = 2
banana% = 2
cherry% = 3</lang>
cherry% = 3</syntaxhighlight>


==={{header|BaCon}}===
==={{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.
BaCon includes an ENUM statement, with or without fixed values. If no value is given, enumerations start at zero and increase by integer 1.


<lang freebasic>' Enumerations
<syntaxhighlight lang="freebasic">' Enumerations
' Start at zero
' Start at zero
ENUM
ENUM
Line 376: Line 376:
sunday=7, monday=1, tuesday, wednesday, thursday, friday, saturday
sunday=7, monday=1, tuesday, wednesday, thursday, friday, saturday
END ENUM
END ENUM
PRINT sunday, " ", wednesday, " ", saturday</lang>
PRINT sunday, " ", wednesday, " ", saturday</syntaxhighlight>


{{out}}
{{out}}
Line 389: 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.'
'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.
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.
<lang bracmat>fruits=apple+banana+cherry;</lang>
<syntaxhighlight lang="bracmat">fruits=apple+banana+cherry;</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>enum fruits { apple, banana, cherry };
<syntaxhighlight lang="c">enum fruits { apple, banana, cherry };


enum fruits { apple = 0, banana = 1, cherry = 2 };</lang>
enum fruits { apple = 0, banana = 1, cherry = 2 };</syntaxhighlight>


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


<lang c>typedef enum { apple, banana, cherry } fruits;
<syntaxhighlight lang="c">typedef enum { apple, banana, cherry } fruits;


typedef enum { apple = 0, banana = 1, cherry = 2 } fruits;</lang>
typedef enum { apple = 0, banana = 1, cherry = 2 } fruits;</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>enum fruits { apple, banana, cherry }
<syntaxhighlight lang="csharp">enum fruits { apple, banana, cherry }


enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits { apple = 0, banana = 1, cherry = 2 }
Line 410: Line 410:


[FlagsAttribute]
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }</lang>
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }</syntaxhighlight>


Placing FlagsAttribute before an enum allows you to perform bitwise operations on the value.
Placing FlagsAttribute before an enum allows you to perform bitwise operations on the value.
Line 416: Line 416:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>enum fruits { apple, banana, cherry };
<syntaxhighlight lang="cpp">enum fruits { apple, banana, cherry };


enum fruits { apple = 0, banana = 1, cherry = 2 };</lang>
enum fruits { apple = 0, banana = 1, cherry = 2 };</syntaxhighlight>
Note that, unlike in C, you can refer to the type here as <code>fruits</code>.
Note that, unlike in C, you can refer to the type here as <code>fruits</code>.


Line 424: Line 424:
{{works with|C++11}}
{{works with|C++11}}
C++11 introduced "strongly typed enumerations", enumerations that cannot be implicitly converted to/from integers:
C++11 introduced "strongly typed enumerations", enumerations that cannot be implicitly converted to/from integers:
<lang cpp>enum class fruits { apple, banana, cherry };
<syntaxhighlight lang="cpp">enum class fruits { apple, banana, cherry };


enum class fruits { apple = 0, banana = 1, cherry = 2 };</lang>
enum class fruits { apple = 0, banana = 1, cherry = 2 };</syntaxhighlight>


These enumeration constants must be referred to as <code>fruits::apple</code>, not just <code>apple</code>.
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>:
You can explicitly specify an underlying type for the enum; the default is <code>int</code>:
<lang cpp>enum class fruits : unsigned int { apple, banana, cherry };</lang>
<syntaxhighlight lang="cpp">enum class fruits : unsigned int { apple, banana, cherry };</syntaxhighlight>


You can also explicitly specify an underlying type for old-style enums:
You can also explicitly specify an underlying type for old-style enums:
<lang cpp>enum fruits : unsigned int { apple, banana, cherry };</lang>
<syntaxhighlight lang="cpp">enum fruits : unsigned int { apple, banana, cherry };</syntaxhighlight>


=={{header|Clojure}}==
=={{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:
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:
<lang clojure>; a set of keywords
<syntaxhighlight lang="clojure">; a set of keywords
(def fruits #{:apple :banana :cherry})
(def fruits #{:apple :banana :cherry})


Line 448: Line 448:


(println (fruit? :apple))
(println (fruit? :apple))
(println (fruit-value :banana))</lang>
(println (fruit-value :banana))</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Values:
Values:


<lang lisp>;; symbol to number
<syntaxhighlight lang="lisp">;; symbol to number
(defconstant +apple+ 0)
(defconstant +apple+ 0)
(defconstant +banana+ 1)
(defconstant +banana+ 1)
Line 460: Line 460:
;; number to symbol
;; number to symbol
(defun index-fruit (i)
(defun index-fruit (i)
(aref #(+apple+ +banana+ +cherry+) i))</lang>
(aref #(+apple+ +banana+ +cherry+) i))</syntaxhighlight>
Of course, the two definitions above can be produced by a single macro, if desired.
Of course, the two definitions above can be produced by a single macro, if desired.


Defining a type for documentation or checking purposes:
Defining a type for documentation or checking purposes:


<lang lisp>(deftype fruit ()
<syntaxhighlight lang="lisp">(deftype fruit ()
'(member +apple+ +banana+ +cherry+))</lang>
'(member +apple+ +banana+ +cherry+))</syntaxhighlight>
=={{header|Computer/zero Assembly}}==
=={{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.
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.
<lang 6502asm>LDA 4 ;load from memory address 4
<syntaxhighlight lang="6502asm">LDA 4 ;load from memory address 4
STP
STP
NOP
NOP
NOP
NOP
byte 1</lang>
byte 1</syntaxhighlight>
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.
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}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
// Named enumeration (commonly used enum in D).
// Named enumeration (commonly used enum in D).
// The underlying type is a 32 bit int.
// The underlying type is a 32 bit int.
Line 526: Line 526:
// Use the & operator between BitFlags for intersection.
// Use the & operator between BitFlags for intersection.
assert (flagsGreen == (flagsRedGreen & flagsBlueGreen));
assert (flagsGreen == (flagsRedGreen & flagsBlueGreen));
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
In addition to [[#Pascal|standard Pascal]], one may explicitly specify an index:
In addition to [[#Pascal|standard Pascal]], one may explicitly specify an index:
<syntaxhighlight lang="delphi">type
<lang Delphi>type
fruit = (apple, banana, cherry);
fruit = (apple, banana, cherry);
ape = (gorilla = 0, chimpanzee = 1, orangutan = 5);</lang>
ape = (gorilla = 0, chimpanzee = 1, orangutan = 5);</syntaxhighlight>
Note, explicit indices ''have'' to be in ascending order.
Note, explicit indices ''have'' to be in ascending order.
You can also just specify explicit indices for ''some'' items.
You can also just specify explicit indices for ''some'' items.
Line 540: Line 540:


With explicit values:
With explicit values:
<lang Diego>add_enum(⟪{int}⟫,⟦{str}⟧,urgency)
<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(⟪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(⟪3⟫,⟦exigent⟧)_static(URGENT_EXIGENT)_colour(orange)_color({hex},#ff6400)_desc(The high urgent state, high risk.);
Line 546: Line 546:
()_enum(⟪1⟫,⟦infergent⟧)_static(URGENT_INFERGENT)_colour(blue)_color({hex},#3566cd)_desc(The low urgent state, low / guarded 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.);
()_enum(⟪0⟫,⟦nonurgent⟧)_static(URGENT_NON)_colour(green)_color({hex},#009a66)_desc(The non-urgent state, negligible risk.);
;</lang>
;</syntaxhighlight>


Without explicit values (and dynamic typing):
Without explicit values (and dynamic typing):
<lang Diego>add_enum(fruits,⟦apple,banana,cherry⟧);</lang>
<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.
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.


<lang Diego>add_flag(ape,⟦gorilla,chimpanzee,orangutan⟧);
<syntaxhighlight lang="diego">add_flag(ape,⟦gorilla,chimpanzee,orangutan⟧);
log_console()_(ape);</lang>
log_console()_(ape);</syntaxhighlight>


Output:
Output:
Line 562: Line 562:
=={{header|DWScript}}==
=={{header|DWScript}}==


<lang Delphi>type TFruit = (Apple, Banana, Cherry);
<syntaxhighlight lang="delphi">type TFruit = (Apple, Banana, Cherry);
type TApe = (Gorilla = 0, Chimpanzee = 1, Orangutan = 5);</lang>
type TApe = (Gorilla = 0, Chimpanzee = 1, Orangutan = 5);</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
Simple group of object definitions (value methods could be left out if appropriate):
Simple group of object definitions (value methods could be left out if appropriate):


<lang e>def apple { to value() { return 0 } }
<syntaxhighlight lang="e">def apple { to value() { return 0 } }
def banana { to value() { return 1 } }
def banana { to value() { return 1 } }
def cherry { to value() { return 2 } }</lang>
def cherry { to value() { return 2 } }</syntaxhighlight>
With a guard for type checks:
With a guard for type checks:
<lang e>interface Fruit guards FruitStamp {}
<syntaxhighlight lang="e">interface Fruit guards FruitStamp {}
def apple implements FruitStamp {}
def apple implements FruitStamp {}
def banana implements FruitStamp {}
def banana implements FruitStamp {}
def cherry implements FruitStamp {}
def cherry implements FruitStamp {}


def eat(fruit :Fruit) { ... }</lang>
def eat(fruit :Fruit) { ... }</syntaxhighlight>
With and without values, using a hypothetical enumeration library:
With and without values, using a hypothetical enumeration library:
<lang e>def [Fruit, [=> apple, => banana, => cherry]] := makeEnumeration()
<syntaxhighlight lang="e">def [Fruit, [=> apple, => banana, => cherry]] := makeEnumeration()


def [Fruit, [=> apple, => banana, => cherry]] :=
def [Fruit, [=> apple, => banana, => cherry]] :=
makeEnumeration(0, ["apple", "banana", "cherry"])</lang>
makeEnumeration(0, ["apple", "banana", "cherry"])</syntaxhighlight>


=={{header|EGL}}==
=={{header|EGL}}==
{{works with|EDT}}
{{works with|EDT}}
<lang EGL>// Without explicit values
<syntaxhighlight lang="egl">// Without explicit values
enumeration FruitsKind
enumeration FruitsKind
APPLE,
APPLE,
Line 612: Line 612:
end
end


end</lang>
end</syntaxhighlight>
{{works with|EDT}}
{{works with|EDT}}
-and-
-and-
{{works with|RBD}}
{{works with|RBD}}
<lang EGL>// With explicit values
<syntaxhighlight lang="egl">// With explicit values
library FruitsKind type BasicLibrary {}
library FruitsKind type BasicLibrary {}
const APPLE int = 0;
const APPLE int = 0;
Line 643: Line 643:
end
end
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
It is possible to use a atom if the value is unrelated.
It is possible to use a atom if the value is unrelated.
<lang elixir>fruits = [:apple, :banana, :cherry]
<syntaxhighlight lang="elixir">fruits = [:apple, :banana, :cherry]
fruits = ~w(apple banana cherry)a # Above-mentioned different notation
fruits = ~w(apple banana cherry)a # Above-mentioned different notation
val = :banana
val = :banana
Enum.member?(fruits, val) #=> true
Enum.member?(fruits, val) #=> true
val in fruits #=> true</lang>
val in fruits #=> true</syntaxhighlight>


If they have to have a specific value
If they have to have a specific value
<lang elixir>fruits = [{:apple, 1}, {:banana, 2}, {:cherry, 3}] # Keyword list
<syntaxhighlight 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, banana: 2, cherry: 3] # Above-mentioned different notation
fruits[:apple] #=> 1
fruits[:apple] #=> 1
Line 663: Line 663:
fruits[:apple] #=> 1
fruits[:apple] #=> 1
fruits.apple #=> 1 (Only When the key is Atom)
fruits.apple #=> 1 (Only When the key is Atom)
Map.has_key?(fruits, :banana) #=> true</lang>
Map.has_key?(fruits, :banana) #=> true</syntaxhighlight>


To give a number in turn, there is the following method.
To give a number in turn, there is the following method.
<lang elixir># Keyword list
<syntaxhighlight lang="elixir"># Keyword list
fruits = ~w(apple banana cherry)a |> Enum.with_index
fruits = ~w(apple banana cherry)a |> Enum.with_index
#=> [apple: 0, banana: 1, cherry: 2]
#=> [apple: 0, banana: 1, cherry: 2]
Line 672: Line 672:
# Map
# Map
fruits = ~w(apple banana cherry)a |> Enum.with_index |> Map.new
fruits = ~w(apple banana cherry)a |> Enum.with_index |> Map.new
#=> %{apple: 0, banana: 1, cherry: 2}</lang>
#=> %{apple: 0, banana: 1, cherry: 2}</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 680: Line 680:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
Enumerations in F# always have explicit values:
Enumerations in F# always have explicit values:
<lang fsharp>type Fruit =
<syntaxhighlight lang="fsharp">type Fruit =
| Apple = 0
| Apple = 0
| Banana = 1
| Banana = 1
Line 686: Line 686:


let basket = [ Fruit.Apple ; Fruit.Banana ; Fruit.Cherry ]
let basket = [ Fruit.Apple ; Fruit.Banana ; Fruit.Cherry ]
Seq.iter (printfn "%A") basket</lang>
Seq.iter (printfn "%A") basket</syntaxhighlight>


If the initialization values are omitted, the resulting type is a discriminated union (algebraic data type) instead.
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.
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.


<lang fsharp>type Fruit =
<syntaxhighlight lang="fsharp">type Fruit =
| Apple
| Apple
| Banana
| Banana
| Cherry
| Cherry
let basket = [ Apple ; Banana ; Cherry ]
let basket = [ Apple ; Banana ; Cherry ]
Seq.iter (printfn "%A") basket</lang>
Seq.iter (printfn "%A") basket</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==


Enumerations are essentially association lists with values (keys) assigned sequentially from constants (values) provided by an initial sequence.
Enumerations are essentially association lists with values (keys) assigned sequentially from constants (values) provided by an initial sequence.
<lang factor>IN: scratchpad { "sun" "mon" "tue" "wed" "thur" "fri" "sat" } <enum>
<syntaxhighlight lang="factor">IN: scratchpad { "sun" "mon" "tue" "wed" "thur" "fri" "sat" } <enum>


--- Data stack:
--- Data stack:
Line 709: Line 709:
--- Data stack:
--- Data stack:
"mon"
"mon"
{ 0 1 2 3 4 5 6 }</lang>
{ 0 1 2 3 4 5 6 }</syntaxhighlight>
Factor also provides C-like enumerations in its C library interface. These enumerations may have explicit values.
Factor also provides C-like enumerations in its C library interface. These enumerations may have explicit values.
<lang factor>IN: scratchpad USE: alien.syntax
<syntaxhighlight lang="factor">IN: scratchpad USE: alien.syntax
IN: scratchpad ENUM: day sun mon { tue 42 } wed thur fri sat ;
IN: scratchpad ENUM: day sun mon { tue 42 } wed thur fri sat ;
IN: scratchpad 1 <day>
IN: scratchpad 1 <day>
Line 721: Line 721:
--- Data stack:
--- Data stack:
mon
mon
tue</lang>
tue</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 727: Line 727:
Enumerations with named constants:
Enumerations with named constants:


<lang fantom>
<syntaxhighlight lang="fantom">
// create an enumeration with named constants
// create an enumeration with named constants
enum class Fruits { apple, banana, orange }
enum class Fruits { apple, banana, orange }
</syntaxhighlight>
</lang>


A private constructor can be added to initialise internal fields, which must be constant.
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
// create an enumeration with explicit values
enum class Fruits_
enum class Fruits_
Line 742: Line 742:
private new make (Int value) { this.value = value }
private new make (Int value) { this.value = value }
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Forth has no types, and therefore no enumeration type. To define sequential constants, a programmer might write code like this:
Forth has no types, and therefore no enumeration type. To define sequential constants, a programmer might write code like this:


<lang forth>0 CONSTANT apple
<syntaxhighlight lang="forth">0 CONSTANT apple
1 CONSTANT banana
1 CONSTANT banana
2 CONSTANT cherry
2 CONSTANT cherry
...</lang>
...</syntaxhighlight>
However, a common idiom in forth is to define a defining word, such as:
However, a common idiom in forth is to define a defining word, such as:
<lang forth>: ENUM ( n -<name>- n+1 ) DUP CONSTANT 1+ ;</lang>
<syntaxhighlight lang="forth">: ENUM ( n -<name>- n+1 ) DUP CONSTANT 1+ ;</syntaxhighlight>
This word defines a new constant of the value specified and returns the next value in sequence.
This word defines a new constant of the value specified and returns the next value in sequence.
It would be used like this:
It would be used like this:


<lang forth>0 ENUM APPLE ENUM BANANA ENUM CHERRY DROP</lang>
<syntaxhighlight lang="forth">0 ENUM APPLE ENUM BANANA ENUM CHERRY DROP</syntaxhighlight>


Or you can use CONSTANT to capture the "end" value instead of dropping it:
Or you can use CONSTANT to capture the "end" value instead of dropping it:


<lang forth>0 ENUM FIRST ENUM SECOND ... CONSTANT LAST</lang>
<syntaxhighlight lang="forth">0 ENUM FIRST ENUM SECOND ... CONSTANT LAST</syntaxhighlight>


A variation of this idea is the "stepped enumeration" that increases the value by more than 1, such as:
A variation of this idea is the "stepped enumeration" that increases the value by more than 1, such as:


<lang forth>: SIZED-ENUM ( n s -<name>- n+s ) OVER CONSTANT + ;
<syntaxhighlight lang="forth">: SIZED-ENUM ( n s -<name>- n+s ) OVER CONSTANT + ;
: CELL-ENUM ( n -<name>- n+cell ) CELL SIZED-ENUM ;</lang>
: CELL-ENUM ( n -<name>- n+cell ) CELL SIZED-ENUM ;</syntaxhighlight>


A programmer could combine these enum definers in any way desired:
A programmer could combine these enum definers in any way desired:


<lang forth>0 ENUM FIRST \ value = 0
<syntaxhighlight lang="forth">0 ENUM FIRST \ value = 0
CELL-ENUM SECOND \ value = 1
CELL-ENUM SECOND \ value = 1
ENUM THIRD \ value = 5
ENUM THIRD \ value = 5
3 SIZED-ENUM FOURTH \ value = 6
3 SIZED-ENUM FOURTH \ value = 6
ENUM FIFTH \ value = 9
ENUM FIFTH \ value = 9
CONSTANT SIXTH \ value = 10</lang>
CONSTANT SIXTH \ value = 10</syntaxhighlight>


Note that a similar technique is often used to implement structures in Forth.
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:
For a simple zero-based sequence of constants, one could use a loop in the defining word:
<lang forth>: CONSTANTS ( n -- ) 0 DO I CONSTANT LOOP ;
<syntaxhighlight lang="forth">: CONSTANTS ( n -- ) 0 DO I CONSTANT LOOP ;


\ resistor digit colors
\ resistor digit colors
10 CONSTANTS black brown red orange yellow green blue violet gray white</lang>
10 CONSTANTS black brown red orange yellow green blue violet gray white</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|2003}}
{{works with|Fortran|2003}}
<lang fortran>enum, bind(c)
<syntaxhighlight lang="fortran">enum, bind(c)
enumerator :: one=1, two, three, four, five
enumerator :: one=1, two, three, four, five
enumerator :: six, seven, nine=9
enumerator :: six, seven, nine=9
end enum</lang>
end enum</syntaxhighlight>


The syntax
The syntax


<lang fortran>enum, bind(c) :: nametype
<syntaxhighlight lang="fortran">enum, bind(c) :: nametype
enumerator :: one=1, two, three
enumerator :: one=1, two, three
end enum nametype</lang>
end enum nametype</syntaxhighlight>


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...)
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 806: Line 806:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Enum Animals
Enum Animals
Line 822: Line 822:
Print Cat, Dog, Zebra
Print Cat, Dog, Zebra
Print Bulldog, Terrier, WolfHound
Print Bulldog, Terrier, WolfHound
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 831: Line 831:


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang>window 1, @"Enumerations", (0,0,480,270)
<syntaxhighlight lang="text">window 1, @"Enumerations", (0,0,480,270)


begin enum 1
begin enum 1
Line 853: Line 853:
print "_cherryExplicit = "; _cherryExplicit
print "_cherryExplicit = "; _cherryExplicit


HandleEvents</lang>
HandleEvents</syntaxhighlight>


Output
Output
Line 868: Line 868:
=={{header|Go}}==
=={{header|Go}}==
Go's enumeration-like feature is called iota. It generates sequential integer constants.
Go's enumeration-like feature is called iota. It generates sequential integer constants.
<lang go>const (
<syntaxhighlight lang="go">const (
apple = iota
apple = iota
banana
banana
cherry
cherry
)</lang>
)</syntaxhighlight>
The above is equivalent to,
The above is equivalent to,
<lang go>const (
<syntaxhighlight lang="go">const (
apple = 0
apple = 0
banana = 1
banana = 1
cherry = 2
cherry = 2
)</lang>
)</syntaxhighlight>
Constants in Go are not typed they way variables are, they are typed when used just like literal constants.
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:
Here is an example of a type safe enumeration:
<lang go>type fruit int
<syntaxhighlight lang="go">type fruit int


const (
const (
Line 887: Line 887:
banana
banana
cherry
cherry
)</lang>
)</syntaxhighlight>
And using explicit values (note each constant must be individual typed here unlike with iota):
And using explicit values (note each constant must be individual typed here unlike with iota):
<lang go>type fruit int
<syntaxhighlight lang="go">type fruit int


const (
const (
Line 895: Line 895:
banana fruit = 1
banana fruit = 1
cherry fruit = 2
cherry fruit = 2
)</lang>
)</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Enumerations:
Enumerations:
<lang groovy>enum Fruit { apple, banana, cherry }
<syntaxhighlight lang="groovy">enum Fruit { apple, banana, cherry }


enum ValuedFruit {
enum ValuedFruit {
Line 909: Line 909:


println Fruit.values()
println Fruit.values()
println ValuedFruit.values()</lang>
println ValuedFruit.values()</syntaxhighlight>


{{out}}
{{out}}
Line 916: Line 916:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>data Fruit = Apple | Banana | Cherry deriving Enum</lang>
<syntaxhighlight lang="haskell">data Fruit = Apple | Banana | Cherry deriving Enum</syntaxhighlight>


=={{header|Huginn}}==
=={{header|Huginn}}==
<lang huginn>enum FRUIT {
<syntaxhighlight lang="huginn">enum FRUIT {
APPLE,
APPLE,
BANANA,
BANANA,
CHERRY
CHERRY
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{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:
Nether Icon nor Unicon has an explicit enumeration type; however, there are several approaches that can be used for this purpose:


<lang Icon> fruits := [ "apple", "banana", "cherry", "apple" ] # a list keeps ordered data
<syntaxhighlight lang="icon"> fruits := [ "apple", "banana", "cherry", "apple" ] # a list keeps ordered data
fruits := set("apple", "banana", "cherry") # a set keeps unique data
fruits := set("apple", "banana", "cherry") # a set keeps unique data
fruits := table() # table keeps an unique data with values
fruits := table() # table keeps an unique data with values
fruits["apple"] := 1
fruits["apple"] := 1
fruits["banana"] := 2
fruits["banana"] := 2
fruits["cherry"] := 3</lang>
fruits["cherry"] := 3</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
<lang inform7>Fruit is a kind of value. The fruits are apple, banana, and cherry.</lang>
<syntaxhighlight lang="inform7">Fruit is a kind of value. The fruits are apple, banana, and cherry.</syntaxhighlight>


Inform 7 doesn't have conversions between enumerated values and numbers, but you can assign properties to enumerated values:
Inform 7 doesn't have conversions between enumerated values and numbers, but you can assign properties to enumerated values:
<lang inform7>[sentence form]
<syntaxhighlight lang="inform7">[sentence form]
Fruit is a kind of value. The fruits are apple, banana, and cherry.
Fruit is a kind of value. The fruits are apple, banana, and cherry.
A fruit has a number called numeric value.
A fruit has a number called numeric value.
The numeric value of apple is 1.
The numeric value of apple is 1.
The numeric value of banana is 2.
The numeric value of banana is 2.
The numeric value of cherry is 3.</lang>
The numeric value of cherry is 3.</syntaxhighlight>
<lang inform7>[table form]
<syntaxhighlight lang="inform7">[table form]
Fruit is a kind of value. The fruits are defined by the Table of Fruits.
Fruit is a kind of value. The fruits are defined by the Table of Fruits.


Line 952: Line 952:
apple 1
apple 1
banana 2
banana 2
cherry 3</lang>
cherry 3</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


J's typing system is fixed, and so extensions occur at the application level. For example, one could create an object
J's typing system is fixed, and so extensions occur at the application level. For example, one could create an object
<lang j> enum =: cocreate''
<syntaxhighlight lang="j"> enum =: cocreate''
( (;:'apple banana cherry') ,L:0 '__enum' ) =: i. 3
( (;:'apple banana cherry') ,L:0 '__enum' ) =: i. 3
cherry__enum
cherry__enum
2</lang>
2</syntaxhighlight>


But this is more akin to a "methodless class or object" than an enum in other languages.
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.
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.
<lang j> fruit=: ;:'apple banana cherry'</lang>
<syntaxhighlight lang="j"> fruit=: ;:'apple banana cherry'</syntaxhighlight>


Now you can get the name associated with an index:
Now you can get the name associated with an index:


<lang j> 2 { fruit
<syntaxhighlight lang="j"> 2 { fruit
+------+
+------+
|cherry|
|cherry|
+------+</lang>
+------+</syntaxhighlight>


And you can get the index associated with a name:
And you can get the index associated with a name:


<lang j> fruit i.<'banana'
<syntaxhighlight lang="j"> fruit i.<'banana'
1</lang>
1</syntaxhighlight>


And you can define an arithmetic with the enum for its domain and range. Here, for example, is 2=1+1:
And you can define an arithmetic with the enum for its domain and range. Here, for example, is 2=1+1:


<lang j> (<'banana') +&.(fruit&i.) <'banana'
<syntaxhighlight lang="j"> (<'banana') +&.(fruit&i.) <'banana'
+------+
+------+
|cherry|
|cherry|
+------+</lang>
+------+</syntaxhighlight>


And, you can iterate over the values, along with numerous other variations on these themes.<lang J> {{for_example. fruit do. echo;example end.}} ''
And, you can iterate over the values, along with numerous other variations on these themes.<syntaxhighlight lang="j"> {{for_example. fruit do. echo;example end.}} ''
apple
apple
banana
banana
cherry</lang>
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.)
(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.)
Line 995: Line 995:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>enum Fruits{
<syntaxhighlight lang="java5">enum Fruits{
APPLE, BANANA, CHERRY
APPLE, BANANA, CHERRY
}</lang>
}</syntaxhighlight>
Or:
Or:
<lang java5>enum Fruits{
<syntaxhighlight lang="java5">enum Fruits{
APPLE(0), BANANA(1), CHERRY(2)
APPLE(0), BANANA(1), CHERRY(2)
private final int value;
private final int value;
fruits(int value) { this.value = value; }
fruits(int value) { this.value = value; }
public int value() { return value; }
public int value() { return value; }
}</lang>
}</syntaxhighlight>
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.
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 1,010: Line 1,010:
In javascript, usually used for this a strings.
In javascript, usually used for this a strings.


<lang javascript>
<syntaxhighlight lang="javascript">
// enum fruits { apple, banana, cherry }
// enum fruits { apple, banana, cherry }


Line 1,018: Line 1,018:
f = "banana";
f = "banana";
}
}
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
Line 1,035: Line 1,035:


=={{header|JScript.NET}}==
=={{header|JScript.NET}}==
<lang jscript>enum fruits { apple, banana, cherry }
<syntaxhighlight lang="jscript">enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }</lang>
enum fruits { apple = 0, banana = 1, cherry = 2 }</syntaxhighlight>


=={{header|JSON}}==
=={{header|JSON}}==
<lang json>{"fruits" : { "apple" : null, "banana" : null, "cherry" : null }
<syntaxhighlight lang="json">{"fruits" : { "apple" : null, "banana" : null, "cherry" : null }
{"fruits" : { "apple" : 0, "banana" : 1, "cherry" : 2 }</lang>
{"fruits" : { "apple" : 0, "banana" : 1, "cherry" : 2 }</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
@enum Fruits APPLE BANANA CHERRY
@enum Fruits APPLE BANANA CHERRY
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,058: Line 1,058:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


enum class Animals {
enum class Animals {
Line 1,072: Line 1,072:
println()
println()
for (value in Dogs.values()) println("${value.name.padEnd(9)} : ${value.id}")
for (value in Dogs.values()) println("${value.name.padEnd(9)} : ${value.id}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,088: Line 1,088:
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):
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):


<lang lingo>-- parent script "Enumeration"
<syntaxhighlight lang="lingo">-- parent script "Enumeration"


property ancestor
property ancestor
Line 1,119: Line 1,119:
on addProp (me)
on addProp (me)
-- do nothing
-- do nothing
end</lang>
end</syntaxhighlight>


<lang lingo>enumeration = script("Enumeration").new("APPLE", "BANANA", "CHERRY")
<syntaxhighlight lang="lingo">enumeration = script("Enumeration").new("APPLE", "BANANA", "CHERRY")


put enumeration["BANANA"]
put enumeration["BANANA"]
Line 1,154: Line 1,154:
enumeration.addProp("FOO", 666)
enumeration.addProp("FOO", 666)
put enumeration["FOO"]
put enumeration["FOO"]
-- <Void></lang>
-- <Void></syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
An explicit enum can be formed by mapping strings to numbers
An explicit enum can be formed by mapping strings to numbers


<lang lua>
<syntaxhighlight lang="lua">
local fruit = {apple = 0, banana = 1, cherry = 2}
local fruit = {apple = 0, banana = 1, cherry = 2}
</syntaxhighlight>
</lang>


or simply by local variables.
or simply by local variables.


<lang lua>
<syntaxhighlight lang="lua">
local apple, banana, cherry = 0,1,2
local apple, banana, cherry = 0,1,2
</syntaxhighlight>
</lang>


Although since Lua strings are interned, there is as much benefit to simply using strings.
Although since Lua strings are interned, there is as much benefit to simply using strings.


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
\\ need revision 15, version 9.4
\\ need revision 15, version 9.4
Line 1,229: Line 1,229:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`enums',
<syntaxhighlight lang="m4">define(`enums',
`define(`$2',$1)`'ifelse(eval($#>2),1,`enums(incr($1),shift(shift($@)))')')
`define(`$2',$1)`'ifelse(eval($#>2),1,`enums(incr($1),shift(shift($@)))')')
define(`enum',
define(`enum',
`enums(1,$@)')
`enums(1,$@)')
enum(a,b,c,d)
enum(a,b,c,d)
`c='c</lang>
`c='c</syntaxhighlight>


{{out}}
{{out}}
Line 1,246: Line 1,246:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Enumerations are not very useful in a symbolic language like Mathematica. If desired, an 'enum' function could be defined :
Enumerations are not very useful in a symbolic language like Mathematica. If desired, an 'enum' function could be defined :
<lang Mathematica>MapIndexed[Set, {A, B, F, G}]
<syntaxhighlight lang="mathematica">MapIndexed[Set, {A, B, F, G}]
->{{1}, {2}, {3}, {4}}
->{{1}, {2}, {3}, {4}}


Line 1,256: Line 1,256:


G
G
->{4}</lang>
->{4}</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,262: Line 1,262:


Example:
Example:
<lang MATLAB>stuff = {'apple', [1 2 3], 'cherry',1+2i}
<syntaxhighlight lang="matlab">stuff = {'apple', [1 2 3], 'cherry',1+2i}


stuff =
stuff =


'apple' [1x3 double] 'cherry' [1.000000000000000 + 2.000000000000000i]</lang>
'apple' [1x3 double] 'cherry' [1.000000000000000 + 2.000000000000000i]</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
Metafont has no an enumeration type. However we can define an useful macro to simulate an enumeration. E.g.
Metafont has no an enumeration type. However we can define an useful macro to simulate an enumeration. E.g.
<lang metafont>vardef enum(expr first)(text t) =
<syntaxhighlight lang="metafont">vardef enum(expr first)(text t) =
save ?; ? := first;
save ?; ? := first;
forsuffixes e := t: e := ?; ?:=?+1; endfor
forsuffixes e := t: e := ?; ?:=?+1; endfor
enddef;</lang>
enddef;</syntaxhighlight>


Usage example:
Usage example:


<lang metafont>enum(1, Apple, Banana, Cherry);
<syntaxhighlight lang="metafont">enum(1, Apple, Banana, Cherry);
enum(5, Orange, Pineapple, Qfruit);
enum(5, Orange, Pineapple, Qfruit);
show Apple, Banana, Cherry, Orange, Pineapple, Qfruit;
show Apple, Banana, Cherry, Orange, Pineapple, Qfruit;


end</lang>
end</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>TYPE Fruit = {Apple, Banana, Cherry};</lang>
<syntaxhighlight lang="modula3">TYPE Fruit = {Apple, Banana, Cherry};</syntaxhighlight>
The values are accessed by qualifying their names.
The values are accessed by qualifying their names.
<lang modula3>fruit := Fruit.Apple;</lang>
<syntaxhighlight lang="modula3">fruit := Fruit.Apple;</syntaxhighlight>
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>.
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>.
<lang modula3>ORD(Fruit.Apple); (* Returns 0 *)
<syntaxhighlight lang="modula3">ORD(Fruit.Apple); (* Returns 0 *)
VAL(0, Fruit); (* Returns Fruit.Apple *)</lang>
VAL(0, Fruit); (* Returns Fruit.Apple *)</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>enum Fruit {
<syntaxhighlight lang="nemerle">enum Fruit {
|apple
|apple
|banana
|banana
Line 1,303: Line 1,303:
|summer = 3
|summer = 3
|autumn = 4
|autumn = 4
}</lang>
}</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim># Simple declaration.
<syntaxhighlight lang="nim"># Simple declaration.
type Fruits1 = enum aApple, aBanana, aCherry
type Fruits1 = enum aApple, aBanana, aCherry


Line 1,328: Line 1,328:
Apple = (1, "apple")
Apple = (1, "apple")
Banana = 3 # implicit name is "Banana".
Banana = 3 # implicit name is "Banana".
Cherry = "cherry" # implicit value is 4.</lang>
Cherry = "cherry" # implicit value is 4.</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
enum Color := -3 {
enum Color := -3 {
Red,
Red,
Line 1,343: Line 1,343:
Terrier
Terrier
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
With iOS 6+ SDK / Mac OS X 10.8+ SDK:
With iOS 6+ SDK / Mac OS X 10.8+ SDK:
<lang objc>typedef NS_ENUM(NSInteger, fruits) { apple, banana, cherry };
<syntaxhighlight lang="objc">typedef NS_ENUM(NSInteger, fruits) { apple, banana, cherry };


typedef NS_ENUM(NSInteger, fruits) { apple = 0, banana = 1, cherry = 2 };</lang>
typedef NS_ENUM(NSInteger, fruits) { apple = 0, banana = 1, cherry = 2 };</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>type fruit =
<syntaxhighlight lang="ocaml">type fruit =
| Apple
| Apple
| Banana
| Banana
| Cherry</lang>
| Cherry</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,365: Line 1,365:
Symbols begin with $. If the symbol does not exists yet, it is created.
Symbols begin with $. If the symbol does not exists yet, it is created.


<lang Oforth>[ $apple, $banana, $cherry ] const: Fruits</lang>
<syntaxhighlight lang="oforth">[ $apple, $banana, $cherry ] const: Fruits</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Ol enumerations is an builtin "ff"s as a simple fast dictionaries with number, constant or symbol keys and any typed values.
Ol enumerations is an builtin "ff"s as a simple fast dictionaries with number, constant or symbol keys and any typed values.


<lang scheme>
<syntaxhighlight lang="scheme">
(define fruits '{
(define fruits '{
apple 0
apple 0
Line 1,398: Line 1,398:
(print (make-enumeration 'apple 'banana 'cherry))
(print (make-enumeration 'apple 'banana 'cherry))
; ==> '#ff((apple . 0) (banana . 1) (cherry . 2))
; ==> '#ff((apple . 0) (banana . 1) (cherry . 2))
</syntaxhighlight>
</lang>


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==


<lang>
<syntaxhighlight lang="text">
enum fruits
enum fruits
apple
apple
Line 1,419: Line 1,419:
' banana 15
' banana 15
' mango 16
' mango 16
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{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:
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:
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {IsFruit A}
fun {IsFruit A}
{Member A [apple banana cherry]}
{Member A [apple banana cherry]}
end
end
in
in
{Show {IsFruit banana}}</lang>
{Show {IsFruit banana}}</syntaxhighlight>


If you need constants with increasing values, you could just enumerate them manually:
If you need constants with increasing values, you could just enumerate them manually:
<lang oz>declare
<syntaxhighlight lang="oz">declare
Apple = 1
Apple = 1
Banana = 2
Banana = 2
Cherry = 3</lang>
Cherry = 3</syntaxhighlight>


Or you could write a procedure that does the job automatically:
Or you could write a procedure that does the job automatically:
<lang oz>declare
<syntaxhighlight lang="oz">declare
proc {Enumeration Xs}
proc {Enumeration Xs}
Xs = {List.number 1 {Length Xs} 1}
Xs = {List.number 1 {Length Xs} 1}
Line 1,444: Line 1,444:
[Apple Banana Cherry] = {Enumeration}
[Apple Banana Cherry] = {Enumeration}
in
in
{Show Cherry}</lang>
{Show Cherry}</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,450: Line 1,450:
An explicit index may not be specified, but [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]] allow this.
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).
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).
<lang pascal>type
<syntaxhighlight lang="pascal">type
phase = (red, green, blue);</lang>
phase = (red, green, blue);</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl># Using an array
<syntaxhighlight lang="perl"># Using an array
my @fruits = qw(apple banana cherry);
my @fruits = qw(apple banana cherry);


# Using a hash
# Using a hash
my %fruits = ( apple => 0, banana => 1, cherry => 2 );</lang>
my %fruits = ( apple => 0, banana => 1, cherry => 2 );</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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> <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;">=
<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;">=
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>// Using an array/hash
<syntaxhighlight lang="php">// Using an array/hash
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );
Line 1,485: Line 1,485:
define("FRUIT_APPLE", 0);
define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);</lang>
define("FRUIT_CHERRY", 2);</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Line 1,491: Line 1,491:
Picat doesn't have enumerations but they can be simulated by facts.
Picat doesn't have enumerations but they can be simulated by facts.


<lang Picat>fruit(apple,1).
<syntaxhighlight lang="picat">fruit(apple,1).
fruit(banana,2).
fruit(banana,2).
fruit(cherry,4).
fruit(cherry,4).
Line 1,497: Line 1,497:
print_fruit_name(N) :-
print_fruit_name(N) :-
fruit(Name,N),
fruit(Name,N),
printf("It is %w\nn", Name).</lang>
printf("It is %w\nn", Name).</syntaxhighlight>




Line 1,503: Line 1,503:
Enumerations are not very useful in a symbolic language like PicoLisp. If
Enumerations are not very useful in a symbolic language like PicoLisp. If
desired, an 'enum' function could be defined:
desired, an 'enum' function could be defined:
<lang PicoLisp>(de enum "Args"
<syntaxhighlight lang="picolisp">(de enum "Args"
(mapc def "Args" (range 1 (length "Args"))) )</lang>
(mapc def "Args" (range 1 (length "Args"))) )</syntaxhighlight>
And used in this way:
And used in this way:
<lang PicoLisp>: (enum A B C D E F)
<syntaxhighlight lang="picolisp">: (enum A B C D E F)
-> F</lang>
-> F</syntaxhighlight>
<pre>: A
<pre>: A
-> 1
-> 1
Line 1,516: Line 1,516:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
define ordinal animal (frog, gnu, elephant, snake);
define ordinal animal (frog, gnu, elephant, snake);


define ordinal color (red value (1), green value (3), blue value (5));
define ordinal color (red value (1), green value (3), blue value (5));
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Without explicit values.
Without explicit values.
{{works with|PowerShell|5}}
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Enum fruits {
Enum fruits {
Apple
Apple
Line 1,534: Line 1,534:
[fruits]::Apple + 1
[fruits]::Apple + 1
[fruits]::Banana + 1
[fruits]::Banana + 1
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 1,543: Line 1,543:
With explicit values.
With explicit values.
{{works with|PowerShell|5}}
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Enum fruits {
Enum fruits {
Apple = 10
Apple = 10
Line 1,552: Line 1,552:
[fruits]::Apple + 1
[fruits]::Apple + 1
[fruits]::Banana + 1
[fruits]::Banana + 1
</syntaxhighlight>
</lang>
<pre>
<pre>
Apple
Apple
Line 1,562: Line 1,562:
Prolog doesn't have enums, but they can be simulated using a set of facts.
Prolog doesn't have enums, but they can be simulated using a set of facts.


<lang prolog>fruit(apple,1).
<syntaxhighlight lang="prolog">fruit(apple,1).
fruit(banana,2).
fruit(banana,2).
fruit(cherry,4).
fruit(cherry,4).
Line 1,568: Line 1,568:
write_fruit_name(N) :-
write_fruit_name(N) :-
fruit(Name,N),
fruit(Name,N),
format('It is a ~p~n', Name).</lang>
format('It is a ~p~n', Name).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Basic Enumeration is defined as
Basic Enumeration is defined as
<lang PureBasic>Enumeration
<syntaxhighlight lang="purebasic">Enumeration
#Apple
#Apple
#Banana
#Banana
#Cherry
#Cherry
EndEnumeration</lang>
EndEnumeration</syntaxhighlight>
This can also be adjusted to the form
This can also be adjusted to the form
<lang PureBasic>Enumeration 10200 Step 12
<syntaxhighlight lang="purebasic">Enumeration 10200 Step 12
#Constant1 ; 10200
#Constant1 ; 10200
#Constant2 ; 10212
#Constant2 ; 10212
Line 1,584: Line 1,584:
#Constant4 = 10117 ; 10117
#Constant4 = 10117 ; 10117
#Constant5 ; 10229
#Constant5 ; 10229
EndEnumeration</lang>
EndEnumeration</syntaxhighlight>
The system constant "#PB_Compiler_EnumerationValue" holds last defined value and can be used to chain to a previously started series.
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;
E.g. in combination with the code above;
<lang PureBasic>Enumeration #PB_Compiler_EnumerationValue
<syntaxhighlight lang="purebasic">Enumeration #PB_Compiler_EnumerationValue
#Constant_A ; 10241
#Constant_A ; 10241
#Constant_B ; 10242
#Constant_B ; 10242
EndEnumeration</lang>
EndEnumeration</syntaxhighlight>


Enumeration groups can also be named to allow continuation where a previous named group left off.
Enumeration groups can also be named to allow continuation where a previous named group left off.
<lang PureBasic>;This starts the enumeration of a named group 'NamedGroup'.
<syntaxhighlight lang="purebasic">;This starts the enumeration of a named group 'NamedGroup'.
Enumeration NamedGroup 5
Enumeration NamedGroup 5
#Green ; 5
#Green ; 5
Line 1,612: Line 1,612:
#Yellow ; 7
#Yellow ; 7
#Red ; 8
#Red ; 8
EndEnumeration</lang>
EndEnumeration</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 1,618: Line 1,618:
Note: [http://www.python.org/dev/peps/pep-0435/ enumerations have come to Python version 3.4].
Note: [http://www.python.org/dev/peps/pep-0435/ enumerations have come to Python version 3.4].


<lang python>>>> from enum import Enum
<syntaxhighlight lang="python">>>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
>>> Contact.__members__
Line 1,632: Line 1,632:
>>> Contact2.__members__
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>> </lang>
>>> </syntaxhighlight>


===Python: Pre version 3.4===
===Python: Pre version 3.4===
{{works with|Python|2.5}}
{{works with|Python|2.5}}
There is no special syntax, typically global variables are used with range:
There is no special syntax, typically global variables are used with range:
<lang python>FIRST_NAME, LAST_NAME, PHONE = range(3)</lang>
<syntaxhighlight lang="python">FIRST_NAME, LAST_NAME, PHONE = range(3)</syntaxhighlight>
Alternately, the above variables can be enumerated from a list with no predetermined length.
Alternately, the above variables can be enumerated from a list with no predetermined length.
<lang python>vars().update((key,val) for val,key in enumerate(("FIRST_NAME","LAST_NAME","PHONE")))</lang>
<syntaxhighlight lang="python">vars().update((key,val) for val,key in enumerate(("FIRST_NAME","LAST_NAME","PHONE")))</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
R does not have an enumeration type, though factors provide a similar functionality.
R does not have an enumeration type, though factors provide a similar functionality.
<lang R> factor(c("apple", "banana", "cherry"))
<syntaxhighlight lang="r"> factor(c("apple", "banana", "cherry"))
# [1] apple banana cherry
# [1] apple banana cherry
# Levels: apple banana cherry</lang>
# Levels: apple banana cherry</syntaxhighlight>
[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.
[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}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,692: Line 1,692:
((ctype-c->scheme _fruits) 4) ; -> '(CHERRY)
((ctype-c->scheme _fruits) 4) ; -> '(CHERRY)
((ctype-c->scheme _fruits) 5) ; -> '(APPLE CHERRY)
((ctype-c->scheme _fruits) 5) ; -> '(APPLE CHERRY)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,698: Line 1,698:
{{works with|Rakudo|2016.01}}
{{works with|Rakudo|2016.01}}


<lang perl6>enum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.
<syntaxhighlight lang="raku" line>enum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.


enum ClassicalElement (
enum ClassicalElement (
Line 1,705: Line 1,705:
'Fire', # gets the value 7
'Fire', # gets the value 7
Water => 10,
Water => 10,
);</lang>
);</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven>{ 'apple' 0 'banana' 1 'cherry' 2 } as fruits</lang>
<syntaxhighlight lang="raven">{ 'apple' 0 'banana' 1 'cherry' 2 } as fruits</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
Retro has a library named '''enum'''' for creation of enumerated values.
Retro has a library named '''enum'''' for creation of enumerated values.


<lang Retro>'/examples/enum.retro include
<syntaxhighlight lang="retro">'/examples/enum.retro include


{ 'a=10 'b 'c 'd=998 'e 'f } a:enum
{ 'a=10 'b 'c 'd=998 'e 'f } a:enum
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,723: Line 1,723:
<br>This REXX entry was kinda modeled after the '''BASIC''', '''Forth''', and
<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)].
'''VBA''' [which does its own enumeration, as does REXX below (as an inventory count)].
<lang rexx>/*REXX program illustrates a method of enumeration of constants via stemmed arrays. */
<syntaxhighlight lang="rexx">/*REXX program illustrates a method of enumeration of constants via stemmed arrays. */
fruit.=0 /*the default for all possible "FRUITS." (zero). */
fruit.=0 /*the default for all possible "FRUITS." (zero). */
fruit.apple = 65
fruit.apple = 65
Line 1,777: Line 1,777:
end /*j*/
end /*j*/
end /*p*/
end /*p*/
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 1,798: Line 1,798:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
apple = 0
apple = 0
banana = 1
banana = 1
Line 1,805: Line 1,805:
see "banana : " + banana + nl
see "banana : " + banana + nl
see "cherry : " + cherry + nl
see "cherry : " + cherry + nl
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
There are plenty of ways to represent '''enum''' in Ruby. Here it is just one example:
There are plenty of ways to represent '''enum''' in Ruby. Here it is just one example:
<lang ruby>module Fruits
<syntaxhighlight lang="ruby">module Fruits
APPLE = 0
APPLE = 0
BANANA = 1
BANANA = 1
Line 1,819: Line 1,819:
FRUITS = [:apple, :banana, :cherry]
FRUITS = [:apple, :banana, :cherry]
val = :banana
val = :banana
FRUITS.include?(val) #=> true</lang>
FRUITS.include?(val) #=> true</syntaxhighlight>
To give a number in turn, there is the following method.
To give a number in turn, there is the following method.
<lang ruby>module Card
<syntaxhighlight lang="ruby">module Card
# constants
# constants
SUITS = %i(Clubs Hearts Spades Diamonds)
SUITS = %i(Clubs Hearts Spades Diamonds)
Line 1,832: Line 1,832:
# PIP_VALUE = Hash[ PIPS.each.with_index(2).to_a ] # before it
# 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}
#=> {:"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</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>enum Fruits {
<syntaxhighlight lang="rust">enum Fruits {
Apple,
Apple,
Banana,
Banana,
Line 1,849: Line 1,849:
// Access to numerical value by conversion
// Access to numerical value by conversion
println!("{}", FruitsWithNumbers::Pear as u8);
println!("{}", FruitsWithNumbers::Pear as u8);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
'''1. Using Algebraic Data Types:'''
'''1. Using Algebraic Data Types:'''
<lang actionscript>sealed abstract class Fruit
<syntaxhighlight lang="actionscript">sealed abstract class Fruit
case object Apple extends Fruit
case object Apple extends Fruit
case object Banana extends Fruit
case object Banana extends Fruit
case object Cherry extends Fruit
case object Cherry extends Fruit
</syntaxhighlight>
</lang>
'''2. Using scala.Enumeration:'''
'''2. Using scala.Enumeration:'''
<lang actionscript>object Fruit extends Enumeration {
<syntaxhighlight lang="actionscript">object Fruit extends Enumeration {
val Apple, Banana, Cherry = Value
val Apple, Banana, Cherry = Value
}
}
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define apple 0)
<syntaxhighlight lang="scheme">(define apple 0)
(define banana 1)
(define banana 1)
(define cherry 2)
(define cherry 2)
Line 1,872: Line 1,872:
(or (equal? 'apple atom)
(or (equal? 'apple atom)
(equal? 'banana atom)
(equal? 'banana atom)
(equal? 'cherry atom)))</lang>
(equal? 'cherry atom)))</syntaxhighlight>
(This section needs attention from someone familiar with Scheme idioms.)
(This section needs attention from someone familiar with Scheme idioms.)
===Using syntax extension===
===Using syntax extension===
{{works with|Chez Scheme}}
{{works with|Chez Scheme}}
'''The Implementation'''
'''The Implementation'''
<lang scheme>; Syntax that implements a C-like enum; items without assignment take next value.
<syntaxhighlight lang="scheme">; Syntax that implements a C-like enum; items without assignment take next value.
; Form: (enum <name> <item>...)
; Form: (enum <name> <item>...)
; Where <name> is a symbol that will be the name of the enum; <item> are one or
; Where <name> is a symbol that will be the name of the enum; <item> are one or
Line 1,916: Line 1,916:
(define sym nxint)
(define sym nxint)
(set! name (cons (cons 'sym nxint) name))
(set! name (cons (cons 'sym nxint) name))
(enum-help name (1+ nxint) rest ...)))))))</lang>
(enum-help name (1+ nxint) rest ...)))))))</syntaxhighlight>
'''Example Use'''
'''Example Use'''
<lang scheme>(define-syntax test
<syntaxhighlight lang="scheme">(define-syntax test
(syntax-rules ()
(syntax-rules ()
((_ e)
((_ e)
Line 1,945: Line 1,945:
(test y)
(test y)
(test z)
(test z)
(test bar)</lang>
(test bar)</syntaxhighlight>
{{out}}
{{out}}
<pre>The 'foo' enum:
<pre>The 'foo' enum:
Line 1,966: Line 1,966:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>const type: fruits is new enum
<syntaxhighlight lang="seed7">const type: fruits is new enum
apple, banana, cherry
apple, banana, cherry
end enum;</lang>
end enum;</syntaxhighlight>


=={{header|Shen}}==
=={{header|Shen}}==
<lang shen>(tc +)
<syntaxhighlight lang="shen">(tc +)


(datatype fruit
(datatype fruit
Line 1,977: Line 1,977:
if (element? Fruit [apple banana cherry])
if (element? Fruit [apple banana cherry])
_____________
_____________
Fruit : fruit;)</lang>
Fruit : fruit;)</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Implicit:
Implicit:
<lang ruby>enum {Apple, Banana, Cherry}; # numbered 0 through 2</lang>
<syntaxhighlight lang="ruby">enum {Apple, Banana, Cherry}; # numbered 0 through 2</syntaxhighlight>
Explicit:
Explicit:
<lang ruby>enum {
<syntaxhighlight lang="ruby">enum {
Apple=3,
Apple=3,
Banana, # gets the value 4
Banana, # gets the value 4
Cherry="a",
Cherry="a",
Orange, # gets the value "b"
Orange, # gets the value "b"
};</lang>
};</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
As just unique objects:
As just unique objects:
<lang slate>define: #Fruit &parents: {Cloneable}.
<syntaxhighlight lang="slate">define: #Fruit &parents: {Cloneable}.
Fruit traits define: #Apple -> Fruit clone.
Fruit traits define: #Apple -> Fruit clone.
Fruit traits define: #Banana -> Fruit clone.
Fruit traits define: #Banana -> Fruit clone.
Fruit traits define: #Cherry -> Fruit clone.</lang>
Fruit traits define: #Cherry -> Fruit clone.</syntaxhighlight>


As labels for primitive values:
As labels for primitive values:
<lang slate>define: #Apple -> 1.
<syntaxhighlight lang="slate">define: #Apple -> 1.
define: #Banana -> 2.
define: #Banana -> 2.
define: #Cherry -> 3.</lang>
define: #Cherry -> 3.</syntaxhighlight>


As a namespace:
As a namespace:
<lang slate>ensureNamespace: #fruit &slots: {#Apple -> 1. #Banana -> 2. #Cherry -> 3}.</lang>
<syntaxhighlight lang="slate">ensureNamespace: #fruit &slots: {#Apple -> 1. #Banana -> 2. #Cherry -> 3}.</syntaxhighlight>


Using a dictionary:
Using a dictionary:
<lang slate>define: #fruit &builder: [{#Apple -> 1. #Banana -> 2. #Cherry -> 3} as: Dictionary].</lang>
<syntaxhighlight lang="slate">define: #fruit &builder: [{#Apple -> 1. #Banana -> 2. #Cherry -> 3} as: Dictionary].</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>datatype fruit =
<syntaxhighlight lang="sml">datatype fruit =
Apple
Apple
| Banana
| Banana
| Cherry</lang>
| Cherry</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>enum Fruit {
<syntaxhighlight lang="swift">enum Fruit {
case Apple
case Apple
case Banana
case Banana
Line 2,030: Line 2,030:
case Summer = 3
case Summer = 3
case Autumn = 4
case Autumn = 4
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{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:]]
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:]]


<lang tcl>proc enumerate {name values} {
<syntaxhighlight lang="tcl">proc enumerate {name values} {
interp alias {} $name: {} lsearch $values
interp alias {} $name: {} lsearch $values
interp alias {} $name@ {} lindex $values
interp alias {} $name@ {} lindex $values
}</lang>
}</syntaxhighlight>


it would be used like this:
it would be used like this:


<lang tcl>enumerate fruit {apple blueberry cherry date elderberry}
<syntaxhighlight lang="tcl">enumerate fruit {apple blueberry cherry date elderberry}
fruit: date
fruit: date
# ==> prints "3"
# ==> prints "3"
fruit@ 2
fruit@ 2
# ==> prints "cherry"</lang>
# ==> prints "cherry"</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
Line 2,054: Line 2,054:
This library function takes a starting value and a list of names as shown in the example below.
This library function takes a starting value and a list of names as shown in the example below.


<lang toka>needs enum
<syntaxhighlight lang="toka">needs enum
0 enum| apple banana carrot |
0 enum| apple banana carrot |
10 enum| foo bar baz |</lang>
10 enum| foo bar baz |</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
Like Visual Basic .NET, actually:
Like Visual Basic .NET, actually:
<syntaxhighlight lang="vb">
<lang vb>
'this enumerates from 0
'this enumerates from 0
Enum fruits
Enum fruits
Line 2,084: Line 2,084:
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,094: Line 2,094:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>' Is this valid?!
<syntaxhighlight lang="vbnet">' Is this valid?!
Enum fruits
Enum fruits
apple
apple
Line 2,106: Line 2,106:
banana = 1
banana = 1
cherry = 2
cherry = 2
End Enum</lang>
End Enum</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 2,112: Line 2,112:


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.
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.
<lang ecmascript>var APPLE = 1
<syntaxhighlight lang="ecmascript">var APPLE = 1
var ORANGE = 2
var ORANGE = 2
var PEAR = 3
var PEAR = 3
Line 2,120: Line 2,120:
var GRAPE = BANANA + 1
var GRAPE = BANANA + 1


System.print([APPLE, ORANGE, PEAR, CHERRY, BANANA, GRAPE])</lang>
System.print([APPLE, ORANGE, PEAR, CHERRY, BANANA, GRAPE])</syntaxhighlight>


{{out}}
{{out}}
Line 2,130: Line 2,130:
<br>
<br>
{{libheader|Wren-dynamic}}
{{libheader|Wren-dynamic}}
<lang ecmascript>import "/dynamic" for Enum
<syntaxhighlight lang="ecmascript">import "/dynamic" for Enum


var Fruit = Enum.create("Fruit", ["apple", "orange", "pear", "cherry", "banana", "grape"], 1)
var Fruit = Enum.create("Fruit", ["apple", "orange", "pear", "cherry", "banana", "grape"], 1)
System.print(Fruit.orange)
System.print(Fruit.orange)
System.print(Fruit.members[Fruit.cherry - 1])</lang>
System.print(Fruit.members[Fruit.cherry - 1])</syntaxhighlight>


{{out}}
{{out}}
Line 2,143: Line 2,143:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>def \Fruit\ Apple, Banana, Cherry; \Apple=0, Banana=1, Cherry=2
<syntaxhighlight lang="xpl0">def \Fruit\ Apple, Banana, Cherry; \Apple=0, Banana=1, Cherry=2
def Apple=1, Banana=2, Cherry=4;
def Apple=1, Banana=2, Cherry=4;
</syntaxhighlight>
</lang>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
Line 2,153: Line 2,153:


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.
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.
<lang z80>Sunday equ 0
<syntaxhighlight lang="z80">Sunday equ 0
Monday equ 1
Monday equ 1
Tuesday equ 2
Tuesday equ 2
Line 2,159: Line 2,159:
Thursday equ 4
Thursday equ 4
Friday equ 5
Friday equ 5
Saturday equ 6</lang>
Saturday equ 6</syntaxhighlight>


===Without Explicit Values===
===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.
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.


<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.
<syntaxhighlight 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.
;this simplifies the lookup process significantly.
Days_Of_The_Week:
Days_Of_The_Week:
Line 2,197: Line 2,197:
call PrintString ;prints a null-terminated string to the screen.
call PrintString ;prints a null-terminated string to the screen.
ret ;return to basic
ret ;return to basic
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,206: Line 2,206:
=={{header|zkl}}==
=={{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).
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).
<lang zkl>const RGB_COLOR{ // put color names in a name space
<syntaxhighlight lang="zkl">const RGB_COLOR{ // put color names in a name space
const RED =0xf00;
const RED =0xf00;
const BLUE=0x0f0, GREEN = 0x00f;
const BLUE=0x0f0, GREEN = 0x00f;
const CYAN=BLUE + GREEN; // → 0x0ff
const CYAN=BLUE + GREEN; // → 0x0ff
}
}
println(RGB_COLOR.BLUE);</lang>
println(RGB_COLOR.BLUE);</syntaxhighlight>
{{out}}
{{out}}
<pre>240</pre>
<pre>240</pre>


<lang zkl>const X0=N; // --> 0
<syntaxhighlight lang="zkl">const X0=N; // --> 0
const A=N,B=N,C=N; // --> 1,2,3
const A=N,B=N,C=N; // --> 1,2,3
const{ _n=-1; } // reset Enum, this should be a const space function
const{ _n=-1; } // reset Enum, this should be a const space function
const X=N; // -->0</lang>
const X=N; // -->0</syntaxhighlight>
Since const space runs at a different time [vs compile space], you need to really careful if you mix the two [spaces]:
Since const space runs at a different time [vs compile space], you need to really careful if you mix the two [spaces]:
<lang zkl>#continuing ...
<syntaxhighlight lang="zkl">#continuing ...
z:=N; // -->2 NOT 1 as it is set AFTER Y (compile time vs parse time)
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</lang>
const Y=N; // -->1! because it is set before z</syntaxhighlight>


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang="zonnon">
module Enumerations;
module Enumerations;
type
type
Line 2,241: Line 2,241:
end
end
end Enumerations.
end Enumerations.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>