表达式< Func> T,bool>从F#函数 [英] Expression<Func<T, bool>> from a F# func

查看:55
本文介绍了表达式< Func> T,bool>从F#函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在linq中.其中有一个Expression>谓词,我可以在F#中写为

in linq, .Where takes a Expression> predicate, which I can write in F# as

<@ fun item:'a -> condition @>    // Expr<'a -> bool>

我正在使用FSharp.Powerpack从引号中构建表达式,但是它给我的是MethodCallExpression.深入研究一下,powerpack代码正确地构建了lambda,但是将其包装在Convert调用中(为什么?).我想知道是否将参数强制转换为方法调用(lambda)最终会给我我需要的Expression>.

I'm using FSharp.Powerpack to build the expression from a quotation, but what it gives me is a MethodCallExpression. Looking deep, the powerpack code builds the lambda correctly, but wraps it in a Convert call (why is that?). I wonder if casting the argument to the method call (a lambda) would finally give me the Expression> I need.

所以问题是为什么进行Convert调用,以及如何实际获得带有Func签名的lambda.

So the question is why the Convert call, and how to actually get the lambda with the Func signature.

推荐答案

我不记得我在哪里找到了这段代码,但这就是将Expr<'a -> 'b>转换为Expression<Func<'a, 'b>>.希望这能解决您的问题.

I can't remember off the top of my head where I found this bit of code, but this is what I use to convert an Expr<'a -> 'b> to Expression<Func<'a, 'b>>. Hopefully this will solve your problem.

open System
open System.Linq.Expressions
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation

let toLinq (expr : Expr<'a -> 'b>) =
  let linq = expr.ToLinqExpression()
  let call = linq :?> MethodCallExpression
  let lambda = call.Arguments.[0] :?> LambdaExpression
  Expression.Lambda<Func<'a, 'b>>(lambda.Body, lambda.Parameters) 

这篇关于表达式&lt; Func&gt; T,bool&gt;从F#函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆