Last active
February 3, 2018 23:00
-
-
Save rnapier/d58e893234539065222a to your computer and use it in GitHub Desktop.
Helper functions
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
import Foundation | |
/// This is going to be one of those things that for many of you is so obvious that it doesn't | |
/// require saying. But maybe a few of you have never really done this before either. I've been | |
/// thinking about nested helper functions. | |
/// I've used little nested helper functions lots of times. I do this when I want a function, but | |
/// nothing outside of this scope would ever need it. | |
func doSomething() { | |
func inc(x: Int) -> Int { return x + 1 } | |
print("\(inc(2))") | |
} | |
/// And I've sometimes used the parameters to the outer function in the nested function, which is | |
/// often very handy. This is really common in Scala because you often need this for loops. | |
func doSomethingToX(x: Int) { | |
func incX() -> Int { return x + 1 } | |
print("\(incX())") | |
} | |
/// But I've always created the helper function at the top. I'd never thought about setting a bunch | |
/// of things to be captured by the helper. For example, from a current project I'm playing with: | |
func solve(config: Config) throws { | |
let input = try config.parser(filename: config.filename) | |
// Here I set up the formatter | |
let formatter = NSDateComponentsFormatter() | |
formatter.allowedUnits = [.Hour, .Minute, .Second] | |
// And here I set the start date | |
let startDate = NSDate() | |
// And *then* I define the helper function, which makes the rest of the code much simpler | |
func duration() -> NSString { | |
return formatter.stringFromDate(startDate, toDate: NSDate()) ?? "" | |
} | |
var bestSolution: Solution? | |
for solution in GeneratorSequence(config.makeSolutionGenerator(input)) { | |
bestSolution = solution | |
print("\(duration()) : \(solution.progressOutput)") | |
} | |
print("Final Time: \(duration())") | |
print("") | |
print(bestSolution?.finalOutput ?? "NO SOLUTION") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment