Skip to content

Instantly share code, notes, and snippets.

@Danappelxx
Created December 18, 2015 22:03
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 Danappelxx/ca1582599d32f72e77ba to your computer and use it in GitHub Desktop.
Save Danappelxx/ca1582599d32f72e77ba to your computer and use it in GitHub Desktop.
enum ReturnType<T> {
case Normal(T)
case Early(T)
}
extension SequenceType {
func rreduce<T>(initial: T, combine: (T, Self.Generator.Element) -> ReturnType<T>) -> T {
var result = initial
for el in self {
switch combine(result, el) {
case .Early(let res):
return res
case .Normal(let res):
result = res
}
}
return result
}
}
let addUntil3: (Int, Int) -> ReturnType<Int> = { total, el in
let total = total + el
if el == 3 {
return .Early(total)
}
return .Normal(total)
}
[1,2,3,4,5].reduce(0, combine: +) // 1+2+3+4+5 -> 15
[1,2,3,4,5].rreduce(0, combine: addUntil3) // 1+2+3 -> 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment