Created
December 17, 2018 20:45
-
-
Save jackmott/093abba3c9c5df87e22373be8e6e52a7 to your computer and use it in GitHub Desktop.
AST Cleaned Up
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
type ASTNode = | |
| Add of (ASTNode * ASTNode) | |
| Sub of (ASTNode * ASTNode) | |
| X | |
| Constant of int | |
let rec Evaluate node x = | |
match node with | |
| Add (l,r) -> (Evaluate l x) + (Evaluate r x) | |
| Sub (l,r) -> (Evaluate l x) - (Evaluate r x) | |
| X -> x | |
| Constant v -> v | |
let rec ASTToString node = | |
match node with | |
| Add (l,r) -> "(" + (ASTToString l) + " + " + (ASTToString r) + ")" | |
| Sub (l,r) -> "(" + (ASTToString l) + " - " + (ASTToString r) + ")" | |
| X -> "X" | |
| Constant v -> string v | |
let rec ConstantFolding node = | |
match node with | |
| Add (l,r) -> match (ConstantFolding(l),ConstantFolding(r)) with | |
| (Constant v1,Constant v2) -> Constant(v1+v2) | |
| (optL,optR) -> Add(optL,optR) | |
| Sub(l,r) -> match (ConstantFolding(l),ConstantFolding(r)) with | |
| (Constant v1,Constant v2) -> Constant(v1-v2) | |
| (optL,optR) -> Sub(optL,optR) | |
| X -> X | |
| Constant v -> Constant(v) | |
[<EntryPoint>] | |
let main argv = | |
let equation = Sub(Constant(3),Add(Constant(5),Constant(2))) | |
let optimized = ConstantFolding equation | |
//let result = Evaluate equation 2 | |
printfn "%A" (ASTToString optimized) | |
Console.ReadLine() | |
0 // return an integer exit code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment