Enumerations: Difference between revisions
m (Fixed lang tags.) |
Underscore (talk | contribs) m (→{{header|JScript.NET}}: <lang jscript.net> -> <lang jscript>) |
||
Line 292: | Line 292: | ||
=={{header|JScript.NET}}== |
=={{header|JScript.NET}}== |
||
<lang jscript |
<lang jscript>enum fruits { apple, banana, cherry } |
||
enum fruits { apple = 0, banana = 1, cherry = 2 }</lang> |
enum fruits { apple = 0, banana = 1, cherry = 2 }</lang> |
||
Revision as of 12:21, 23 November 2009
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
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
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 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: <lang awk>enum["apple"]=1; enum["banana"]=2; enum["cherry"]=3 enum[1]="apple"; enum[2]="banana"; enum[3]="cherry"</lang>
BASIC
<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.
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>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
<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
<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>
Perl
<lang perl># Using an array my @fruits = qw(apple banana cherry);
- Using a hash
my %fruits = ( apple => 0, banana => 1, cherry => 2 );</lang>
Perl 6
<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>
Python
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] 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
<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
- ==> prints "3"
fruit@ 2
- ==> 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>
- Programming Tasks
- Basic language learning
- ActionScript
- Ada
- ALGOL 68
- AmigaE
- AutoHotkey
- AWK
- BASIC
- C
- C++
- C sharp
- Common Lisp
- D
- E
- Forth
- Fortran
- F Sharp
- Haskell
- J
- Java
- JavaScript
- JSON
- JScript.NET
- M4
- Metafont
- Modula-3
- OCaml
- Perl
- Perl 6
- PHP
- Python
- R
- Raven
- Ruby
- Scheme
- Seed7
- Slate
- Standard ML
- Tcl
- Toka
- Visual Basic .NET
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit