Reputation: 2344
Given
type X () = class end
type XX () = inherit X()
type NestedList<'T> = list<list<'T>>
let xxs = [[ XX() ]] // list<list<XX>>
What is the best way to cast from list<list<XX>>
to NestedList<X>
?
This fails:
let xs = xxs :> NestedList<X> //fails
This works but reallocates the list. Is there a more elegant way doing this without reallocation?
let xs : NestedList<X> = [ for xx in xxs do yield List.ofSeq (Seq.cast<X> xx) ]
How could I define a cast
function on NestedList<'T>
? (like Seq.cast
)
Upvotes: 1
Views: 83
Reputation: 4119
let cast xxs = xxs |> List.map (List.map (fun e -> e :> X))
would do the job.
More fancy way:
let mapNested f = (List.map >> List.map) f
let cast xxs = mapNested (fun e -> e :> X) xxs
P.S. I strongly recommend avoid unnecessary abstractions like NestedList<'T>
from your example.
Upvotes: 2