Skip to content

Instantly share code, notes, and snippets.

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 = {
func randomDouble() -> Double {
return Double(arc4random()) / Double(UInt32.max)
}
let uniform = Distribution<Double>(get: randomDouble)
uniform.sample(5)
func lessThan(p: Double) -> (Double -> Bool) {
return { x in return x < p }
}
let tf = uniform.map({ $0 < 0.7 })
tf.sample(10)
let bernoulli = tf.map({ $0 ? 1 : 0 })
bernoulli.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 dice = die6.flatMap({
(d1: Int) in return die6.map({ (d2: Int) in return d1 + d2 })
})
dice.sample(10)
uniform.mean() // Approximately 0.5
uniform.prob({ $0 > 0.7 }) // Approximately 0.3
dice.prob({ $0 == 7 }) // Approximately 1/6
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 = {
func flatMap<B>(f: A -> Distribution<B>) -> Distribution<B> {
var d = Distribution<B>(get: {() -> Optional<B> in return nil})
d.get = {
(Void) -> B in return f(self.get()!).get()!
}
return d
}
@klgraham
klgraham / Activation.swift
Last active April 3, 2016 17:35
Sign step and activation functions
func activate(bias: Double, bW: Double, x: [Double], w: [Double]) -> Int {
var sum = 0.0
for i in 0..<x.count {
sum += x[i] * w[i]
}
sum += bias * bW
return step(sum)
}