Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate an enum/type in F#

Tags:

.net

enums

f#

I've got an enumeration type defined like so:

type tags = 
    | ART  = 0
    | N    = 1
    | V    = 2 
    | P    = 3
    | NULL = 4

is there a way to do a for ... in tags do ?

This is the error that I'm getting:

The value, constructor, namespace or type tags is not defined

like image 955
Jared Avatar asked Feb 02 '10 04:02

Jared


People also ask

How do you define an enum type?

You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type. Specify the type after enum name as : type .

How do I iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

What is enumerated data type with example?

An enumerated type is a type whose legal values consist of a fixed set of constants. Common examples include compass directions, which take the values North, South, East and West and days of the week, which take the values Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday.

Which is the correct syntax for defining an enumeration data type?

The keyword “enum” is used to declare an enumeration. Here is the syntax of enum in C language, enum enum_name{const1, const2, ....... }; The enum keyword is also used to define the variables of enum type.


2 Answers

How about:

let enumToList<'a> = (Enum.GetValues(typeof<'a>) :?> ('a [])) |> Array.toList

This has the advantage of providing a strongly typed list

To use just do:

let tagList = enumToList<tags>
like image 91
bill Avatar answered Nov 24 '22 09:11

bill


Use Enum.GetValues:

let allTags = Enum.GetValues(typeof<tags>)
like image 42
jason Avatar answered Nov 24 '22 07:11

jason