20 people like it.

Supercompilation using quotations

This code sample shows how to create a function that raises number to a given power using supercompilation with quotations. For any given power, the function returns quoted expression for calculating the power using explicit multiplications, which is then evaluated.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
// Simulating supercompilation using quotations

(Linking to FSharp Powerpack)

// Raising x to the power of n
// Returns quotation expression that calculates the result
// metapower 5 x returns <@ x*x*x*x*x @>
let rec metapower n x =
  if n=0 then <@ 1 @>
  else (fun z -> <@ %x * %z @>) (metapower(n-1) x)

// Defining short synonim for quotation evaluation
let qeval = Microsoft.FSharp.Linq.QuotationEvaluator.Evaluate

// Raising arbitrary number to the power of 5
// Gets the quotation with expression x*x*x*x*x and evaluates it
let pow5 x = metapower 5 <@ x @> |> qeval

printfn "%d" (pow5 10)
#r "FSharp.Powerpack.Linq"
val metapower : n:int -> x:Quotations.Expr<int> -> Quotations.Expr<int>

Full name: Script.metapower
val n : int
val x : Quotations.Expr<int>
val z : Quotations.Expr<int>
val qeval : (Quotations.Expr<int> -> int)

Full name: Script.qeval
namespace Microsoft
namespace Microsoft.FSharp
namespace Microsoft.FSharp.Linq
val pow5 : x:int -> int

Full name: Script.pow5
val x : int
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view New version

More information

Link:http://fssnip.net/1W
Posted:6 years ago
Author:Dmitry Soshnikov
Tags: quotations , supercompilation