gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:58:31 25 4
gpt4 key购买 nike

为什么...

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com