# Documentation

PnP2023.Lec_03_24.Sampling

# Random sampling for an element #

We implement sampling to find an element with a given property, for instance being prime or being coprime to a given number. For this we need a hypothesis that such an element exists.

We use the IO monad to generate random numbers. This is because a random number is not a function, in the sense of having value determined by arguments.

The basic way we sample is to choose an element at random from the list, and then check if it satisfies the property. If it does, we return it. If not, we remove it from the list and try again. To show termination we see (following a lab) that the length of the list decreases by at least one each time.

theorem remove_length_le {α : Type u} [] (a : α) (l : List α) :

Removing an element from a list does not increase length

theorem remove_mem_length {α : Type u} [] {a : α} {l : List α} (hyp : a l) :

Removing a member from a list shortens the list

We pick an index of the list l, which is of type Fin l.length. Rather than proving that the random number generator has this property we pass mod n.

def IO.randFin (n : ) (h : 0 < n) :
IO (Fin n)

A random number in Fin n

Instances For
def pickElemIO {α : Type} [] (l : List α) (p : αBool) (h : t, t l p t = true) :
IO { t // t l p t = true }

A random element with a given property from a list, within IO

Equations
• One or more equations did not get rendered due to their size.
Instances For
def pickElemD {α : Type} [] (l : List α) (p : αBool) (default : α) (h₁ : default l) (h₂ : p default = true) :
{ t // t l p t = true }

A random element with a given property from a list. As IO may in principle give an error, we specify a default to fallback and the conditions that this is in the list and has the property p

Instances For

We used the IO Monad which has a lot of stuff besides randomness. We will now demistify this by constructing a Monad for randomness only.

def RandomM (α : Type u_1) :
Type u_1
Instances For
def RandomM.rand (lo : ) (hi : ) :
Instances For
def RandomM.run {α : Type u_1} (x : ) :
StdGen
Instances For
def RandomM.run' {α : Type u_1} (x : ) (gen : optParam StdGen default) :
α
Instances For
Instances For
def RandomM.randList (lo : ) (hi : ) (n : ) :
Equations
Instances For
def RandomM.setSeed (n : ) :
Instances For
def RandomM.withSeed {α : Type} (n : ) (c : ) :
Instances For
def StateM' (σ : Type u_1) (α : Type u_2) :
Type (max u_1 u_2)
Instances For
instance instMonadStateM' {σ : Type u_1} :
def StateM'.run {σ : Type u_1} {α : Type u_2} (x : StateM' σ α) :
σα × σ
Instances For
def StateM'.run' {σ : Type u_1} {α : Type u_2} [] (x : StateM' σ α) (s : optParam σ default) :
α
Instances For
def StateM'.setState {σ : Type u_1} (s : σ) :
Instances For
def StateM'.getState {σ : Type u_1} :
StateM' σ σ
Instances For
def StateM'.withState {σ : Type u_1} {α : Type} (s : σ) (c : StateM' σ α) :
StateM' σ α
Instances For
def RandomM' (α : Type u_1) :
Type u_1
Instances For