Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting byte to an instance of an enum in F#

Tags:

enums

f#

Let's consider the following enum in C#

public enum ScrollMode : byte
{
      None = 0,
      Left = 1,
      Right = 2,
      Up = 3,
      Down = 4
}

The F# code receives a byte and has to return an instance of the enum I have tried

let mode = 1uy
let x = (ScrollMode)mode

(Of course in the real application I do not get to set 'mode', it is received as part of network data).

The example above does not compile, any suggestions?

like image 794
TimothyP Avatar asked May 15 '09 02:05

TimothyP


1 Answers

For enums whose underlying type is 'int', the 'enum' function will do the conversion, but for non-int enums, you need 'LanguagePrimitives.EnumOfValue', a la:

// define an enumerated type with an sbyte implementation
type EnumType =
  | Zero = 0y
  | Ten  = 10y

// examples to convert to and from
let x = sbyte EnumType.Zero
let y : EnumType = LanguagePrimitives.EnumOfValue 10y

(EnumOfValue is listed here

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.LanguagePrimitives.html

(now http://msdn.microsoft.com/en-us/library/ee340276(VS.100).aspx )

whereas enum is listed here

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html

(now http://msdn.microsoft.com/en-us/library/ee353754(VS.100).aspx ) )

like image 131
Brian Avatar answered Oct 11 '22 19:10

Brian