Question

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.

Was it helpful?

Solution

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")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top