Skip to content

Instantly share code, notes, and snippets.

@klgraham
klgraham / tail-recursive factorial
Created September 9, 2016 08:36
Tail-recursive factorial in Scala
def factorial(n: BigInt): BigInt = {
def fact(n: BigInt, result: BigInt): BigInt = {
if (n == 0) return result
else return fact(n - 1, result * n)
}
return fact(n, 1)
}
@klgraham
klgraham / Scala Loop-Recur for zipper
Created September 9, 2016 08:27
Example of tail-recursion in Scala that will not throw a StackOverflowError.
// Scala analog to Clojure's loop-recur construct
def loopRecur[A](index: Int, coll: Seq[A], zippedList: List[(Int, A)]): List[(Int, A)] = {
if (coll.isEmpty) return zippedList
else return loopRecur(index + 1, coll.tail, zippedList ++ List((index, coll.head)))
}
// Given a sequecne of items, returns a List of tuples of the form (item index, item)
def zipIndex[A](coll: Seq[A]): List[(Int, A)] = {
return loopRecur(0, coll, List.empty[(Int, A)])
}
@klgraham
klgraham / StringReversal.java
Created August 6, 2016 02:16
Recursive string reversal
package org.klgraham;
/**
* Created by klogram on 8/5/16.
*/
public class StringReversal {
public static String reverseStringIterative(final String s) {
StringBuilder sb = new StringBuilder();
func sign(z: Double) -> Int {
// Note that 0 is not considered positive or negative
return (z > 0) ? 1 : -1
}
func randomDouble() -> Double {
return Double(arc4random()) / Double(UINT32_MAX)
}
func createData(numPoints: Int) -> [PerceptronDataPair] {
var data = [PerceptronDataPair]()
for _ in 0..<numPoints {
let x = [2.0 * (randomDouble() - 0.5)]
let y = line(x[0])
struct PerceptronTrainer {
let data: [PerceptronDataPair]
func train(inout p: Perceptron) -> Int {
var error: Int = 0
for d in data {
error = p.backProp(d.input, output: d.output)
}
return error
}
mutating func backProp(input: [Double], output: Int) {
let prediction = feedForward(input)
let error = output - prediction
for i in 0..<weights.count {
weights[i] += learningRate * Double(error) * input[i]
}
}
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)
}
@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)
}
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
}