簡體   English   中英

Expr的F#匹配模式<int>

[英]F# match pattern for Expr<int>

我嘗試找到匹配的正確模式,並使用以下代碼運行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

找到了! 愚蠢的是我首先嘗試使用逗號分隔模式匹配數組模式(就像C#中的列表分隔符一樣),這顯然不適用於F#抱怨它不是列表而是tupple因此不是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())

奇跡般有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM