This is a Swift microframework providing a lazy Stream<T> type with generic implementations of ==/!= where T: Equatable.
Streams are lazily-populated as well as lazily-evaluated, making them convenient for procrastinating tasks you don’t want to do yet, like performing an expensive computation in successive stages.
You can construct Streams with SequenceTypes, use them as SequenceTypes, and map and fold to your heart’s content.
Constructing a Stream:
let empty: Stream<Int> = nil
let unary = Stream.pure(4)
let binary = Stream.cons(4, nil)
let fibonacci: Stream<Int> = fix { fib in // fix is from Prelude.framework
{ x, y in Stream.cons(x + y, fib(y, x + y)) }
}(0, 1)Note that fibonacci is infinite! Don’t worry about it, just don’t evaluate it all in one go (like with a for loop that never breaks).
It’s safe to extract values from any Stream, whether infinite or not:
let (first, rest) = fibonacci.uncons
let first = fibonacci.first
let rest = fibonacci.rest
let isEmpty = fibonacci.isEmptyBetter yet, use take and drop to do the heavy lifting for you, or map to compute whatever you need to in a new infinite Stream:
// Bad, infinite loops:
for each in fibonacci {}
// Okay, stops:
for each in fibonacci { break }
// Good, doesn’t compute anything til you iterate the result:
let firstFive = fibonacci.take(5)
// Best, doesn’t compute anything til you iterate, and it’s infinite too:
let fibonacciSquares = fibonacci.map { x in x * x }You can combine Streams together by concatenating them using the ++ operator—even infinite ones:
let aleph = fibonacci ++ fibonacciThis is more useful for prepending elements onto an infinite stream, though:
let fibonacciSquaresForABit = firstFive.map { x in x * x } ++ fibonacci.drop(5)Full API documentation is in the source.
- Add this repository as a submodule and check out its dependencies, and/or add it to your Cartfile if you’re using carthage to manage your dependencies.
- Drag
Stream.xcodeprojinto your project or workspace, and do the same with its dependencies (i.e. the other.xcodeprojfiles included inStream.xcworkspace). NB:Stream.xcworkspaceis for standalone development of Stream, whileStream.xcodeprojis for targets using Stream as a dependency. - Link your target against
Stream.frameworkand each of the dependency frameworks. - Application targets should ensure that the framework gets copied into their application bundle. (Framework targets should instead require the application linking them to include Stream and its dependencies.)