F#比较vs C#IComparable [英] F# comparison vs C# IComparable
问题描述
我的问题,简而言之,是这样的:
我可以做什么关于存储一个元组)
这可以工作:
> let x(y:'a when'a:comparison)= y ;;
val x:y:'a - > 'a when'a:comparison
> x(1,2);;
val it:int * int =(1,2)
将工作:
> let x(y:IComparable< int>)= y ;;
val x:y:IComparable< int> - > IComparable< int>
> x(1,2);;
x(1,2);;
--- ^^^
stdin(28,4):error FS0001:类型a *'b'与类型'IComparable< int>'不兼容
还有:
> let x(y:IComparable)= y ;;
val x:y:IComparable - > IComparable
> x(1,2);;
x(1,2);;
--- ^^^
stdin(30,4):error FS0001:类型a *'b'与类型'IComparable'不兼容
EDIT
F#不做隐式向上转换的论点。但是,即使明确:
> (1,2):> IComparable ;;
(1,2):> IComparable ;;
^^^^^^^^^^^^^^^^^^^
stdin(43,1):error FS0193:类型约束不匹配。类型
int * int
与类型
不兼容IComparable
类型int * int与类型IComparable不兼容
我认为这是有道理的,因为F#元组的可比性在F#类型系统中是结构推断的,也许额外的信息不是
下面的每个注释似乎一个解决方法是调用
Tuple< _,_> (1,2)。
或甚至
code> box(1,2):?> IComparable ;;
解决方案FWIW,如果你构造一个
System.Tuple< _,_>
显然,这可能是一个解决方法:let x(y:IComparable)= y
let t =(2,3)
x(Tuple< _,_&
My problem, in a nutshell, is this:
What can I do about storing a tuple (or any type with a constraint of 'comparison') in a C# container that requires an IComparable?
This works:
> let x (y : 'a when 'a : comparison) = y ;; val x : y:'a -> 'a when 'a : comparison > x (1,2) ;; val it : int * int = (1, 2)
I would have thought this would work:
> let x (y : IComparable<int>) = y ;; val x : y:IComparable<int> -> IComparable<int> > x (1,2) ;; x (1,2) ;; ---^^^ stdin(28,4): error FS0001: The type ''a * 'b' is not compatible with the type 'IComparable<int>'
And this as well:
> let x (y : IComparable) = y ;; val x : y:IComparable -> IComparable > x (1,2) ;; x (1,2) ;; ---^^^ stdin(30,4): error FS0001: The type ''a * 'b' is not compatible with the type 'IComparable'
EDIT
I follow the argument that F# doesn't do implicit upcasting. However, even explicitly:
> (1, 2) :> IComparable ;; (1, 2) :> IComparable ;; ^^^^^^^^^^^^^^^^^^^^^ stdin(43,1): error FS0193: Type constraint mismatch. The type int * int is not compatible with type IComparable The type 'int * int' is not compatible with the type 'IComparable'
I suppose this makes sense as the comparability of a F# tuple is inferred structurally within the F# type system, and perhaps that extra information is not available to .NET.
It seems one workaround per a comment below is invoking
Tuple<_,_> (1,2) ;;
Or even
box (1, 2) :?> IComparable ;;
解决方案Definitely some weirdness going on. FWIW, it works if you construct a
System.Tuple<_, _>
explicitly, so that might be a workaround:let x (y : IComparable) = y let t = (2, 3) x (Tuple<_,_> t)
这篇关于F#比较vs C#IComparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!