Skip to content

Instantly share code, notes, and snippets.

@altyus
Last active August 29, 2015 14:17
Show Gist options
  • Save altyus/b19dba3852e1de2cccdf to your computer and use it in GitHub Desktop.
Save altyus/b19dba3852e1de2cccdf to your computer and use it in GitHub Desktop.
Recursive Reduce Swift
//Implement Reduce
func reduceRecursively <A, R>(xs: [A], initialValue: R, combine:(R, A) -> R) -> R {
if let head = xs.first {
let tail = Array(dropFirst(xs))
return reduceRecursively(tail, combine(initialValue, head), combine)
} else {
return initialValue
}
}
// Call Reduce
reduceRecursively([1, 2, 3, 4], 1) {
$0 + $1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment