Skip to content

Instantly share code, notes, and snippets.

@zeux
Created April 22, 2012 22:34
Show Gist options
  • Save zeux/2467344 to your computer and use it in GitHub Desktop.
Save zeux/2467344 to your computer and use it in GitHub Desktop.
F# generic enumeration helper
// helpers to iterate IDiaEnum* objects
let inline toSeq (o: ^T) =
let e = { new IEnumerable with member this.GetEnumerator () = (^T: (member GetEnumerator: unit -> _) (o)) }
if true then
Seq.cast e
else
// Dummy expression to constrain return type to that of o.Item
seq [| (^T: (member Item: _ -> _) (o, Unchecked.defaultof<_>)) |]
@gusty
Copy link

gusty commented Nov 2, 2016

In FsControl there is a more generic version, which use a default-case which is equivalent to your code. If you extract that overload to a single function you get this:

open System
let inline toSeq (x:'S when 'S :> Collections.IEnumerable) = 
    let f i x :'T = ( ^S : (member get_Item : int -> 'T) x, i) // this is a dummy function
    Seq.cast<'T> x : seq<'T>

Although it's better to use the even more generic toSeq function defined there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment