简体   繁体   中英

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

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

(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' "

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 (eg 'T * 'T -> int ), you need to provide your function in curried form (eg fun ab -> mySort ab ). See section 6.4.2 of the spec.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM