Oldrich Svec
Oldrich Svec

Reputation: 4231

HashSet `.ToArray()` using F#

What do I need to do to be able to call .ToArray () for a HashSet? I have tried the following but it did not work:

let a = System.Collections.Generic.HashSet ()
a.Add 5 |> ignore
a.ToArray () // Not possible
let b = a :> System.Collections.IEnumerable
b.ToArray () // Not possible

Here, this is stated:

ToArray : Creates an array from a IEnumerable. (Defined by Enumerable.)

so there should be a way.

Upvotes: 1

Views: 756

Answers (3)

Tomas Petricek
Tomas Petricek

Reputation: 243041

The HashSet type implements standard generic IEnumerable<'T> type (called seq<'T> in F#), so you can use Seq.toArray (without opening any namespaces):

let hs = System.Collections.Generic.HashSet()
hs.Add(1)

let ar = hs |> Seq.toArray

Using C# extension method ToArray will work too (if you open System.Linq), but I believe that using standard F# functions is more idiomatic.

Upvotes: 3

cfern
cfern

Reputation: 6006

IEnumerable.ToArray() is defined as an extension method under System.Linq. Alternatively, use Seq.toArray or Array.ofSeq.

open System.Collections.Generic
open System.Linq

let hs = HashSet()
hs.Add 4
hs.Add 2

let arr = hs.ToArray()       // needs System.Linq
let arr2 = hs |> Seq.toArray // provided by F#

Upvotes: 6

Brian
Brian

Reputation: 118865

I believe it's an extension method, so you need to open the namespace containing Enumerable (Linq?) to get it, just as in C#.

Upvotes: 0

Related Questions