Enumerations: Difference between revisions

From Rosetta Code
Content added Content deleted
m (omit TI-BASIC)
(add m4)
Line 300: Line 300:
enum fruits { apple, banana, cherry }
enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits { apple = 0, banana = 1, cherry = 2 }

=={{header|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:
<pre>
c=3
</pre>


=={{header|Metafont}}==
=={{header|Metafont}}==

Revision as of 01:40, 7 September 2009

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

ActionScript

<lang actionscript> var fruit:Object = {apple: 0, banana: 1, cherry: 2}; </lang> Or more explicitly <lang actionscript> public class Fruit {

   public static const APPLE:int = 0;
   public static const BANANA:int = 1;
   public static const CHERRY:int = 2;

} </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 algol>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 algol>BEGIN # example 2 #

 MODE ENUM = [0]CHAR; # something with minimal size #
 MODE FRUIT = UNION(STRUCT(ENUM apple), STRUCT(ENUM banana), STRUCT(ENUM cherry));
 OP REPR = (FRUIT f)STRING:
   CASE f IN
     (STRUCT(ENUM apple)):"Apple",
     (STRUCT(ENUM banana)):"Banana",
     (STRUCT(ENUM cherry)):"Cherry"
   OUT
     "?" # uninitalised #
   ESAC;
 FRUIT x := LOC STRUCT(ENUM cherry);
 CASE x IN
   (STRUCT(ENUM apple)):print(("It is an ",REPR x, new line)),
   (STRUCT(ENUM banana)):print(("It is a ",REPR x, new line)),
   (STRUCT(ENUM 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 union construct was intended to be used.

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:

enum["apple"]=1; enum["banana"]=2; enum["cherry"]=3
enum[1]="apple"; enum[2]="banana"; enum[3]="cherry"

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

C

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

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

C++

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

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

C#

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

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

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 }

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"])

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

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#

type fruit = 
  | Apple
  | Banana
  | Cherry
let basket = [ Apple ; Banana ; Cherry ]
Seq.iter (fun a -> printfn "%A" a) basket

Haskell

data Fruit = Apple | Banana | Cherry deriving Enum

Java

Works with: Java version 1.5+
 enum fruits { apple, banana, cherry }
 enum fruits
 {
   apple(0), banana(1), cherry(2)
   private final int value;
   fruits(int value) { this.value = value; }
   public int value() { return value; }
 }

JavaScript

 var fruits = { apple, banana, cherry };
 var fruits = { apple : 0, banana : 1, cherry : 2 };

JSON

 fruits { apple, banana, cherry };
 fruits { apple : 0, banana : 1, cherry : 2 };

JScript.NET

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

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

type fruit =
  Apple
| Banana
| Cherry

Perl

 # Using an array
 my @fruits = qw(apple banana cherry);
 # Using a hash
 my %fruits = ( apple => 0, banana => 1, cherry => 2 );

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

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

Or more cryptically:

vars().update(zip(*zip(*list(enumerate(("FIRST_NAME","LAST_NAME","PHONE"))))[::-1]))

R

R does not have an enumeration type, though factors provide a similar functionality. <lang R>

factor(c("apple", "banana", "cherry"))
# [1] apple  banana cherry
# Levels: apple banana cherry

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

Raven

{ 'apple' 0 'banana' 1 'cherry' 2 } as fruits

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

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

Seed7

 const type: fruits is new enum
     apple, banana, cherry
   end enum;

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

datatype fruit =
  Apple
| Banana
| Cherry

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.

needs enum
0 enum| apple banana carrot |
10 enum| foo bar baz |

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