在F#中用Lambda表达式创建代表 [英] Creating Delegates With Lambda Expressions in F#

查看:127
本文介绍了在F#中用Lambda表达式创建代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么...

type IntDelegate = delegate of int -> unit

type ListHelper =
    static member ApplyDelegate (l : int list) (d : IntDelegate) =
        l |> List.iter (fun x -> d.Invoke x)

ListHelper.ApplyDelegate [1..10] (fun x -> printfn "%d" x)

不能编译,当时:

type IntDelegate = delegate of int -> unit

type ListHelper =
    static member ApplyDelegate (l : int list, d : IntDelegate) =
        l |> List.iter (fun x -> d.Invoke x)

ListHelper.ApplyDelegate ([1..10], (fun x -> printfn "%d" x))

是吗?

唯一的区别是第二个 ApplyDelegate 将其参数作为元组。

The only difference that is that in the second one, ApplyDelegate takes its parameters as a tuple.


此函数需要太多的参数,或者在一个不需要函数的上下文中使用

This function takes too many arguments, or is used in a context where a function is not expected


推荐答案

没有看到规范确认,但我猜测从lambda到命名委托类型的隐式转换只发生在成员调用中。

I haven't looked at the spec to confirm, but I am guessing that the implicit conversion from "lambda" to "named delegate type" only occurs in a "member invocations".

您可以随时使转换显式:

You can always make the conversion explicit:

ListHelper.ApplyDelegate [1..10] (IntDelegate(fun x -> printfn "%d" x))

(错误诊断相当差;我将文件一个错误。)

(The error diagnostic is quite poor; I'll file a bug.)

编辑:

对于赢家...

是的, spec


8.13.6成员调用中的类型导向转换如
中所述方法应用程序解析(参见
§14.4)中,两个类型导向转换
在方法调用中应用。

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

如果一个正式参数是委托
,则键入DelegateType,实际的
参数在语法上是函数
value(fun ...),那么参数是
解释,就好像已经写了
new DelegateType(fun ...)。

If a formal parameter is of delegate type DelegateType, and an actual argument is syntactically a function value (fun ...), then the parameter is interpreted as if it had been written new DelegateType(fun ...).

lambdas自动转换为仅在成员调用中委派类型。在curried成员的情况下,传递的第一个参数是成员调用,然后返回一个函数值来应用第二个参数,函数调用不具有这个隐式转换规则。

that lambdas get converted automagically to delegate types only at "member invocations". In the case of the curried member, the first argument passed is a member invocation, but then that returns a function value to apply the second argument, and function invocations do not have this implicit conversion rule.

这篇关于在F#中用Lambda表达式创建代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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