.net - 在 F# 中使用 Lambda 表达式创建委托(delegate)

标签 .net f# functional-programming delegates

为什么...

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将其参数作为一个元组。

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

最佳答案

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

您始终可以使转换显式:

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

(错误诊断很差;我会提交一个错误。)

编辑:

对于笨蛋...

是的,spec

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.

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



lambda 仅在“成员调用”时自动转换为委托(delegate)类型。在 curried 成员的情况下,传递的第一个参数是成员调用,但随后返回一个函数值以应用第二个参数,并且函数调用没有此隐式转换规则。

关于.net - 在 F# 中使用 Lambda 表达式创建委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2783450/

相关文章:

python - python 闭包什么时候进行捕获?

ios - swift 函数式计算

c# - 从 C# 中的参数化构造函数调用无参数构造函数?

c# - 固定大小的字节数组

.NET 日期比较 : Count the amount of working days since a date?

c# - 为什么我无法访问 T4 模板中类成员中的实用方法?

c# - .NET 运行时尝试加载 FSharp.Core 4.3.0,即使所有项目都引用 4.3.1

functional-programming - 在 Agda 中编写证明

f# - 如何等待异步完成

list - 如何更改 F# 中特定索引处列表中的项目? (属性 'Item'无法设置)