Convert Abstract Syntax Tree (AST) to F #

I am trying to create an AST for a logical decision table. One of the things that I would like to do with the discriminatory union that my ACT represents is transforming parts of it for various reasons. For clarity, I will give you an example.

Logical decision table

@VAR = 10; Y;

The above can be read because there is one rule, and the condition VAR = 10 is included in this rule with the entry Y.

Abstract syntax tree definition (simplified for this example)

type expression = | Value of double | Variable of string | Equality of expression * expression type entry = | Entry of string type entries = | Entries of entry list type conditional = | ConditionEntries of expression * entries type condition | Condition of expression * string type rule = | Rule of condition list 

Presented (before conversion)

 ConditionEntries( Equality( Variable("VAR"), Value(10.0)), Entries(["Y"])) 

Presented (after conversion)

 Rule( Condition( Equality( Variable("VAR"), Value(10.0) ), Entry("Y") ) ) 

Now what I would like to do is convert the above tree to expand the rules presented in the entries. I thought that I could use the recursive function and pattern matching to do this, but I have small problems wrapping my head around it right now.

I assume that basically what I'm trying to do is when I see the ConditionEntries node, I want to emit a new rule for each line in the Records list, where the Condition is combined with the Input. It makes sense?

Thanks in advance for any advice.

ps I didnโ€™t quite try to compile the above example, so please forgive any grammatical errors.

+4
source share
1 answer

Hmm, based on your AST, which is terribly broken, here is a tranform function that outputs the result from the input you want (although it is not recursive, it just uses List.map with some pattern matching. expression is your only recursive type, but it doesn't seem like do you want to process it recursively?):

 let ex1 = ConditionEntries( Equality( Variable("VAR"), Value(10.0)), Entries([Entry("Y")])) let ex2 = ConditionEntries( Equality( Variable("VAR"), Value(10.0)), Entries([Entry("X");Entry("Y");Entry("Z")])) let transform ces = match ces with | ConditionEntries(x, Entries(entries)) -> entries |> List.map (function Entry(entry) -> Condition(x, entry)) //FSI output: > transform ex1;; val it : condition list = [Condition (Equality (Variable "VAR",Value 10.0),"Y")] > transform ex2;; val it : condition list = [Condition (Equality (Variable "VAR",Value 10.0),"X"); Condition (Equality (Variable "VAR",Value 10.0),"Y"); Condition (Equality (Variable "VAR",Value 10.0),"Z")] 
+2
source

All Articles