参见英文答案 >
How to constrain one type parameter by another 1个
我正在尝试在F#中实现“try cast”运算符.约束的子类型不起作用.
我正在尝试在F#中实现“try cast”运算符.约束的子类型不起作用.
举个例子,我想用C#做什么:
static A TryCast<TSuper,TSub,A>( Func<TSub,A> f,Func<TSuper,A> g,TSuper x) where TSub : TSuper => x is TSub sub ? f(sub) : g(x);
F#中的等价物应该是:
let tryCast<'super,'sub when 'sub :> 'super> (f : 'sub -> 'a) (g: 'super -> 'a) (x : 'super) : 'a = match x with | :? 'sub as sub -> f sub | x -> g x
要么
... if x :? 'sub then f (x :?> 'sub) else g x
但是,它给了我一个错误“’sub”在“when”子句中被限制为总是’super’.
这似乎表明F#不支持这一点.但我觉得奇怪的是我可以在C#中做到这一点.
所以问题是:这可以在F#中完成吗?
解决方法
感谢链接解释它确实是一个F#限制:
How to constrain one type parameter by another
How to constrain one type parameter by another
let tryCastWith (success : 'sub -> 'a) (fallback: 'super -> 'a) (x : 'super) : 'a = let o = Box x if o :? 'sub then success (o :?> 'sub) else fallback x
更具体地说,我实际想要的功能是这样的:
let tryCast (x : 'super) : Choice<'sub,'super> = tryCastWith Choice1Of2 Choice2Of2 x
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。