f# - How to iterate over an Enum, and cast the obj -


how enumerate enum/type in f# tells how enumerator .net enum type in f#:

use: enum.getvalues(typeof<mytype>)

however, when put use found limitation. can work around limitation, looking better way.

the problem solution returns .net array of objects, use need cast it, , casting unwieldy iteration.

type colors = | red = 0 | blue = 1 | green = 2  // typed function, show 'obj' in real use let isfavorite color = color = colors.green  // iterate on enum (colors) color in enum.getvalues(typeof<colors>)     printfn "color %a. favorite -> %b" color (isfavorite color)  // <-- need cast 

the (isfavorite color) raises type conflict between colors (expected) , obj (actual)

this fixed:

for obj in enum.getvalues(typeof<colors>)     printfn "color %a. favorite -> %b" obj (isfavorite (unbox<colors> obj)) 

but, if 1 needs (unbox<colors> obj) in several places?

a local let color = ... suffice, but, ideally, use enumerable-expression returns seq<colors>.

i have been able build expression, is: a. difficult build, , b. long winded.

let colorsseq =       seq.cast (enum.getvalues(typeof<colors>))       |> seq.map (fun o -> unbox<colors> o)  color in colorsseq     printfn "color %a. favorite -> %b" color (isfavorite color) 

is there better expression?

this seem simplest possible version:

let t : colors seq = unbox (enum.getvalues(typeof<colors>))  

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -