2

Without using the power pack to convert Expr to C# expressions, it seems like once I create an Expr, the only thing I can do with it is either print out a string representation of it, or...create another Expr.

If I print out a code quotation of an expression, I see that it prints out calls to static Expr methods. How can I use these for something useful?

  • Presumably by walking the expression tree and doing stuff with it, but I don't know enough F# specifically to say for sure. – Telastyn Aug 12 '15 at 01:44

1 Answers1

4

It sounds like you're missing the ability to be able to parse an expression using pattern matching. For example:

open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns

let x = <@@ fun y -> y + 100 @@>

let extractConstantValue = function 
    | Lambda(_, SpecificCall <@@ (+) @@> (_, _, _ :: Value(:? int as constant, _) :: _)) -> constant 
    | _ -> 0

printfn "Value of constant is %O" (extractConstantValue x)
// prints "Value of constant is 100"

This gives you all the power to interpret and process expressions, including those generated via the query computation expression (clauses in query blocks are auto-quoted, i.e. turned into expressions by the compiler). So bearing that in mind, most type providers, such as OdataService and SqlEntityConnection, are parsers and consumers of query expressions.

Also, providers like Websharper translate expressions into Javascript.

You can't, as you alluded to, compile or evaluate expressions without the Powerpack. Other than that, the possible uses for F# expressions are the same as for .NET expressions. In simple cases, you could use them to describe operations, or to parse a mathematical expression, or to translate simple F# code into some other syntax.

Tim
  • 1,427
  • 10
  • 11
  • Thanks! This answer helps fill in a lot of gaps. I thought it was also worth mentioning that a lot of canonical F# resources like to use reflection to get a MethodInfo object they can call Invoke() on too. – moarboilerplate Aug 12 '15 at 14:46