Created
January 2, 2015 01:50
-
-
Save kazk/19d2370947800670e6e2 to your computer and use it in GitHub Desktop.
This file contains 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
// accumulate (scanl) | |
public func accumulate<S : SequenceType, T> | |
(sequence: S, initial: T, combine: (T, S.Generator.Element)->T) | |
-> SequenceOf<T> | |
{ | |
return SequenceOf {_ -> GeneratorOf<T> in | |
var g = sequence.generate() | |
var value:T? = initial | |
return GeneratorOf { | |
switch value { | |
case .None: return nil | |
case .Some(let x): | |
value = g.next().map { combine(x, $0) } | |
return x | |
} | |
} | |
} | |
} | |
// scanl1 | |
public func accumulate<S : SequenceType> | |
(sequence: S, combine: (S.Generator.Element, S.Generator.Element)->S.Generator.Element) | |
-> SequenceOf<S.Generator.Element> | |
{ | |
return SequenceOf {_ -> GeneratorOf<S.Generator.Element> in | |
var g = sequence.generate() | |
var value = g.next() | |
return GeneratorOf { | |
switch value { | |
case .None: return nil | |
case .Some(let x): | |
value = g.next().map { combine(x, $0) } | |
return x | |
} | |
} | |
} | |
} | |
// accumulate([1,1,1,1], 0, +).array //=> [0,1,2,3,4] | |
// accumulate([1,1,1,1], 0, -).array //=> [0,-1,-2,-3,-4] | |
// accumulate([1], 0, -).array //=> [0,-1] | |
// accumulate([1,1,1,1], +).array //=> [1,2,3,4] | |
// accumulate([1,2,3,4,5], +).array //=> [1,3,6,10,15] | |
// accumulate([1,2,3,4,5], *).array //=> [1,2,6,24,120] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment