Skip to content

Instantly share code, notes, and snippets.

@davidpdrsn
Created June 3, 2014 16:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidpdrsn/3afcee0327285be77fbd to your computer and use it in GitHub Desktop.
Save davidpdrsn/3afcee0327285be77fbd to your computer and use it in GitHub Desktop.
Fold function in Swift
func foldl<T, E>(list:Array<T>, base:E, transform:(acc:E, item:T) -> E) -> E {
var result = base
for item in list {
result = transform(acc: result, item: item)
}
return result
}
func add(x:Int, y:Int) -> Int {
return x + y;
}
var numbers = [1,2,3,4,5]
var sum = foldl(numbers, 0, add)
println(sum)
@jbarros35
Copy link

pretty cool sample.

@vlm
Copy link

vlm commented Apr 18, 2018

(swift) [1,2,3].reduce(0, +)
// r0 : Int = 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment