Last active
August 29, 2015 14:16
-
-
Save JadenGeller/6417b483f9085431fec7 to your computer and use it in GitHub Desktop.
Lambda Wrapping to Guard Evaluation in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Imagine we have a function that curries | |
// That is, multiply takes in an integer a | |
// and returns a fuction that takes in another | |
// integer b that will return a * b | |
func multiply(a: Int) -> Int -> Int { | |
println("I got the first thing") | |
return { b in | |
println("I got the second thing") | |
return a * b | |
} | |
} | |
// Note we can use such a function to muliply 3 and 5 as follows | |
multiply(3)(5) | |
// First we will examine the case of no guard | |
let multiplyBy3 = multiply(3) // -> "I got the first thing" | |
println("I'm waiting...") // -> "I'm waiting" | |
let result = multiplyBy3(5) // -> "I got the second thing" | |
println("The result is \(result)") // -> "The result is 15" | |
// Notice that we printed "I'm waiting" in between | |
// receiving the first and second argument | |
// Now we will wrap our first line of code in a lambda (closure) | |
let multiplyBy3 = { x in multiply(3)(x) } // -> | |
println("I'm waiting...") // -> "I'm waiting" | |
let result = multiplyBy3(5) // -> "I got the first thing"; -> "I got the second thing" | |
println("The result is \(result)") // -> "The result is 15" | |
// Notice that we printed "I'm waiting before we even recieved | |
// the first argument! This is because we created a new function | |
// that WILL pass three into multiply whenever it recieves another | |
// arugment x to pass in as well. Neat! | |
// Note that I wanted to make a function guard that would work like | |
// above with the syntax guard(multiply(3)), but it turns out that | |
// you cannot use @autoclosures to caputre partially evaluated | |
// functions in Swift, darn. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment