56 people like it.

Compiling quotations

Demonstrates how to compose code at run time using F# quotations (both typed and untyped) and how to compile and run the quotation using F# PowerPack API.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
#r "FSharp.PowerPack.Linq.dll"
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation
    
// Create a part of expression using "Expr" calls 
// (this creates arbitrary untyped quotation)
let expr = Expr.Value(13)

// Create a part using quotation syntax 
// (splicing untyped part in using %%)
let expr2 = <@ (fun x -> x * %%expr) @>
    
// Compile the quotation & Run returned function
let f = expr2.Compile()()
f 10
namespace Microsoft
namespace Microsoft.FSharp
namespace Microsoft.FSharp.Quotations
namespace Microsoft.FSharp.Linq
val expr : Expr

Full name: Script.expr
Multiple items
type Expr =
  override Equals : obj:obj -> bool
  member GetFreeVars : unit -> seq<Var>
  member Substitute : substitution:(Var -> Expr option) -> Expr
  member ToString : full:bool -> string
  member CustomAttributes : Expr list
  member Type : Type
  static member AddressOf : target:Expr -> Expr
  static member AddressSet : target:Expr * value:Expr -> Expr
  static member Application : functionExpr:Expr * argument:Expr -> Expr
  static member Applications : functionExpr:Expr * arguments:Expr list list -> Expr
  ...

Full name: Microsoft.FSharp.Quotations.Expr

--------------------
type Expr<'T> =
  inherit Expr
  member Raw : Expr

Full name: Microsoft.FSharp.Quotations.Expr<_>
static member Expr.Value : value:'T -> Expr
static member Expr.Value : value:obj * expressionType:System.Type -> Expr
val expr2 : Expr<(int -> int)>

Full name: Script.expr2
val x : int
val f : (int -> obj)

Full name: Script.f

More information

Link:http://fssnip.net/11
Posted:6 years ago
Author:Tomas Petricek
Tags: quotations , compilation , run time