Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Reduce, without the initial value
enum ListError: ErrorType {
case Empty
case Unknown
}
extension CollectionType {
typealias Elem = Self.Generator.Element
func list(combine:(Elem, Elem) -> Elem) throws -> Elem {
var gen = self.generate()
var cur:Elem? = gen.next()
guard let first = cur else{
throw ListError.Empty
}
var x:Elem = first
cur = gen.next()
while(cur != nil){
x = combine(x,cur!)
cur = gen.next()
}
return x
}
func list<T>(transform:(Elem -> T), @noescape combine:(T, T) -> T) throws -> T{
var gen = self.generate()
var cur = gen.next()
guard let first = cur else{
throw ListError.Empty
}
var x:T = transform(first)
cur = gen.next()
while(cur != nil){
x = combine(x,transform(cur!))
cur = gen.next()
}
return x
}
}
let nums = [1,2,3,4,5,6,7,8]
let numb = try? nums.list(+)
print(numb)
//Optional(36)
let strNums = ["1","2","3","4","5","6","7","8"]
let strNumb = try? strNums.list{$0+","+$1}
print(strNumb)
//Optional("1,2,3,4,5,6,7,8")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment