Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active August 29, 2015 14:02
Show Gist options
  • Save kristopherjohnson/6a76b7e03fc7a8d6a918 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/6a76b7e03fc7a8d6a918 to your computer and use it in GitHub Desktop.
F#-isms translated into Swift
// Wrap closure that will be evaluated only the first time force()/value is called.
// Subsequent calls will return the already-calculated value.
class Lazy<T> {
init(_ closure: () -> T) {
self.force = { [unowned self] in
let v = closure()
self.force = { return v }
return v
}
}
// Evaluate if necessary and return value
var force: (() -> T)!
// Computed property calls force()
var value: T {
return force()
}
}
// Create a Lazy<T> using a simple expression
func lazy<T>(expression: @auto_closure () -> T) -> Lazy<T> {
return Lazy<T>(expression)
}
operator infix >> { associativity left }
@infix func >> <T1, T2, T3> (left: (T1)->T2, right: (T2)->T3) -> (T1)->T3 {
return { (t1: T1) -> T3 in return right(left(t1)) }
}
operator infix << { associativity right }
@infix func << <T1, T2, T3> (left: (T3)->T1, right: (T2)->T3) -> (T2)->T1 {
return { (t2: T2) -> T1 in return left(right(t2)) }
}
operator infix |> { associativity left }
@infix func |><T,U> (left: T, right: (T)->U ) -> U {
return right(left)
}
operator infix <| { associativity right }
@infix func <| <T, U> (left: (T)->U, right: T ) -> U {
return left(right)
}
func zip<T, U>(a1: Array<T>, a2: Array<U>) -> Array<(T, U)> {
assert(a1.count == a2.count);
let count = a1.count
var result = Array<(T, U)>()
result.reserveCapacity(count)
for i in 0..count {
let newElem = (a1[i], a2[i])
result.append(newElem)
}
return result
}
func unzip<T, U>(a: Array<(T, U)>) -> (Array<T>, Array<U>) {
let count = a.count
var aT = Array<T>()
var aU = Array<U>()
aT.reserveCapacity(count)
aU.reserveCapacity(count)
for (t, u) in a {
aT.append(t)
aU.append(u)
}
return (aT, aU)
}
@kristopherjohnson
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment