Set of N length generator in FSCheck

124 views Asked by At

I'm still learning FSCheck, and recently needed a fixed collection of unique strings.

This works, but I suspect there is a more efficient way.

Arb.generate<Set<NonEmptyString>> 
|> Gen.filter (fun s -> Set.count s > 9)
|> Gen.map (Seq.truncate 10) 

Is there?

1

There are 1 answers

4
Brian Berns On BEST ANSWER

It's probably more efficient to build a set that you know contains exactly N strings, like this:

let genSet genItem size =
    let rec loop (items : Set<_>) =
        gen {
            if items.Count >= size then
                return items
            else
                let! item = genItem
                return! items.Add(item) |> loop
        }
    loop Set.empty

let genSetOfNonEmptyStringsOfSize10 =
    genSet
        Arb.generate<NonEmptyString>
        10

Note that genSet will build a set of any type, not just NonEmptyStrings.

Related Questions in F#