简体   繁体   English

在 F# 中,如何将 function 投射到不同的代表?

[英]In F#, How can I cast a function to a different delegate?

I need to cast a function with the signature Thing -> Thing -> int to a Comparison<Thing> .我需要将带有签名Thing -> Thing -> int的 function 转换为Comparison<Thing>

For example, when I have:例如,当我有:

Array.Sort(values, mySort)

I get an error stating " This expression was expected to have type Comparison but here has type Thing -> Thing -> int "我收到一条错误消息,指出“此表达式应具有比较类型,但此处的类型为 Thing -> Thing -> int

When I try this:当我尝试这个时:

Array.Sort(values, (fun (a, b) -> mySort a b))

(actually, this is by way of a wrapper object) (实际上,这是通过包装对象)

I get an error stating " Type constraint mismatch. The type ''a -> 'b' is not compatible with the type 'Comparison' "我收到一条错误消息,指出“类型约束不匹配。类型 ''a -> 'b' 与类型 'Comparison' 不兼容

How am I supposed to provide a Comparison<T> ?我应该如何提供Comparison<T>

FYI: Comparison<T> is a delegate with the signature 'T * 'T -> int仅供参考: Comparison<T>是具有签名'T * 'T -> int的委托

This works for me:这对我有用:

let values = [|1;2;3|]
let mySort a b = 0
Array.Sort(values, mySort)

But have you tried:但是你有没有试过:

Array.Sort(values, Comparison(mySort))

Oddly, despite the fact that delegate signatures are expressed in tupled form (eg 'T * 'T -> int ), you need to provide your function in curried form (eg fun ab -> mySort ab ).奇怪的是,尽管委托签名以元组形式表示(例如'T * 'T -> int ),但您需要以咖喱形式(例如fun ab -> mySort ab )提供您的 function 。 See section 6.4.2 of the spec.请参阅规范的第 6.4.2 节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在F#中使用返回不同类型的函数? - How can I have a function that returns different types in F#? 如何将F#委托传递给期望函数指针的P / Invoke方法? - How can I pass an F# delegate to a P/Invoke method expecting a function pointer? F# 中函数/委托的 ConstructorInfo - ConstructorInfo of a function/delegate in F# 如何在 F# 中创建 System.Buffers.SpanAction 类型的委托以在 String.Create 中使用? - How can I create a delegate in F# of the type System.Buffers.SpanAction for use in String.Create? 如何在定义的F#函数中交换应用程序的顺序? - How can I swap the order of application in a defined F# function? 如何使此F#函数不会导致堆栈溢出 - How can I make this F# function not cause a stack overflow 如何打破F#中的函数依赖关系? - How can I break a function dependency in F#? 如何在 F# 中创建递归异步 function? - how can I make a recursive async function in F#? 在F#中,如何判断对象是否为Async &lt;_&gt;,如何将其转换为Async &lt;_&gt;? - In F#, how do I tell if an object is an Async<_>, and how can I cast it to an Async<_>? 如何仅通过在F#中使用递归来编写此函数? - How can I write this function only by using recursion in F#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM