1

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)

Goswin Rothenthal
  • 2,244
  • 1
  • 19
  • 32

1 Answers1

2

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.

Zazaeil
  • 3,900
  • 2
  • 14
  • 31