Expr< int>的F#匹配模式 [英] F# match pattern for Expr<int>
问题描述
我尝试使用以下代码找到匹配的正确模式并运行Expr<int>
:
I try to find the correct pattern to match and run an Expr<int>
using the below code:
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>
The runSelectQuery correctly matches the Expr<IQueryable<'T>>
pattern. However, I cannot find the correct pattern to match my generic count query Expr<int>
我从countQuery签名派生的代码中的模式给了我一个
The pattern in the code I derived from the signature of countQuery gives me a:
该表达式应具有类型 Expr,但是这里有类型 'a *'b
This expression was expected to have type Expr but here has type 'a * 'b
推荐答案
找到了!愚蠢的是,我首先尝试使用逗号分隔的模式来匹配数组模式(C#中的列表定界符),显然在F#中不起作用,抱怨它不是列表,而是tupple,因此不是Rex.
Found it! Stupidly I first tried to match the array pattern using a comma separated pattern (as is the list delimiter in C#), that obviously did not work in F# complaining the it was not a list but a tupple and thus not a Rex.
要再次匹配一个int结果或任何'T结果:
To match agains an int result or any 'T result:
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())
像魅力一样工作.
这篇关于Expr< int>的F#匹配模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!