Reputation: 11060
To convert a list of ints into a list of IComparables I write
[ 1; 2; 3 ] |> List.map (fun x -> x :> IComparable)
System.Linq offers the Cast method to cast a collection. Trying to implement a similar List.cast<'newtype> function in F# appears more tricky than I thought.
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)
Solution thx to the hint of pblasucci:
module List =
let cast<'t> = Seq.cast<'t> >> Seq.toList
[1..4] |> List.cast<IComparable>
Upvotes: 2
Views: 78
Reputation: 1778
Why not just use Seq.cast<_>
(either directly or as the basis for a List.cast<_>
function)?
Upvotes: 3