Skip to content

Instantly share code, notes, and snippets.

@jackmott jackmott/ast.fs
Created Dec 17, 2018

Embed
What would you like to do?
AST Cleaned Up
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
You can’t perform that action at this time.