将lambda表达式转换为Func [英] Conversion of lambda expressions to Func

查看:170
本文介绍了将lambda表达式转换为Func的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下内容:

 打开System.Linq 

let seqA = {1 .. 10}

这样做:

  seqA.All(fun n  - > n> 0)

然而这并不是:

  let abc = fun n  - > n> 0 

seqA.All(abc)

为什么F#提供隐式转换从lambda表达式到 Func s但不是来自函数?指向我可以阅读这里发生的事情的文档是值得欢迎的。 : - )

/research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335819028rel =nofollow>方法解决方案,同样在成员调用中的类型定向转换。引用后者:
$ b


方法应用程序解析中所述(请参阅第14.4节),两个
类型定向转换应用于方法调用。



第一种类型定向转换将匿名函数
表达式和其他函数值参数转换为委托类型。
鉴于:


  • 委托类型的正式参数 D

  • 已知类型 ty 1 - > ...> - > ty n - > rty 的实际参数 farg em>

  • 精确 n 参数给委托类型的调用方法 D >



然后:


  • 被解释为如下:

    new D fun arg 1 ... arg n - > farg arg 1 ... arg n


似乎表明这种转换适用于任何函数值,但观察表明它仅适用于匿名函数。


Given the following:

open System.Linq

let seqA = { 1..10 }

this works:

seqA.All (fun n -> n > 0)

However this doesn't:

let abc = fun n -> n > 0

seqA.All (abc)

Why does F# offer implicit conversion from lambda expressions to Funcs but not from functions? Pointers to the documentation where I can read up on what's going on here are welcome. :-)

解决方案

This is covered in the (rather involved) section of the spec on Method Resolution and again in Type-directed Conversions at Member Invocations. Quoting from the latter:

As described in Method Application Resolution (see §14.4), two type-directed conversions are applied at method invocations.

The first type-directed conversion converts anonymous function expressions and other function-valued arguments to delegate types. Given:

  • A formal parameter of delegate type D
  • An actual argument farg of known type ty1 -> ... -> tyn -> rty
  • Precisely n arguments to the Invoke method of delegate type D

Then:

  • The parameter is interpreted as if it were written:
    new D(fun arg1 ... argn -> farg arg1 ... argn)

It seems to suggest this conversion would be applied to any function value, but observation suggests it's applied only to anonymous functions.

这篇关于将lambda表达式转换为Func的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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