1

我尝试找到正确的模式来匹配并Expr<int>使用以下代码运行:

open System.Linq

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

let runSelectQuery (q:Expr<IQueryable<'T>>) = 
    match q with
    | Application(Lambda(builder, Call(Some builder2, miRun, [Quote body])), queryObj) ->
        query.Run(Expr.Cast<Microsoft.FSharp.Linq.QuerySource<'T, IQueryable>>(body))
    | _ -> failwith "Cannot run this query %s" (q.ToString())

let runCountQuery (q:Expr<int>) = 
    match q with
    | Application(Lambda(builder, Call(None, miRun, [builder2, Quote body])), queryObj) ->
        query.Run(Expr.Cast<int>(body))
    | _ -> failwith "Cannot run this query %s" (q.ToString())

let countQuery source filter =
    let filter = match filter with | Some filter -> filter | _ -> <@ fun _ -> true @>
    <@ query { for item in source do
               where ((%filter) item)
               count } @>

runSelectQuery 与Expr<IQueryable<'T>>模式正确匹配。但是,我找不到与我的通用计数查询匹配的正确模式Expr<int>

我从 countQuery 的签名派生的代码中的模式给了我一个:

此表达式应为 Expr 类型,但这里的类型为 'a * 'b

4

1 回答 1

3

找到了!愚蠢的是,我首先尝试使用逗号分隔模式匹配数组模式(就像 C# 中的列表分隔符一样),这显然在 F# 中不起作用,抱怨它不是列表而是元组,因此不是 Rex。

要再次匹配 int 结果或任何 'T 结果:

let runQueryToQueryable (q:Expr<IQueryable<'T>>) = 
    match q with
    | Application(Lambda(builder, Call(Some builder2, miRun, [Quote body])), queryObj) ->
        query.Run(Expr.Cast<Microsoft.FSharp.Linq.QuerySource<'T, IQueryable>>(body))
    | _ -> failwith "Cannot run this query %s" (q.ToString())

let runQueryToType (q:Expr<'T>) = 
    match q with
    | Application(Lambda(builder, Call(None, miRun, [builder2; Quote body])), queryObj) ->
           query.Run(Expr.Cast<'T>(body))
    | _ -> failwith "Cannot run this query %s" (q.ToString())

奇迹般有效。

于 2013-06-17T21:50:52.637 回答