Conversion of lambda expressions to Func

一曲冷凌霜 提交于 2019-12-01 08:38:57

问题


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. :-)


回答1:


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.



来源:https://stackoverflow.com/questions/23234047/conversion-of-lambda-expressions-to-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!