Skip to content

Instantly share code, notes, and snippets.

@plumhead
Created June 10, 2014 21:33
Show Gist options
  • Save plumhead/b5ef3065aabcb8a6e15a to your computer and use it in GitHub Desktop.
Save plumhead/b5ef3065aabcb8a6e15a to your computer and use it in GitHub Desktop.
Swift folding
operator infix |> {associativity left precedence 140}
func |> <T,U> (left: @auto_closure () -> T,right: T -> U) -> U {
return right(left())
}
func fold<S,T>(f : (S,T) -> S,acc: S)(s : Array<T>) -> S {
if s.isEmpty {
return acc
}
else {
return fold(f,f(acc,s[0]))(s: Array(s[1..s.count]))
}
}
// Ints
let z =
[1,2,3,4,5,6]
|> fold({
(acc,value) in
return acc + value
},0)
// Not generic as it relies on the + operator (Swift type hierarchy makes this difficult to make generic - will try and work out a better solution)
func sum(s : Array<Int>, seed: Int) -> Int {
return s |> fold({(acc,value) in acc + value},seed)
}
sum([1,2,3,4,5],10) // 25
sum([],0) // 0
// Strings
let z1 =
["Andy","Calderbank"]
|> fold({
(acc,value) in
acc + ":" + value
},"Name") // Name:Andy:Calderbank
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment