Skip to content

Instantly share code, notes, and snippets.

@7sharp9
Created Nov 2, 2018
Embed
What would you like to do?
Introduction to quotations
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