Create an enumeration of types with and without values.

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

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>

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: <lang awk>enum["apple"]=1; enum["banana"]=2; enum["cherry"]=3 enum[1]="apple"; enum[2]="banana"; enum[3]="cherry"</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>

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

Works with: DMD
Works with: GDC

<lang d>enum fruits { apple, banana, cherry }

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

enum fruits : int { apple = 0, banana = 1, cherry = 2 }</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>

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#

<lang fsharp>type fruit =

 | Apple
 | Banana
 | Cherry

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

Haskell

<lang haskell>data Fruit = Apple | Banana | Cherry deriving Enum</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.

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>

JavaScript

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

JSON

<lang json>fruits { apple, banana, cherry }; 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>

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

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>

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>

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>

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

<lang PureBasic>Enumeration

  #Apple
  #Banana
  #Cherry

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> Or more cryptically: <lang python>vars().update(zip(*zip(*list(enumerate(("FIRST_NAME","LAST_NAME","PHONE"))))[::-1]))</lang>

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.

Raven

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

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>

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>

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>