Created
January 2, 2015 22:33
-
-
Save marcelofabri/4b41adb87a09ce86ff40 to your computer and use it in GitHub Desktop.
sumRecursively based on http://natashatherobot.com/functional-swift-tail-recursion/
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
func sumRecursively(numbers: [Int], _ acc:Int = 0) -> Int { | |
if let head = numbers.first { | |
let tail = Array(dropFirst(numbers)) | |
return sumRecursively(tail, head + acc) | |
} else { | |
return acc | |
} | |
} | |
let myNumbers = [1,2,3,4,5] | |
sumRecursively(myNumbers) // 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment