I am creating a simple DSL with multiple discriminated unions(DU) . There is building block DU and higher DUs are build on top of lower ones.
Now I want to create UI where user can build a text which matches my DSL. to UI I don't want to express my full grammar, but show only possible actions that can be done. So I need a way to figure out from my hierarchical DU, what are other possible states that user can do.
sample input text (1 + (2 * 3))
type Expression =
| Constant of int
| Add of Expression * Expression
| Mul of expression * Expression
so when user starts, I have to return a list saying only Constant
can be used.
when user passes (constant ) as his current state, I have to tell you can add/Mul
(which is expression) and so on.
I want to represent a structure which says, current state and possible states to go from in a type safe way. Is there a way to solve this kind of problem in f#
I think you're looking for FSharpType.GetUnionCases
. You can use this as follows:
open System
open Microsoft.FSharp.Collections
open Microsoft.FSharp.Reflection
type Expression =
| Constant of int
| Add of Expression * Expression
| Mul of Expression * Expression
typeof<Expression> |> FSharpType.GetUnionCases|> Dump |> ignore
LinqPad for the above here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With