Skip to content

Commit

Permalink
replaced Random.replicate with ListRandom traverse and sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
TysonMN committed Feb 8, 2021
1 parent 0efe16e commit d95c9ae
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 13 deletions.
8 changes: 6 additions & 2 deletions src/Hedgehog/Gen.fs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,10 @@ module Gen =
let list (range : Range<int>) (g : Gen<'a>) : Gen<List<'a>> =
Random.sized (fun size -> random {
let! k = Random.integral range
let! xs = Random.replicate k (toRandom g)
let! xs =
toRandom g
|> List.replicate k
|> ListRandom.sequence
return Shrink.sequenceList xs
|> Tree.filter (atLeast (Range.lowerBound size range))
})
Expand Down Expand Up @@ -488,7 +491,8 @@ module Gen =
let sampleTree (size : Size) (count : int) (g : Gen<'a>) : List<Tree<'a>> =
let seed = Seed.random ()
toRandom g
|> Random.replicate count
|> List.replicate count
|> ListRandom.sequence
|> Random.run seed size

let sample (size : Size) (count : int) (g : Gen<'a>) : List<'a> =
Expand Down
1 change: 1 addition & 0 deletions src/Hedgehog/Hedgehog.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ https://github.com/hedgehogqa/fsharp-hedgehog/blob/master/doc/index.md
<Compile Include="OptionTree.fs" />
<Compile Include="Range.fs" />
<Compile Include="Random.fs" />
<Compile Include="ListRandom.fs" />
<Compile Include="Shrink.fs" />
<Compile Include="Gen.fs" />
<Compile Include="ListGen.fs" />
Expand Down
16 changes: 16 additions & 0 deletions src/Hedgehog/ListRandom.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[<RequireQualifiedAccess>]
module Hedgehog.ListRandom

let traverse (f: 'a -> Random<'b>) (list: List<'a>) : Random<List<'b>> =
let rec loop input output =
match input with
| [] -> output |> List.rev |> Random.constant
| a :: input ->
random {
let! b = f a
return! loop input (b :: output)
}
loop list []

let sequence (randoms : List<Random<'a>>) : Random<List<'a>> =
randoms |> traverse id
11 changes: 0 additions & 11 deletions src/Hedgehog/Random.fs
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,6 @@ module Random =
let bind (f: 'a -> Random<'b>) (r: Random<'a>) : Random<'b> =
r |> map f |> join

let replicate (times: int) (r: Random<'a>) : Random<List<'a>> =
Random (fun seed0 size ->
let rec loop seed k acc =
if k <= 0 then
acc
else
let seed1, seed2 = Seed.split seed
let x = unsafeRun seed1 size r
loop seed2 (k - 1) (x :: acc)
loop seed0 times [])

type Builder internal () =
member __.Return(x : 'a) : Random<'a> =
constant x
Expand Down

0 comments on commit d95c9ae

Please sign in to comment.