Last active
August 29, 2015 14:14
-
-
Save kazk/fc96b66468ba38e32904 to your computer and use it in GitHub Desktop.
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
// ([T], (T)->[U]) -> [U] | |
public func flatMap<S : SequenceType, R : SequenceType> | |
(sequence: S, f: (S.Generator.Element)->R) | |
-> SequenceOf<R.Generator.Element> | |
{ | |
return SequenceOf {_ -> GeneratorOf<R.Generator.Element> in | |
var g = sequence.generate() | |
var ss = GeneratorOf<R> { g.next().map(f) } | |
var rG = ss.next()?.generate() | |
return GeneratorOf { | |
if let x = rG?.next() { return x } | |
while let s = ss.next() { | |
rG = s.generate() | |
if let x = rG?.next() { return x } | |
} | |
return nil | |
} | |
} | |
} | |
// map([0, 1, 2, 3]) { [Int](count: $0, repeatedValue: $0) } | |
//=> [[], [1], [2, 2], [3, 3, 3]] | |
// flatMap([0, 1, 2, 3]) { [Int](count: $0, repeatedValue: $0) }.array | |
//=> [1, 2, 2, 3, 3, 3] | |
public func flatMap<T, U>(x: T?, f: (T)->U?) -> U? { | |
return x.map(f) ?? nil | |
} | |
//extension Optional { | |
// func flatMap<U>(f: (T)->U?) -> U? { return self.map(f) ?? nil } | |
//} | |
// let (a, b): (Int?, Int?) = (1, 1) | |
// a.map {_a in b.map {_b in _a + _b} } // {{Some 2}} | |
// a.flatMap {_a in b.flatMap {_b in _a + _b} } // {Some 2} | |
// map(a) {(_a) in map(b) {(_b) in _a + _b } } // {{Some 2}} | |
// flatMap(a) {(_a) in flatMap(b) {(_b) in _a + _b } } // {Some 2} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment