Skip to content

Instantly share code, notes, and snippets.

@mrange
Last active August 29, 2015 14:07
Show Gist options
  • Save mrange/9b56a7c16f1370f8a874 to your computer and use it in GitHub Desktop.
Save mrange/9b56a7c16f1370f8a874 to your computer and use it in GitHub Desktop.
LinqOtimizer question.
// The problem with Run is that the expression is begin rebuilt and then compiled everytime, potentially too expensive
let Run : int -> int = fun y -> Query.range(0,1000)
|> Query.filter(fun x -> x > y)
|> Query.sum
|> Query.run
// The problem with BuildFunc is that it doesn't compile :)
let BuildFunc : int -> int = Query.range(0,1000)
|> Query.filter(fun x -> x > VAR) // VAR should be the input parameter to the compiled func
|> Query.sum
|> Query.compile
@palladin
Copy link

palladin commented Oct 1, 2014

Check this https://github.com/nessos/LinqOptimizer/blob/master/src/LinqOptimizer.FSharp/FSharpQuery.fs
file for compile method overloads.
For your scenario, I think you need to call
Query.compile(fun y -> Query.range(0,1000)
|> Query.filter(fun x -> x > y)
|> Query.sum )

@krontogiannis
Copy link

palladin's snippet should theoretically work except it will not. The problem is the way that the F# compiler produces expressions trees (seems like a conversion from Quotations to Expression) and especially nested expressions. Of course in C# this overload of compile will work fine. Consider the following snippet.

open System
open System.Linq.Expressions

type Expression =
    static member OfLambda<'I,'O> (x : Expression<Func<'I,'O>>) = x

// works fine
// x => x
let e1 = Expression.OfLambda<int,_>(fun x -> x)

// inner expression is messed up
// i => OfLambda(
//    QuotationToLambdaExpression(
//        SubstHelper(NewDelegate (Func`2, j, Call (None, op_Addition, [i, j])), new [] {i}, new [] {Convert(i)})))
let e2 = Expression.OfLambda(fun i -> 
            Expression.OfLambda(fun j -> i + j))

The second expression corresponds to palladin's Query.compile(.... Query.filter(...lambda...)....).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment