Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# getting list of possible discriminated union item

Tags:

f#

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#

like image 223
abhishek Avatar asked Jan 10 '17 01:01

abhishek


1 Answers

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

like image 96
Sean Kearon Avatar answered Nov 07 '22 04:11

Sean Kearon