Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Seq functions on an IEnumerable [duplicate]

Tags:

I'm trying to apply Seq functions on an IEnumerable. More specifically, it's System.Windows.Forms.HtmlElementCollection which implements ICollection and IEnumerable.

Since an F# seq is an IEnumerable, I thought I could write

let foo = myHtmlElementCollection |> Seq.find (fun i -> i.Name = "foo")

but the compiler will have none of it, and complains that "The type 'HtmlElementCollection' is not compatible with the type 'seq<'a>'".

However, the compiler willingly accepts the IEnumerable in a for .. in .. sequence expression:

let foo = seq { for i in myHtmlElementCollection -> i } |> Seq.find (fun i -> i.Name = "foo")

What do I need to do in order for the IEnumerable to be treated just like any old F# seq?

NB: This question is marked as a duplicate, but it's not. The linked "duplicate" is about untyped sequences (a seq from the seq { for ... } expression), whereas my question is about typed sequences.

like image 624
John Reynolds Avatar asked Jan 30 '14 23:01

John Reynolds


1 Answers

F#'s type seq<'a> is equivalent to the generic IEnumerable<'a> in System.Collections.Generic, but not to the non-generic IEnumerable. You can use the Seq.cast<'a> function to convert from the non-generic one to the generic one:

let foo = myHtmlElementCollection
            |> Seq.cast<HtmlElement>
            |> Seq.find (fun i -> i.Name = "foo")
like image 114
GS - Apologise to Monica Avatar answered Oct 10 '22 21:10

GS - Apologise to Monica