Alan Wayne
Alan Wayne

Reputation: 5384

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.

Upvotes: 2

Views: 293

Answers (2)

JL0PD
JL0PD

Reputation: 4488

Usage of Seq.cast have overhead of creating new enumerable, that wraps original, see source. Better to use casting

let movies : MovieInfo list = []
let moviesAsObj = movies :> seq<_> :?> seq<obj>
// and if it's inside `option`
let moviesOpt = Some movies
let moviesAsObjOpt = moviesOpt |> Option.map (fun m -> m :> seq<_> :?> obj)

Took idea from here

Upvotes: 2

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

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)

Upvotes: 3

Related Questions