Created
November 2, 2018 20:41
-
-
Save 7sharp9/a9d2e5fd598792d46dbeccae3aca6c3a to your computer and use it in GitHub Desktop.
Introduction to quotations
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 | |
open Microsoft.FSharp.Quotations | |
open Microsoft.FSharp.Quotations.Patterns | |
open Microsoft.FSharp.Quotations.ExprShape | |
open Microsoft.FSharp.Quotations.DerivedPatterns | |
let qliteral = | |
<@ | |
let addAndMultiply a b = | |
let first = a + b | |
let second = a * b | |
first + second in addAndMultiply | |
@> | |
let splicing = | |
<@ (%qliteral) 2 3 @> | |
let rec traverse expr = | |
match expr with | |
| Application(e1, e2) -> | |
printfn "Application" | |
traverse e1 | |
traverse e2 | |
| Let(v, e1, e2) -> | |
printfn "let" | |
traverse e1 | |
traverse e2 | |
| Lambda(v, e) -> | |
printfn "lambda" | |
traverse e | |
| other -> printfn "other: %A" other | |
traverse qliteral | |
let rec substituteExpr expr = | |
match expr with | |
| SpecificCall<@ (+) @> (_, _, exprs) -> | |
let lhs = exprs |> List.head | |
let rhs = exprs |> List.last | |
<@@ %%lhs - %%rhs @@> | |
| ShapeVar var -> Expr.Var var | |
| ShapeLambda(var, expr) -> | |
Expr.Lambda(var, substituteExpr expr) | |
| ShapeCombination(shapeCombo, exprs) -> | |
RebuildShapeCombination(shapeCombo, List.map substituteExpr exprs) | |
let result = substituteExpr <@ 1 + 1 @> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment