Search code examples
listf#ienumerableupcasting

In F#, what is the simplest method of upcasting a typed list to a seq<_>?


(Newbie question) In F#, what is the simplest method of upcasting a typed list to a seq<_> ?

I am working on interop with C# and trying to learn F#. I have specifically a list of movies defined as:

Movies: MovieInfo list option

which I would like to upcast to

 ItemsSource: seq<obj> option

So given Movies, how do I go to ItemsSource?

e.g., movies |> ?????

Thank you for any help.


Solution

  • There are actually two small tasks here: (1) convert the list to a sequence, which is what you asked about, and (2) do it "inside" the option.

    Converting a list to sequence is easy: Seq.ofList. Plus, if you need to cast the element type, use Seq.cast:

    let movies: MovieInfo list = ...
    let itemsSource = movies |> Seq.ofList |> Seq.cast
    

    But that's not all: you don't have a naked list MovieInfo list, you have it inside an option - MovieInfo list option. And a way to apply a transformation to a value inside of an option is via Option.map:

    let x = Some 3
    let y = x |> Option.map ((+) 2)  // now, y = Some 5
    

    So to combine all of the above:

    let ItemsSource = Movies |> Option.map (Seq.ofList >> Seq.cast)