Skip to content
This repository has been archived by the owner on Jan 2, 2022. It is now read-only.

Commit

Permalink
Streams.
Browse files Browse the repository at this point in the history
  • Loading branch information
jtomschroeder committed Aug 6, 2016
1 parent 9c1644a commit 1d86d5c
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/lambda.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 23,6 @@

#include "lambda/dollar.hpp"

#include "lambda/stream.hpp"

#endif // LAMBDA_LAMBDA_H
69 changes: 69 additions & 0 deletions lib/lambda/stream.hpp
Original file line number Diff line number Diff line change
@@ -0,0 1,69 @@

#pragma once

#include "maybe.hpp"

namespace lambda {

// pub trait Iterator {
// type Item;
// fn next(&mut self)->Option<Self::Item>;
//
// fn map<B, F>(self, f: F) -> Map<Self, F> where Self: Sized, F: FnMut(Self::Item) -> B { ... }
//
//
// pub struct Map<I, F> {
// iter: I,
// f: F,
// }
//

template <class T>
class Stream : public std::enable_shared_from_this<Stream<T>> {
public:
using RawStream = std::shared_ptr<Stream>;

Stream() {}

virtual Maybe<T> next() = 0;

template <class F>
RawStream map(F &&f);
};

template <class T>
using RawStream = typename Stream<T>::RawStream;

template <class T, class F>
class Map : public Stream<T> {
RawStream<T> stream;
F f;

public:
Map(RawStream<T> stream, F f) : stream(stream), f(f) {}

virtual Maybe<T> next() { return stream->next() >> f; }
};

template <class T, class C>
class IteratorStream : public Stream<T> {
typename C::const_iterator begin, end;

public:
IteratorStream(C &collection) : begin(collection.cbegin()), end(collection.cend()) {}

virtual Maybe<T> next() { return begin != end ? some(*begin ) : none; }
};

template <class T, class C>
static auto from(C &collection) {
return RawStream<T>(new IteratorStream<T, C>{collection});
}

template <class T>
template <class F>
RawStream<T> Stream<T>::map(F &&f) {
return RawStream(new Map<T, F>{Stream<T>::shared_from_this(), f});
}

} /* lambda */
7 changes: 7 additions & 0 deletions test/test_dollar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 13,11 @@ TEST(lambda, dollar) {
ASSERT_EQ(vector(2, 3, 4, 5), map(vector(1, 2, 3, 4), plus(1)));

ASSERT_EQ(vector(1, 4), without(vector(1, 2, 3, 4), 2, 3));

auto vec = vector(1, 2, 3, 4);
// auto stream = IteratorStream<int, std::vector<int>>{vec}.map([](auto i) { return i; });
auto stream = from<int>(vec)->map([](auto i) { return i * 25; });
while (auto val = stream->next()) {
printer << val;
}
}

0 comments on commit 1d86d5c

Please sign in to comment.