Last active
January 22, 2019 15:20
-
-
Save marcocapano/5f80311fb843d5b0c5148c790b8d346e to your computer and use it in GitHub Desktop.
This file contains 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
/// 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