Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Quoted Expression in F#

Tags:

f#

quotations

I hope I haven't missed something obvious, but I've been playing with F# expressions and I want to evaluate quoted expressions on the fly. For example, I want write something like this:

let x = <@ 2 * 5 @>
let y = transform x // replaces op_Multiply with op_Addition, or <@ 2 + 5 @>
let z = eval y // dynamically evaluates y, returns 7

Is there a built-in F# method which can evaluate quoted expressions, or do I have to write my own?

like image 735
Juliet Avatar asked May 11 '09 18:05

Juliet


1 Answers

I've implemented a reflection-based Quotation evaluator as part of Unquote (this is a new feature as of version 2.0.0).

> #r @"..\packages\Unquote.2.2.2\lib\net40\Unquote.dll"

--> Referenced '..\packages\Unquote.2.2.2\lib\net40\Unquote.dll'

> Swensen.Unquote.Operators.eval <@ sprintf "%A" (1,2) @>;;
val it : string = "(1, 2)"

I've measured it to be up to 50 times faster than PowerPack's evaluator. This will, of course, vary by scenario. But Unquote is generally magnitudes faster than PowerPack at interpreting expressions.

It also supports many more expressions than PowerPack's evaluator, including VarSet, PropertySet, FieldSet, WhileLoop, ForIntegerRangeLoop, and Quote. In fact, Unquote's evaluator supports all quotation expressions except NewDelegate, AddressSet, and AddressOf all of which I plan on eventually supporting.

like image 93
Stephen Swensen Avatar answered Sep 22 '22 06:09

Stephen Swensen