Skip to content

Instantly share code, notes, and snippets.

@marcocapano
Last active January 22, 2019 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcocapano/5f80311fb843d5b0c5148c790b8d346e to your computer and use it in GitHub Desktop.
Save marcocapano/5f80311fb843d5b0c5148c790b8d346e to your computer and use it in GitHub Desktop.
/// Calls a function n times passing the result of each call into the next call.
///
/// - Parameters:
/// - function: A function that takes T and returns T. It will be called multiple times and produce the result.
/// - initialInput: The initial input to pass into the function.
/// - repetitions: The number of times the function has to be called.
/// - Returns: Returns the result of consecutive calls to the given functions.
func call<T>(_ function: @escaping (T) -> T?, initialInput: T, repetitions: Int) -> T? {
var seq = sequence(first: initialInput, next: function)
var result: T?
//we call next() n+1 times because otherwise the first call would result in the initial input being the output.
for _ in 0..<(repetitions + 1) {
result = seq.next()
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment