[英]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.