-
-
Save edwardean/d28a53baee6ff6c4cdf62e921520bc71 to your computer and use it in GitHub Desktop.
sumRecursively based on http://natashatherobot.com/functional-swift-tail-recursion/
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
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