Skip to content

Instantly share code, notes, and snippets.

uniform.mean() // Approximately 0.5
uniform.prob({ $0 > 0.7 }) // Approximately 0.3
dice.prob({ $0 == 7 }) // Approximately 1/6
let dice = die6.flatMap({
(d1: Int) in return die6.map({ (d2: Int) in return d1 + d2 })
})
dice.sample(10)
func nextInt(min min: Int, max: Int) -> ((Void) -> Int) {
assert(max > min)
return { () in return Int(arc4random_uniform(UInt32((max - min) + 1))) + min }
}
let die6 = Distribution<Int>(get: nextInt(min: 1, max: 6))
die6.sample(10)
let tf = uniform.map({ $0 < 0.7 })
tf.sample(10)
let bernoulli = tf.map({ $0 ? 1 : 0 })
bernoulli.sample(10)
func lessThan(p: Double) -> (Double -> Bool) {
return { x in return x < p }
}
func randomDouble() -> Double {
return Double(arc4random()) / Double(UInt32.max)
}
let uniform = Distribution<Double>(get: randomDouble)
uniform.sample(5)
struct Distribution<A> {
var get: () -> A?
func sample(n: Int) -> [A] {
return (1...n).map { x in get()! }
}
func map<B>(f: A -> B) -> Distribution<B> {
var d = Distribution<B>(get: {() -> Optional<B> in return nil})
d.get = {
struct UniformDoubleDist: Stochastic {
// Returns a uniform double on [0,1]
func get() -> Double {
return drand48()
}
func sample(n: Int) -> [Double] {
return (1...n).map { x in get() }
}
}
protocol Parameterized {
associatedtype ParameterType
var p: ParameterType { get }
}
protocol Stochastic {
// the type of value stored in the distribution
associatedtype ValueType
// Sample a single value from the distribution
func get() -> ValueType
// Sample n values from the distribution
func sample(n: Int) -> [ValueType]
}