F#中如何实现类似System.Linq.Enumerable.Cast的List.cast函数
F#中实现等价于LINQ Cast的List.cast函数踩坑记录
常规类型转换写法
将整型列表转换为IComparable类型列表时,开发者通常会编写如下代码完成转换:
[ 1; 2; 3 ] |> List.map (fun x -> x :> IComparable)
自定义List.cast函数的踩坑过程
System.Linq提供的Cast方法可对任意集合执行通用类型转换。尝试在F#中实现功能等价的List.cast<'newtype>函数时,实际遇到的问题复杂度远超预期,先后尝试的几种实现方式均出现编译报错:
- 第一种写法触发类型无法确定报错:
let listcast<'i> ls = ls |> List.map (fun x -> x :> 'i) // error indeterminate type
- 第二种写法触发函数无法实现泛型通用化报错:
let listcast<'t, 'i when 't :> 'i> (ls: 't list) = // error: could not be generalized ls |> List.map (fun x -> x :> 'i)
- 第三种写法触发类型无法确定报错:
let listcast<'i when 'i :> Object> (ls: Object list) = // error indeterminate type ls |> List.map (fun x -> x :> 'i)
可行实现方案
参考社区给出的实现思路,可得到如下可正常运行的实现代码:
module List = let cast<'t> = Seq.cast<'t> >> Seq.toList // 调用示例 [1..4] |> List.cast<IComparable>
内容的提问来源于stack exchange,提问作者citykid
相关产品推荐
相关产品推荐

