You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.

Generating Quotation Expressions

Decomposing quotation expressions gives you a way to inspect and transform ASTs, but you can build up quotation expressions dynamically at runtime as well.

Generating quotation expressions is especially useful when creating mini-programming languages. Rather than writing F# code and processing the AST, you can parse another, perhaps simpler, language to generate the expression tree and then process that.

Any active pattern you see for decomposing quotation expressions has a complementary static method on the Expr class for producing an equivalent Expr<_> value.

The following snippet shows taking the quotation of a simple expression and the equivalent way to build up that same expression value:

let organicQuotation =
        let x = (1, 2, 3)
        (x, x)

let syntheticQuotation =
        new Var("x", typeof<int * int * int>),
        Expr.NewTuple( [ Expr.Value(1); Expr.Value(2); Expr.Value(3) ] ),
        Expr.NewTuple( [ Expr.GlobalVar("x").Raw; Expr.GlobalVar("x").Raw ] )

Expression Holes

Using methods on the Expr type isn’t the only way to generate quotation expressions. Quotations may contain expression holes, which are locations for new instances of Expr<_> to be placed, allowing you to build up expression trees by simply patching holes in an existing expression.

To declare an expression hole, simply use a percent sign % in front of any expression within the quotation, and the result of that expression will be bound to the generated quotation expression tree. (Similar ...

The best content for your career. Discover unlimited learning on demand for around $1/day.