开发者

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

开发者 https://www.devze.com 2023-03-18 22:09 出处:网络
I need to cast a function with the signature Thing -> Thing -> int to a Comparison<Thing>.

I need to cast a function with the signature Thing -> Thing -> int to a 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"

When I try this:

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

(actu开发者_运维问答ally, 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'"

How am I supposed to provide a Comparison<T>?

FYI: Comparison<T> is a delegate with the signature '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 (e.g. 'T * 'T -> int), you need to provide your function in curried form (e.g. fun a b -> mySort a b). See section 6.4.2 of the spec.

0

精彩评论

暂无评论...
验证码 换一张
取 消