Created
December 18, 2015 22:03
-
-
Save Danappelxx/ca1582599d32f72e77ba to your computer and use it in GitHub Desktop.
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
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