Enumerations
From Rosetta Code
You are encouraged to solve this task according to the task description, using any language you may know.
Create an enumeration of types with and without values.
[edit] 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.
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
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.
[edit] ALGOL 68
Translation of: C
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
Note: In this first example ALGOL 68's MODE does not create FRUITS as a distinct enumerated type. In particular FRUITS remain compatible with INT and so FRUITS inherit/share all INT's operators and procedures.
BEGIN # example 1 #
MODE FRUIT = INT;
FRUIT apple = 1, banana = 2, cherry = 4;
FRUIT x := cherry;
CASE x IN
print(("It is an apple #",x, new line)),
print(("It is a banana #",x, new line)),
SKIP, # 3 not defined #
print(("It is a cherry #",x, new line))
OUT
SKIP # other values #
ESAC
END;
Output:
It is a cherry # +4
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
In this second example ALGOL 68's tagged unions are used to generate the (private) values of the members of the enumerated type. However this new type comes with no operators, not even the "=" equality operator. Hence at least REPR (or ABS for INT type) must be defined if anything other then a case conditional clause is required.
BEGIN # example 2 #
MODE ENUM = [0]CHAR; # something with minimal size #
MODE APPLE = STRUCT(ENUM apple), BANANA = STRUCT(ENUM banana), CHERRY = STRUCT(ENUM cherry);
MODE FRUIT = UNION(APPLE, BANANA, CHERRY);
OP REPR = (FRUIT f)STRING:
CASE f IN
(APPLE):"Apple",
(BANANA):"Banana",
(CHERRY):"Cherry"
OUT
"?" # uninitalised #
ESAC;
FRUIT x := LOC CHERRY;
CASE x IN
(APPLE):print(("It is an ",REPR x, new line)),
(BANANA):print(("It is a ",REPR x, new line)),
(CHERRY):print(("It is a ",REPR x, new line))
OUT
SKIP # uninitialised FRUIT #
ESAC
END
Output:
It is a Cherry
Warning: This second example is probably not how the conformity case clause construct was intended to be used.
See also: Standard Deviation for another example.
[edit] AmigaE
ENUM APPLE, BANANA, CHERRY
PROC main()
DEF x
ForAll({x}, [APPLE, BANANA, CHERRY],
`WriteF('\d\n', x))
ENDPROC
writes 0, 1, 2 to the console.
[edit] AutoHotkey
AutoHotkey doesn't really enforce types.
However you can simulate types like enumeration with associative arrays:
fruit_%apple% = 0
fruit_%banana% = 1
fruit_%cherry% = 2
[edit] AWK
In awk we can use an array, for mapping both ways, or initialize variables:
enum["apple"]=1; enum["banana"]=2; enum["cherry"]=3
enum[1]="apple"; enum[2]="banana"; enum[3]="cherry"
i=0; apple=++i; banana=++i; cherry=++i;
[edit] BASIC
Works with: QuickBasic version 4.5
Works with: PB version 7.1
REM Impossible. Can only be faked with arrays of strings.
OPTION BASE 1
DIM SHARED fruitsName$(1 TO 3)
DIM SHARED fruitsVal%( 1 TO 3)
fruitsName$[1] = "apple"
fruitsName$[2] = "banana"
fruitsName$[3] = "cherry"
fruitsVal%[1] = 1
fruitsVal%[2] = 2
fruitsVal%[3] = 3
REM OR GLOBAL CONSTANTS
DIM SHARED apple%, banana%, cherry%
apple% = 1
banana% = 2
cherry% = 3
[edit] C
enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
[edit] C++
enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
[edit] C#
enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits : int { apple = 0, banana = 1, cherry = 2 }
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
Placing FlagsAttribute before an enum allows you to perform bitwise operations on the value. Note: All enums have a value of 0 defined, even if not specified in the set values.
[edit] 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:
; a set of keywords
(def fruits #{:apple :banana :cherry})
; a predicate to test "fruit" membership
(defn fruit? [x] (contains? fruits x))
; if you need a value associated with each fruit
(def fruit-value (zipmap fruits (iterate inc 1)))
(println (fruit? :apple))
(println (fruit-value :banana))
[edit] Common Lisp
Values:
;; symbol to number
(defconstant +apple+ 0)
(defconstant +banana+ 1)
(defconstant +cherry+ 2)
;; number to symbol
(defun index-fruit (i)
(aref #(+apple+ +banana+ +cherry+) i))
Of course, the two definitions above can be produced by a single macro, if desired.
Defining a type for documentation or checking purposes:
(deftype fruit ()
'(member +apple+ +banana+ +cherry+))
[edit] D
Works with: DMD
Works with: GDC
enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits : int { apple = 0, banana = 1, cherry = 2 }
[edit] E
Simple group of object definitions (value methods could be left out if appropriate):
def apple { to value() { return 0 } }
def banana { to value() { return 1 } }
def cherry { to value() { return 2 } }
With a guard for type checks:
interface Fruit guards FruitStamp {}
def apple implements FruitStamp {}
def banana implements FruitStamp {}
def cherry implements FruitStamp {}
def eat(fruit :Fruit) { ... }
With and without values, using a hypothetical enumeration library:
def [Fruit, [=> apple, => banana, => cherry]] := makeEnumeration()
def [Fruit, [=> apple, => banana, => cherry]] :=
makeEnumeration(0, ["apple", "banana", "cherry"])
[edit] Forth
Forth has no types, and therefore no enumeration type. To define sequential constants, a programmer might write code like this:
0 CONSTANT apple
1 CONSTANT banana
2 CONSTANT cherry
...
However, a common idiom in forth is to define a defining word, such as:
: ENUM ( n -<name>- n+1 ) DUP CONSTANT 1+ ;
This word defines a new constant of the value specified and returns the next value in sequence. It would be used like this:
0 ENUM APPLE ENUM BANANA ENUM CHERRY DROP
Or you can use CONSTANT to capture the "end" value instead of dropping it:
0 ENUM FIRST ENUM SECOND ... CONSTANT LAST
A variation of this idea is the "stepped enumeration" that increases the value by more than 1, such as:
: SIZED-ENUM ( n s -<name>- n+s ) OVER CONSTANT + ;
: CELL-ENUM ( n -<name>- n+cell ) CELL SIZED-ENUM ;
A programmer could combine these enum definers in any way desired:
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
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:
: CONSTANTS ( n -- ) 0 DO I CONSTANT LOOP ;
\ resistor digit colors
10 CONSTANTS black brown red orange yellow green blue violet gray white
[edit] Fortran
Works with: Fortran version 2003
enum, bind(c)
enumerator :: one=1, two, three, four, five
enumerator :: six, seven, nine=9
end enum
The syntax
enum, bind(c) :: nametype
enumerator :: one=1, two, three
end enum nametype
does not work with gfortran; it is used in some Cray docs about Fortran, but the syntax shown at 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 Fortran 2003 Standard section to understand why differences may exist...)
[edit] F#
type fruit =
| Apple
| Banana
| Cherry
let basket = [ Apple ; Banana ; Cherry ]
Seq.iter (fun a -> printfn "%A" a) basket
[edit] Go
const (
apple = iota
banana
cherry
)
[edit] Haskell
data Fruit = Apple | Banana | Cherry deriving Enum
[edit] J
J's typing system is fixed, and so extensions occur at the application level. For example, one could create an object
enum =: cocreate''
( 'apple banana cherry' ,L:0 '__enum' ) =: i. 3
cherry__enum
2
But this is more akin to a "methodless class or object" than an enum in other languages.
[edit] Java
Works with: Java version 1.5+
enum fruits { apple, banana, cherry }
Or:
enum fruits{
apple(0), banana(1), cherry(2)
private final int value;
fruits(int value) { this.value = value; }
public int value() { return value; }
}
[edit] JavaScript
var fruits = { apple : 0, banana : 1, cherry : 2 };
[edit] JSON
{"fruits" : { "apple" : null, "banana" : null, "cherry" : null }
{"fruits" : { "apple" : 0, "banana" : 1, "cherry" : 2 }
[edit] JScript.NET
enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
[edit] 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
Output:
c=3
[edit] MATLAB
Enumeration is done by creating a cell array (a.k.a set) of objects, where the numeral of the object is its index in the 1-based cell array. The cell array structure can contain any type of data structure including other cell arrays, and all members don't have to be the same data type.
Example:
stuff = {'apple', [1 2 3], 'cherry',1+2i}
stuff =
'apple' [1x3 double] 'cherry' [1.000000000000000 + 2.000000000000000i]
[edit] Metafont
Metafont has no an enumeration type. However we can define an useful macro to simulate an enumeration. E.g.
vardef enum(expr first)(text t) =
save ?; ? := first;
forsuffixes e := t: e := ?; ?:=?+1; endfor
enddef;
Usage example:
enum(1, Apple, Banana, Cherry);
enum(5, Orange, Pineapple, Qfruit);
show Apple, Banana, Cherry, Orange, Pineapple, Qfruit;
end
[edit] Modula-3
TYPE Fruit = {Apple, Banana, Cherry};
The values are accessed by qualifying their names.
fruit := Fruit.Apple;
You can get an element's position in the enumeration by using ORD and get the element given the position by using VAL.
ORD(Fruit.Apple); (* Returns 0 *)
VAL(0, Fruit); (* Returns Fruit.Apple *)
[edit] Objeck
enum Color := -3 {
Red,
White,
Blue
}
enum Dog {
Pug,
Boxer,
Terrier
}
[edit] OCaml
type fruit =
Apple
| Banana
| Cherry
[edit] 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:
declare
fun {IsFruit A}
{Member A [apple banana cherry]}
end
in
{Show {IsFruit banana}}
If you need constants with increasing values, you could just enumerate them manually:
declare
Apple = 1
Banana = 2
Cherry = 3
Or you could write a procedure that does the job automatically:
declare
proc {Enumeration Xs}
Xs = {List.number 1 {Length Xs} 1}
end
[Apple Banana Cherry] = {Enumeration}
in
{Show Cherry}
[edit] Perl
# Using an array
my @fruits = qw(apple banana cherry);
# Using a hash
my %fruits = ( apple => 0, banana => 1, cherry => 2 );
[edit] Perl 6
Works with: Rakudo version #21 "Seattle"
enum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.
enum ClassicalElement (
Earth => 5,
'Air', # Gets the value 6.
Fire => 'hot',
Water => 'wet'
);
[edit] PHP
// Using an array/hash
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );
// If you are inside a class scope
class Fruit {
const APPLE = 0;
const BANANA = 1;
const CHERRY = 2;
}
// Then you can access them as such
$value = Fruit::APPLE;
// Or, you can do it using define()
define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);
[edit] PL/I
define ordinal animal (frog, gnu, elephant, snake);
define ordinal color (red value (1), green value (3), blue value (5));
[edit] PicoLisp
Enumerations are not very useful in a symbolic language like PicoLisp. If desired, an 'enum' function could be defined:
(de enum "Args"
(mapc def "Args" (range 1 (length "Args"))) )
And used in this way:
: (enum A B C D E F)
-> F
: A -> 1 : B -> 2 : F -> 6
[edit] PureBasic
Basic Enumeration is defined as
Enumeration
#Apple
#Banana
#Cherry
EndEnumeration
This can also be adjusted to the form
Enumeration 10200 Step 12
#Constant1 ; 10200
#Constant2 ; 10212
#Constant3 ; 10224
#Constant4 = 10117 ; 10117
#Constant5 ; 10229
EndEnumeration
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;
Enumeration #PB_Compiler_EnumerationValue
#Constant_A ; 10241
#Constant_B ; 10242
EndEnumeration
[edit] Python
Works with: Python version 2.5 There is no special syntax, typically global variables are used with range:
FIRST_NAME, LAST_NAME, PHONE = range(3)
Alternately, the above variables can be enumerated from a list with no predetermined length.
vars().update((key,val) for val,key in enumerate(("FIRST_NAME","LAST_NAME","PHONE")))
[edit] R
R does not have an enumeration type, though factors provide a similar functionality.
factor(c("apple", "banana", "cherry"))
# [1] apple banana cherry
# Levels: apple banana cherry
This thread in the R mail archive contains code for an enum-like class for traffic light colours.
[edit] Raven
{ 'apple' 0 'banana' 1 'cherry' 2 } as fruits
[edit] Ruby
There are plenty of ways to represent enum in Ruby. Here it is just one example:
module Fruits
APPLE = 0
BANANA = 1
CHERRY = 2
end
[edit] Scala
1. Using Algebraic Data Types:
sealed abstract class Fruit
case object Apple extends Fruit
case object Banana extends Fruit
case object Cherry extends Fruit
2. Using scala.Enumeration:
object Fruit extends Enumeration {
val Apple, Banana, Cherry = Value
}
[edit] Scheme
(define apple 0)
(define banana 1)
(define cherry 2)
(define (fruit? atom)
(or (equal? 'apple atom)
(equal? 'banana atom)
(equal? 'cherry atom)))
(This section needs attention from someone familiar with Scheme idioms.)
[edit] Seed7
const type: fruits is new enum
apple, banana, cherry
end enum;
[edit] Slate
As just unique objects:
define: #Fruit &parents: {Cloneable}.
Fruit traits define: #Apple -> Fruit clone.
Fruit traits define: #Banana -> Fruit clone.
Fruit traits define: #Cherry -> Fruit clone.
As labels for primitive values:
define: #Apple -> 1.
define: #Banana -> 2.
define: #Cherry -> 3.
As a namespace:
ensureNamespace: #fruit &slots: {#Apple -> 1. #Banana -> 2. #Cherry -> 3}.
Using a dictionary:
define: #fruit &builder: [{#Apple -> 1. #Banana -> 2. #Cherry -> 3} as: Dictionary].
[edit] Standard ML
datatype fruit =
Apple
| Banana
| Cherry
[edit] 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 [Tcl wiki:]
proc enumerate {name values} {
interp alias {} $name: {} lsearch $values
interp alias {} $name@ {} lindex $values
}
it would be used like this:
enumerate fruit {apple blueberry cherry date elderberry}
fruit: date
# ==> prints "3"
fruit@ 2
# ==> prints "cherry"
[edit] Toka
Toka has no data types, and therefore no actual enumeration type. There is an optional library function which does provide a way to create enumerated values easily though.
This library function takes a starting value and a list of names as shown in the example below.
needs enum
0 enum| apple banana carrot |
10 enum| foo bar baz |
[edit] Visual Basic .NET
' Is this valid?!
Enum fruits
apple
banana
cherry
End Enum
' This is correct
Enum fruits
apple = 0
banana = 1
cherry = 2
End Enum

