Enumerations: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 543: Line 543:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>var fruits = { apple : 0, banana : 1, cherry : 2 };</lang>
<lang javascript>
var fruits = { apple : 0, banana : 1, cherry : 2 };

<lang javascript>var fruits = Object.freeze({ apple : 0, banana : 1, cherry : 2 });</lang>
var fruits = Object.freeze({ apple : 0, banana : 1, cherry : 2 });
</lang>
Prevents modification of enumeration at runtime.
Object.freeze() Prevents modification of enumeration at runtime.


=={{header|JSON}}==
=={{header|JSON}}==

Revision as of 21:39, 19 February 2014

Task
Enumerations
You are encouraged to solve this task according to the task description, using any language you may know.

Create an enumeration of constants with and without explicit values.

ACL2

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

<lang Lisp>(defun symbol-to-constant (sym)

  (intern (concatenate 'string "*" (symbol-name sym) "*")
          "ACL2"))

(defmacro enum-with-vals (symbol value &rest args)

  (if (endp args)
      `(defconst ,(symbol-to-constant symbol) ,value)
      `(progn (defconst ,(symbol-to-constant symbol) ,value)
              (enum-with-vals ,@args))))

(defun interleave-with-nats-r (xs i)

  (if (endp xs)
      nil
      (cons (first xs)
            (cons i (interleave-with-nats-r (rest xs)
                                            (1+ i))))))

(defun interleave-with-nats (xs)

  (interleave-with-nats-r xs 0))

(defmacro enum (&rest symbols)

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

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

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. <lang algol68>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;</lang> 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. <lang algol68>BEGIN # example 2 #

 MODE ENUM = [0]CHAR; # something with minimal size #
 MODE APPLE = STRUCT(ENUM apple), BANANA = STRUCT(ENUM banana), CHERRY = STRUCT(ENUM cherry);
 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</lang> 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.

AmigaE

<lang amigae>ENUM APPLE, BANANA, CHERRY

PROC main()

 DEF x
 ForAll({x}, [APPLE, BANANA, CHERRY],
        `WriteF('\d\n', x))

ENDPROC</lang>

writes 0, 1, 2 to the console.

AutoHotkey

AutoHotkey doesn't really enforce types.
However you can simulate types like enumeration with associative arrays: <lang AutoHotkey>fruit_%apple% = 0 fruit_%banana% = 1 fruit_%cherry% = 2</lang>

AWK

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 fruit[1]="apple"; fruit[2]="banana"; fruit[3]="cherry" i=0; apple=++i; banana=++i; cherry=++i;</lang>

BASIC

Works with: QuickBasic version 4.5
Works with: PB version 7.1

<lang qbasic>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</lang>

Bracmat

Wikipedia says: 'An enumeration is a collection of items that is a complete, ordered listing of all of the items in that collection.' So the task is taken to be: '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. <lang bracmat>fruits=apple+banana+cherry;</lang>

C

<lang c>enum fruits { apple, banana, cherry };

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

C++

<lang cpp>enum fruits { apple, banana, cherry };

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

C#

<lang csharp>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 }</lang>

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.

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: <lang clojure>; 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))</lang>

Common Lisp

Values:

<lang lisp>;; symbol to number (defconstant +apple+ 0) (defconstant +banana+ 1) (defconstant +cherry+ 2)

number to symbol

(defun index-fruit (i)

 (aref #(+apple+ +banana+ +cherry+) i))</lang>

Of course, the two definitions above can be produced by a single macro, if desired.

Defining a type for documentation or checking purposes:

<lang lisp>(deftype fruit ()

 '(member +apple+ +banana+ +cherry+))</lang>

D

<lang d>// Named (commonly used enum in D) (int). enum Fruits1 { apple, banana, cherry }

// Anonymous, as in C. enum { APPLE, BANANA, CHERRY }

// Named with specified values (int). enum Fruits2 { apple = 0, banana = 10, cherry = 20 }

// Named, typed and with specified values. enum Fruits3 : ubyte { apple = 0, banana = 100, cherry = 200 }

void main() {

   static assert(CHERRY == 2);
   int f1 = Fruits2.banana; // No error.
   // Fruits2 f2 = 1; // Error: cannot implicitly convert.

}</lang>

Delphi

<lang Delphi>type

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


DWScript

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

E

Simple group of object definitions (value methods could be left out if appropriate):

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

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

def [Fruit, [=> apple, => banana, => cherry]] :=

 makeEnumeration(0, ["apple", "banana", "cherry"])</lang>

EGL

Works with: EDT

<lang EGL>// Without explicit values enumeration FruitsKind APPLE, BANANA, CHERRY end

program EnumerationTest

function main() whatFruitAmI(FruitsKind.CHERRY); end

function whatFruitAmI(fruit FruitsKind) case (fruit) when(FruitsKind.APPLE) syslib.writestdout("You're an apple."); when(FruitsKind.BANANA) syslib.writestdout("You're a banana."); when(FruitsKind.CHERRY) syslib.writestdout("You're a cherry."); otherwise syslib.writestdout("I'm not sure what you are."); end end

end</lang>

Works with: EDT

-and-

Works with: RBD

<lang EGL>// With explicit values library FruitsKind type BasicLibrary {} const APPLE int = 0; const BANANA int = 1; const CHERRY int = 2; end

program EnumerationTest

function main() whatFruitAmI(FruitsKind.CHERRY); end

function whatFruitAmI(fruit int in) case (fruit) when(FruitsKind.APPLE) syslib.writestdout("You're an apple."); when(FruitsKind.BANANA) syslib.writestdout("You're a banana."); when(FruitsKind.CHERRY) syslib.writestdout("You're a cherry."); otherwise syslib.writestdout("I'm not sure what you are."); end end

end </lang>

Erlang

For the unspecific value enum use case, Erlang has atoms. You can use apple, banana, orange directly in the code. If they have to have a specific value they could be grouped like this: {apple, 1}, {banana, 3}, {orange, 8}

Fantom

Enumerations with named constants:

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

A private constructor can be added to initialise internal fields, which must be constant.

<lang Fantom> // create an enumeration with explicit values enum class Fruits_ {

 apple (1), banana (2), orange (3)
 const Int value
 private new make (Int value) { this.value = value }

} </lang>

Forth

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 1 CONSTANT banana 2 CONSTANT cherry ...</lang> 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> This word defines a new constant of the value specified and returns the next value in sequence. It would be used like this:

<lang forth>0 ENUM APPLE ENUM BANANA ENUM CHERRY DROP</lang>

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

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

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 + ;

CELL-ENUM ( n -<name>- n+cell ) CELL SIZED-ENUM ;</lang>

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

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

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: <lang forth>: CONSTANTS ( n -- ) 0 DO I CONSTANT LOOP ;

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

Fortran

Works with: Fortran version 2003

<lang fortran>enum, bind(c)

 enumerator :: one=1, two, three, four, five
 enumerator :: six, seven, nine=9

end enum</lang>

The syntax

<lang fortran>enum, bind(c) :: nametype

 enumerator :: one=1, two, three

end enum nametype</lang>

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...)

F#

Enumerations in F# always have explicit values: <lang fsharp>type Fruit =

 | Apple = 0
 | Banana = 1
 | Cherry = 2

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

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.

<lang fsharp>type Fruit =

 | Apple
 | Banana
 | Cherry

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

Go

Go's enumeration-like feature is called iota. It generates sequential integer constants. <lang go>const (

  apple = iota
  banana
  cherry

)</lang> The above is equivalent to, <lang go>const (

  apple = 0
  banana = 1
  cherry = 2

)</lang> Constants in Go are not typed they way variables are, and so constants defined with iota do not actually represent an enumeration data type. Go does not have an enumeration data type.

Groovy

Enumerations: <lang groovy>enum Fruit { apple, banana, cherry }

enum ValuedFruit {

   apple(1), banana(2), cherry(3);
   def value
   ValuedFruit(val) {value = val}
   String toString() { super.toString() + "(${value})" }

}

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

Output:

[apple, banana, cherry]
[apple(1), banana(2), cherry(3)]

Haskell

<lang haskell>data Fruit = Apple | Banana | Cherry deriving Enum</lang>

Inform 7

<lang inform7>Fruit is a kind of value. The fruits are apple, banana, and cherry.</lang>

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

Table of Fruits fruit numeric value apple 1 banana 2 cherry 3</lang>

Icon and Unicon

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

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

J

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

  ( (;:'apple banana cherry') ,L:0 '__enum' ) =: i. 3
  cherry__enum

2</lang>

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. <lang j> fruit=: ;:'apple banana cherry'</lang>

Now you can get the name associated with an index:

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

And you can get the index associated with a name:

<lang j> fruit i.<'banana' 1</lang>

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' +------+ |cherry| +------+</lang>

And, you can iterate over the values (though an example of that is probably beyond the scope of this task), along with numerous other variations on these themes.

A person could reasonably argue that enums were introduced in some languages to work around deficiencies in array handling in those languages.

Java

Works with: Java version 1.5+

<lang java5>enum Fruits{

  APPLE, BANANA, CHERRY

}</lang> Or: <lang java5>enum Fruits{

 APPLE(0), BANANA(1), CHERRY(2)
 private final int value;
 fruits(int value) { this.value = value; }
 public int value() { return value; }

}</lang> 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.

JavaScript

<lang javascript> var fruits = { apple : 0, banana : 1, cherry : 2 }; var fruits = Object.freeze({ apple : 0, banana : 1, cherry : 2 }); </lang> Object.freeze() Prevents modification of enumeration at runtime.

JSON

<lang json>{"fruits" : { "apple" : null, "banana" : null, "cherry" : null } {"fruits" : { "apple" : 0, "banana" : 1, "cherry" : 2 }</lang>

JScript.NET

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

Lua

An explicit enum can be formed by mapping strings to numbers

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

or simply by local variables.

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

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

M4

<lang 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</lang>

Output:

c=3


Mathematica

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}] ->{{1}, {2}, {3}, {4}}

A ->{1}

B ->{2}

G ->{4}</lang>


MATLAB / Octave

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: <lang MATLAB>stuff = {'apple', [1 2 3], 'cherry',1+2i}

stuff =

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

Metafont

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) = save ?; ? := first; forsuffixes e := t: e := ?; ?:=?+1; endfor enddef;</lang>

Usage example:

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

end</lang>

Modula-3

<lang modula3>TYPE Fruit = {Apple, Banana, Cherry};</lang> The values are accessed by qualifying their names. <lang modula3>fruit := Fruit.Apple;</lang> You can get an element's position in the enumeration by using ORD and get the element given the position by using VAL. <lang modula3>ORD(Fruit.Apple); (* Returns 0 *) VAL(0, Fruit); (* Returns Fruit.Apple *)</lang>

Nemerle

<lang Nemerle>enum Fruit {

   |apple
   |banana
   |cherry

}

enum Season {

   |winter = 1
   |spring = 2
   |summer = 3
   |autumn = 4

}</lang>

Objeck

<lang objeck> enum Color := -3 {

 Red,
 White,
 Blue

}

enum Dog {

 Pug,
 Boxer,
 Terrier

} </lang>

OCaml

<lang ocaml>type fruit =

 | Apple
 | Banana
 | Cherry</lang>

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: <lang oz>declare

 fun {IsFruit A}
    {Member A [apple banana cherry]}
 end

in

 {Show {IsFruit banana}}</lang>

If you need constants with increasing values, you could just enumerate them manually: <lang oz>declare

 Apple = 1
 Banana = 2
 Cherry = 3</lang>

Or you could write a procedure that does the job automatically: <lang oz>declare

 proc {Enumeration Xs}
    Xs = {List.number 1 {Length Xs} 1}
 end
 [Apple Banana Cherry] = {Enumeration}

in

 {Show Cherry}</lang>

Pascal

See Delphi

Perl

<lang perl># Using an array my @fruits = qw(apple banana cherry);

  1. Using a hash

my %fruits = ( apple => 0, banana => 1, cherry => 2 );</lang>

Perl 6

Works with: Rakudo version #21 "Seattle"

<lang perl6>enum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.

enum ClassicalElement (

   Earth => 5,
   'Air', # Gets the value 6.
   Fire => 'hot',
   Water => 'wet'

);</lang>

PHP

<lang 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);</lang>

PicoLisp

Enumerations are not very useful in a symbolic language like PicoLisp. If desired, an 'enum' function could be defined: <lang PicoLisp>(de enum "Args"

  (mapc def "Args" (range 1 (length "Args"))) )</lang>

And used in this way: <lang PicoLisp>: (enum A B C D E F) -> F</lang>

: A
-> 1
: B
-> 2
: F
-> 6

PL/I

<lang PL/I> define ordinal animal (frog, gnu, elephant, snake);

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

PureBasic

Basic Enumeration is defined as <lang PureBasic>Enumeration

  #Apple
  #Banana
  #Cherry

EndEnumeration</lang> This can also be adjusted to the form <lang PureBasic>Enumeration 10200 Step 12

 #Constant1           ; 10200
 #Constant2           ; 10212
 #Constant3           ; 10224
 #Constant4 = 10117   ; 10117
 #Constant5           ; 10229

EndEnumeration</lang> 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; <lang PureBasic>Enumeration #PB_Compiler_EnumerationValue

 #Constant_A           ; 10241
 #Constant_B           ; 10242

EndEnumeration</lang>

Python

Works with: Python version 2.5

There is no special syntax, typically global variables are used with range: <lang python>FIRST_NAME, LAST_NAME, PHONE = range(3)</lang> 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>

Note that enumerations are coming to Python version 3.4.

R

R does not have an enumeration type, though factors provide a similar functionality. <lang R> factor(c("apple", "banana", "cherry"))

  1. [1] apple banana cherry
  2. Levels: apple banana cherry</lang>

This thread in the R mail archive contains code for an enum-like class for traffic light colours.

Racket

<lang Racket>

  1. lang racket
Like other Lisps, Racketeers prefer using symbols directly instead of
numeric definitions, and lists of symbols instead of bitwise
combinations

(define fruits '(apple banana cherry))

In Typed Racket, a type can be defined for a specific set of symbols
(define-type Fruit (U 'apple 'banana 'cherry))
The conventional approach is possible too, of course

(define APPLE 1) (define BANANA 2) (define CHERRY 4)

And finally, when dealing with foreign functions it is useful to
translate idiomatic Racket values (= symbols) to/from integers.
Racket's ffi has two ways to do this -- either an enumeration (for
independent integer constants) or a bitmask (intended to represent
sets using bitwise or)

(require ffi/unsafe) (define _fruit (_enum '(APPLE = 1

                        BANANA
                        CHERRY = 4)))

(define _fruits (_bitmask '(APPLE = 1

                           BANANA = 2
                           CHERRY = 4)))
Normally, Racket code will just use plain values (a symbol for the
first, and a list of symbols for the second) and the foreign side
sees the integers. But do demonstrate this, we can use the primitive
raw functionality to see how the translation works

(require (only-in '#%foreign ctype-scheme->c ctype-c->scheme))

((ctype-scheme->c _fruit) 'CHERRY)  ; -> 4 ((ctype-scheme->c _fruits) 'CHERRY)  ; -> 4 ((ctype-scheme->c _fruits) '(APPLE CHERRY)) ; -> 5

((ctype-c->scheme _fruit) 4) ; -> 'CHERRY ((ctype-c->scheme _fruits) 4) ; -> '(CHERRY) ((ctype-c->scheme _fruits) 5) ; -> '(APPLE CHERRY) </lang>

Raven

<lang raven>{ 'apple' 0 'banana' 1 'cherry' 2 } as fruits</lang>

Retro

Retro has a library named enum' for creation of enumerated values.

<lang Retro>needs enum' ( Creating a series of values ) 0 ^enum'enum| a b c d |

( Create values individually ) 0 ^enum'enum a ^enum'enum b</lang>

The actual values for each subsequent enumerated value created are determined by the ^enum'step function. This defaults to incrementing by 1, but can be altered as desired:

<lang Retro>with enum' [ 10 * ] is step 0 ^enum'enum| a b c d |</lang>

REXX

REXX has no types, and therefore has no enumeration type.

However, in the spirit of enumeration, REXX programmers can use stemmed arrays for enumerating constants (shown below).
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)]. <lang rexx>/*REXX program to illustrate enumeration of constants via stemmed arrays*/ fruit.=0 /*the default for all "FRUITS." */ fruit.apple = 65 fruit.cherry = 4 fruit.kiwi = 12 fruit.peach = 48 fruit.plum = 50 fruit.raspberry = 17 fruit.tomato = 8000 fruit.ugli = 2 fruit.watermelon = 0.5 /*could also specify: 1/2 */

                          /*A partial list of some fruits (below).     */
                          /* [↓]   This is one method of using a list. */

FruitList='apple apricot avocado banana bilberry blackberry blackcurrent blueberry baobab boysenberry breadfruit cantalope cherry chilli chokecherry citront',

 'coconut cranberry cucumber current date dragonfruit durian eggplant elderberry fig feijoa gac gooseberry grape grapefruit guava honeydew huckleberry jackfruit',
 'jambul juneberry kiwi kumquat lemon lime lingenberry loquat lychee mandarine mango mangosteen netarine orange papaya passionfruit peach pear persimmon',
 'physalis pineapple pitaya pomegranate pomelo plum pumpkin rambutan raspberry redcurrent satsuma squash strawberry tangerine tomato ugli watermelon zucchini'

/*┌────────────────────────────────────────────────────────────────────┐

 │ Spoiler alert:  sex is discussed below: PG-13.  Most berries don't │
 │ have  "berry"  in their name.   A berry is a simple fruit produced │
 │ from a single ovary.   Some true berries are:  pomegranate, guava, │
 │ eggplant, tomato, chilli, pumpkin, cucumber, melon, and  citruses. │
 │ Blueberry  is a  false  berry,  blackberry is an  aggregate fruit, │
 │ and  strawberry  is an  accessory  fruit.    Most nuts are fruits. │
 │ The following  aren't  true nuts:    almond,  cashew,  coconut,    │
 │ macadamia,  peanut,  pecan,  pistachio,  and  walnut.              │
 └────────────────────────────────────────────────────────────────────┘*/
                       /*  [↓] due to a Central America blight in 1922.*/

if fruit.banana=0 then say "Yes! We have no bananas today." /*(sic)*/ if fruit.kiwi \=0 then say "We gots" fruit.kiwi "hairy fruit." /*(sic)*/ if fruit.peach\=0 then say "We gots" fruit.peach "fuzzy fruit." /*(sic)*/ maxL = length(' fruit ') maxQ = length(' quantity ') say

    do pass=1  for 2                  /*first pass finds the maximums. */
         do j=1  for words(FruitList)
         f=word(FruitList,j)          /*get a fruit name from the list.*/
         q=value('FRUIT.'f)
         if pass==1  then do          /*widest fruit name and quantity.*/
                          maxL=max(maxL,length(f)) /*longest fruit name*/
                          maxQ=max(maxQ,length(q)) /*widest fruit quant*/
                          iterate  /*j*/
                          end
         if j==1  then say center('fruit',maxL)   center('quantity',maxQ)
         if j==1  then say copies('─',maxL)       copies('─',maxQ)
         if q\=0  then say right(f,maxL)          right(q,maxQ)
         end   /*j*/
    end        /*pass*/
                                      /*stick a fork in it, we're done.*/</lang>

output

Yes!  We have no bananas today.
We gots 12 hairy fruit.
We gots 48 fuzzy fruit.

   fruit      quantity
──────────── ──────────
       apple         65
      cherry          4
        kiwi         12
       peach         48
        plum         50
   raspberry         17
      tomato       8000
        ugli          2
  watermelon        0.5

Ruby

There are plenty of ways to represent enum in Ruby. Here it is just one example: <lang ruby>module Fruits APPLE = 0 BANANA = 1 CHERRY = 2 end</lang>

Scala

1. Using Algebraic Data Types: <lang actionscript>sealed abstract class Fruit case object Apple extends Fruit case object Banana extends Fruit case object Cherry extends Fruit </lang> 2. Using scala.Enumeration: <lang actionscript>object Fruit extends Enumeration {

 val Apple, Banana, Cherry = Value

} </lang>

Scheme

<lang scheme>(define apple 0) (define banana 1) (define cherry 2)

(define (fruit? atom)

 (or (equal? 'apple atom)
     (equal? 'banana atom)
     (equal? 'cherry atom)))</lang>

(This section needs attention from someone familiar with Scheme idioms.)

Seed7

<lang seed7>const type: fruits is new enum

   apple, banana, cherry
 end enum;</lang>

Slate

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

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

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

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

Standard ML

<lang sml>datatype fruit =

 Apple

| Banana | Cherry</lang>

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

<lang tcl>proc enumerate {name values} {

   interp alias {} $name: {} lsearch $values
   interp alias {} $name@ {} lindex $values

}</lang>

it would be used like this:

<lang tcl>enumerate fruit {apple blueberry cherry date elderberry}

fruit: date

  1. ==> prints "3"

fruit@ 2

  1. ==> prints "cherry"</lang>

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.

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

VBA

Like Visual Basic .NET, actually: <lang vb> 'this enumerates from 0 Enum fruits

 apple
 banana
 cherry

End Enum

'here we use our own enumeration Enum fruits2

 pear = 5
 mango = 10
 kiwi = 20
 pineapple = 20

End Enum


Sub test() Dim f As fruits

 f = apple
 Debug.Print "apple equals "; f
 Debug.Print "kiwi equals "; kiwi
 Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple

End Sub </lang> Output:

test
apple equals  0 
kiwi equals  20 
cherry plus kiwi plus pineapple equals  42 

Visual Basic .NET

<lang vbnet>' Is this valid?! Enum fruits apple banana cherry End Enum

' This is correct Enum fruits apple = 0 banana = 1 cherry = 2 End Enum</lang>

XPL0

<lang XPL0>def \Fruit\ Apple, Banana, Cherry; \Apple=0, Banana=1, Cherry=2 def Apple=1, Banana=2, Cherry=4; </lang>