Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I believe you were trying to do the following: for any Discriminated Union have an ability to go from particular DU case to its name and back without burden of hardcoding the relationship for each pair, which have place in both answers by Brian and pad.</p> <p>If you sacrifice override of ToString() in lieu of the equivalent static member it can be done with the following approach:</p> <pre><code>open Microsoft.FSharp.Reflection type Blah = | AThing | AnotherThing [&lt;AutoOpenAttribute&gt;] module BlahExt = let cases = FSharpType.GetUnionCases typeof&lt;Blah&gt; let toBlah = dict [for case in cases do yield (case.Name, FSharpValue.MakeUnion(case, [||]) :?&gt; Blah)] let fromBlah = dict [for case in cases do yield ((FSharpValue.MakeUnion(case, [||]) :?&gt; Blah), case.Name)] type Blah with static member ofString name = if toBlah.ContainsKey name then (toBlah.Item name) else failwith "bad string" static member toString x = fromBlah.Item x </code></pre> <p>Now <code>printfn "ofString: %A" (Blah.ofString "AThing")</code> shows union case <code>AThing</code> and vice versa <code>printfn "toString: %s" (Blah.toString AThing)</code> shows string <code>AThing</code>.</p> <p>You can notice that I did not list members of your DU whatsoever, this is achieved once thru reflection and guaranteed to be correct mapping automagically. This approach will work <strong>for any number of unit cases</strong> - two or two hundreds - without any need to hardcode the particular cases.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload