Skip to content

Commit 6fcd9b0

Browse files
committed
chore(Control/Random): Use NeZero instead of returning Fin n.succ (#22672)
Changes the random generation of `Fin`s to take `NeZero n` instead of giving a `Fin n.succ`.
1 parent 708ea06 commit 6fcd9b0

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

Mathlib/Control/Random.lean

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,10 @@ def randBound (α : Type u)
9595
(BoundedRandom.randomR lo hi h : RandGT g _ _)
9696

9797
/-- Generate a random `Fin`. -/
98-
def randFin {n : Nat} [RandomGen g] : RandGT g m (Fin n.succ) :=
99-
fun ⟨g⟩ ↦ pure <| randNat g 0 n |>.map (Fin.ofNat' _) ULift.up
98+
def randFin {n : Nat} [NeZero n] [RandomGen g] : RandGT g m (Fin n) :=
99+
fun ⟨g⟩ ↦ pure <| randNat g 0 (n - 1) |>.map (Fin.ofNat' n) ULift.up
100100

101-
instance {n : Nat} : Random m (Fin n.succ) where
101+
instance {n : Nat} [NeZero n] : Random m (Fin n) where
102102
random := randFin
103103

104104
/-- Generate a random `Bool`. -/
@@ -113,10 +113,10 @@ instance {α : Type u} [ULiftable m m'] [Random m α] : Random m' (ULift.{v} α)
113113

114114
instance : BoundedRandom m Nat where
115115
randomR lo hi h _ := do
116-
let z ← rand (Fin (hi - lo).succ)
116+
let z ← rand (Fin (hi - lo + 1))
117117
pure ⟨
118118
lo + z.val, Nat.le_add_right _ _,
119-
Nat.add_le_of_le_sub' h (Nat.le_of_succ_le_succ z.isLt)
119+
Nat.add_le_of_le_sub' h (Nat.le_of_lt_add_one z.isLt)
120120
121121

122122
instance : BoundedRandom m Int where

MathlibTest/random.lean

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ info: GOOD
8989
IO.runRandWith 257 <| do
9090
let mut count := 0
9191
for _ in [:10000] do
92-
if (← randFin (n := 2)) == 1 then count := count + 1
92+
if (← randFin : Fin 3) == 1 then count := count + 1
9393
if Float.abs (0.333 - (count / Nat.toFloat 10000)) < 0.01 then
9494
IO.println "GOOD"
9595
else
@@ -103,7 +103,7 @@ info: GOOD
103103
IO.runRandWith 257 <| do
104104
let mut count := 0
105105
for _ in [:10000] do
106-
if (← randFin (n := 1)) == 0 then count := count + 1
106+
if (← randFin : Fin 2) == 0 then count := count + 1
107107
if Float.abs (0.5 - (count / Nat.toFloat 10000)) < 0.01 then
108108
IO.println "GOOD"
109109
else
@@ -117,7 +117,7 @@ info: GOOD
117117
IO.runRandWith 257 <| do
118118
let mut count := 0
119119
for _ in [:10000] do
120-
if (← randFin (n := 9)) == 5 then count := count + 1
120+
if (← randFin : Fin 10) == 5 then count := count + 1
121121
if Float.abs (0.1 - (count / Nat.toFloat 10000)) < 0.01 then
122122
IO.println "GOOD"
123123
else

0 commit comments

Comments
 (0)