Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active February 12, 2016 13:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/0fbdf39e2a4d2a17629f to your computer and use it in GitHub Desktop.
Save JadenGeller/0fbdf39e2a4d2a17629f to your computer and use it in GitHub Desktop.
Swift Callback Function Transformation
/*
* Takes in a function that transform T to U and
* a callback that takes arguments of type T and U
* and returns a function that performs f but calls
* the callback before returning
*/
func callback<T,U>(f: T -> U, c: (T, U) -> ()) -> T -> U{
return { x in
let r = f(x)
c(x,r)
return r
}
}
/*
* Example usage of our callback function
* that will create a new function that performs
* f but also prints the input and output of f
*/
func print<T,U>(f: T -> U) -> T -> U {
return callback(f, { x, r in println("\(x) -> \(r)") })
}
/*
* Similiar to the print function, but also takes in a
* tag as input
*/
func print<T,U>(f: T -> U, tag: String) -> T -> U {
return callback(f, { x, r in println("\(tag): \(x) -> \(r)") })
}
/*
* Pretty intutive, e.g. identity(x) -> x
*/
func identity<T>(x: T) -> T {
return x
}
// Example A
var x = 0
for i in 1...4 {
x = print(+, "add")(0,i) // -> "add: (0,1) -> 1"
} // "add: (1,2) -> 3"
// "add: (3,3) -> 6"
// "add: (6,4) -> 10"
println("the result is \(x)") // -> "the result is 10"
// Example B
var s = ""
for i in "Hey" {
s.append(print(identity)(i)) // -> "H -> H"
// "e -> e"
// "y -> y"
print(s.append)(i) // -> "H -> ()"
} // -> "e -> ()"
// -> "y -> ()"
println("the result is \(s)") // "the result is HHeeyy"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment