Skip to content

Instantly share code, notes, and snippets.

@HenningBrandt
Created June 28, 2015 14:00
Show Gist options
  • Save HenningBrandt/f44a0f59c716e7fe4689 to your computer and use it in GitHub Desktop.
Save HenningBrandt/f44a0f59c716e7fe4689 to your computer and use it in GitHub Desktop.
Sample code from this blog post: http://thepurecoder.com/more-on-fold/
func foldl1<A>(list: Array<A>, f: (A, A) -> A) -> A {
return foldl(list.head!, list: list.tail!, f: f)
}
extension Array {
var initial: Array<Element>? {
get {
if self.empty() { return nil }
return Array(dropLast(self))
}
}
}
func foldr<A,B>(acc: A, list: Array<B>, f: (B, A) -> A) -> A {
if list.empty() { return acc }
return foldr(f(list.last!, acc), list: list.initial!, f: f);
}
func foldr1<A>(list: Array<A>, f: (A, A) -> A) -> A {
return foldr(list.last!, list: list.initial!, f: f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment