It's certainly possible to create a function that does something like what you want. Unfortunately, enumerated types in .NET are a bit strange, so you'll want to think about how to handle corner cases. For instance, it's possible to have instances of an enumerated type which don't match any of the named instances (e.g.

1
let (c:color) = enum 7

. It's also possible to create enums where the same underlying value is given more than one name:

1
type weird = | x = 0 | y = 0 | z = 1

Depending on how you want your function to behave, here are a few different approaches you can take. This will give you a new enum with an underlying value which is one higher than that of the enum passed in (regardless of whether that's a valid option):

1
2
3
4
5
let inline succ (e:'en when 'en : enum<'a>) : 'en =
  e 
  |> LanguagePrimitives.EnumToValue
  |> (LanguagePrimitives.AdditionDynamic (LanguagePrimitives.GenericOne:'a))
  |> LanguagePrimitives.EnumOfValue

This will pick the first explicitly defined value higher than the value passed in (or throw if there is none):

1
2
3
4
let succ (e:'en when 'en:enum<'a>) : 'en =
  System.Enum.GetValues(typeof<'en>) :?> 'en[]
  |> Array.find (fun e' -> e' > e)
  |> unbox
By on 2/18/2010 8:06 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper