2 * Copyright 2012 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 namespace folly { namespace gen {
20 * IsCompatibleSignature - Trait type for testing whether a given Functor
21 * matches an expected signature.
24 * IsCompatibleSignature<FunctorType, bool(int, float)>::value
26 template<class Candidate, class Expected>
27 class IsCompatibleSignature {
28 static constexpr bool value = false;
31 template<class Candidate,
34 class IsCompatibleSignature<Candidate, ExpectedReturn(ArgTypes...)> {
37 decltype(std::declval<F>()(std::declval<ArgTypes>()...)),
38 bool good = std::is_same<ExpectedReturn, ActualReturn>::value>
39 static constexpr bool testArgs(int* p) {
44 static constexpr bool testArgs(...) {
48 static constexpr bool value = testArgs<Candidate>(nullptr);
52 * ArgumentReference - For determining ideal argument type to receive a value.
55 struct ArgumentReference :
56 public std::conditional<std::is_reference<T>::value,
57 T, // T& -> T&, T&& -> T&&, const T& -> const T&
58 typename std::conditional<
59 std::is_const<T>::value,
60 T&, // const int -> const int&
65 * FBounded - Helper type for the curiously recurring template pattern, used
66 * heavily here to enable inlining and obviate virtual functions
70 const Self& self() const {
71 return *static_cast<const Self*>(this);
75 return *static_cast<Self*>(this);
80 * Operator - Core abstraction of an operation which may be applied to a
81 * generator. All operators implement a method compose(), which takes a
82 * generator and produces an output generator.
85 class Operator : public FBounded<Self> {
88 * compose() - Must be implemented by child class to compose a new Generator
89 * out of a given generator. This function left intentionally unimplemented.
91 template<class Source,
93 class ResultGen = void>
94 ResultGen compose(const GenImpl<Value, Source>& source) const;
98 Operator(const Operator&) = default;
99 Operator(Operator&&) = default;
103 * operator|() - For composing two operators without binding it to a
104 * particular generator.
108 class Composed = detail::Composed<Left, Right>>
109 Composed operator|(const Operator<Left>& left,
110 const Operator<Right>& right) {
111 return Composed(left.self(), right.self());
116 class Composed = detail::Composed<Left, Right>>
117 Composed operator|(const Operator<Left>& left,
118 Operator<Right>&& right) {
119 return Composed(left.self(), std::move(right.self()));
124 class Composed = detail::Composed<Left, Right>>
125 Composed operator|(Operator<Left>&& left,
126 const Operator<Right>& right) {
127 return Composed(std::move(left.self()), right.self());
132 class Composed = detail::Composed<Left, Right>>
133 Composed operator|(Operator<Left>&& left,
134 Operator<Right>&& right) {
135 return Composed(std::move(left.self()), std::move(right.self()));
138 template<class Value,
140 class Yield = detail::Yield<Value, Source>>
141 Yield operator+(const detail::GeneratorBuilder<Value>&,
143 return Yield(std::forward<Source>(source));
147 * GenImpl - Core abstraction of a generator, an object which produces values by
148 * passing them to a given handler lambda. All generator implementations must
149 * implement apply(). foreach() may also be implemented to special case the
150 * condition where the entire sequence is consumed.
152 template<class Value,
154 class GenImpl : public FBounded<Self> {
156 // To prevent slicing
158 GenImpl(const GenImpl&) = default;
159 GenImpl(GenImpl&&) = default;
162 typedef Value ValueType;
163 typedef typename std::decay<Value>::type StorageType;
166 * apply() - Send all values produced by this generator to given
167 * handler until it returns false. Returns true if the false iff the handler
170 template<class Handler>
171 bool apply(Handler&& handler) const;
174 * foreach() - Send all values produced by this generator to given lambda.
177 void foreach(Body&& body) const {
178 this->self().apply([&](Value value) {
179 body(std::forward<Value>(value));
185 template<class LeftValue,
189 class Chain = detail::Chain<LeftValue, Left, Right>>
190 Chain operator+(const GenImpl<LeftValue, Left>& left,
191 const GenImpl<RightValue, Right>& right) {
193 std::is_same<LeftValue, RightValue>::value,
194 "Generators may ony be combined if Values are the exact same type.");
195 return Chain(left.self(), right.self());
198 template<class LeftValue,
202 class Chain = detail::Chain<LeftValue, Left, Right>>
203 Chain operator+(const GenImpl<LeftValue, Left>& left,
204 GenImpl<RightValue, Right>&& right) {
206 std::is_same<LeftValue, RightValue>::value,
207 "Generators may ony be combined if Values are the exact same type.");
208 return Chain(left.self(), std::move(right.self()));
211 template<class LeftValue,
215 class Chain = detail::Chain<LeftValue, Left, Right>>
216 Chain operator+(GenImpl<LeftValue, Left>&& left,
217 const GenImpl<RightValue, Right>& right) {
219 std::is_same<LeftValue, RightValue>::value,
220 "Generators may ony be combined if Values are the exact same type.");
221 return Chain(std::move(left.self()), right.self());
224 template<class LeftValue,
228 class Chain = detail::Chain<LeftValue, Left, Right>>
229 Chain operator+(GenImpl<LeftValue, Left>&& left,
230 GenImpl<RightValue, Right>&& right) {
232 std::is_same<LeftValue, RightValue>::value,
233 "Generators may ony be combined if Values are the exact same type.");
234 return Chain(std::move(left.self()), std::move(right.self()));
238 * operator|() which enables foreach-like usage:
239 * gen | [](Value v) -> void {...};
241 template<class Value,
244 typename std::enable_if<
245 IsCompatibleSignature<Handler, void(Value)>::value>::type
246 operator|(const GenImpl<Value, Gen>& gen, Handler&& handler) {
247 gen.self().foreach(std::forward<Handler>(handler));
251 * operator|() which enables foreach-like usage with 'break' support:
252 * gen | [](Value v) -> bool { return shouldContinue(); };
254 template<class Value,
257 typename std::enable_if<
258 IsCompatibleSignature<Handler, bool(Value)>::value, bool>::type
259 operator|(const GenImpl<Value, Gen>& gen, Handler&& handler) {
260 return gen.self().apply(std::forward<Handler>(handler));
264 * operator|() for composing generators with operators, similar to boosts' range
266 * gen | map(square) | sum
268 template<class Value,
271 auto operator|(const GenImpl<Value, Gen>& gen, const Operator<Op>& op) ->
272 decltype(op.self().compose(gen.self())) {
273 return op.self().compose(gen.self());
276 template<class Value,
279 auto operator|(GenImpl<Value, Gen>&& gen, const Operator<Op>& op) ->
280 decltype(op.self().compose(std::move(gen.self()))) {
281 return op.self().compose(std::move(gen.self()));
287 * ReferencedSource - Generate values from an STL-like container using
288 * iterators from .begin() until .end(). Value type defaults to the type of
289 * *container->begin(). For std::vector<int>, this would be int&. Note that the
290 * value here is a reference, so the values in the vector will be passed by
291 * reference to downstream operators.
293 * This type is primarily used through the 'from' helper method, like:
295 * string& longestName = from(names)
296 * | maxBy([](string& s) { return s.size() });
298 template<class Container,
300 class ReferencedSource :
301 public GenImpl<Value, ReferencedSource<Container, Value>> {
302 Container* container_;
304 explicit ReferencedSource(Container* container)
305 : container_(container) {}
308 void foreach(Body&& body) const {
309 for (auto& value : *container_) {
310 body(std::forward<Value>(value));
314 template<class Handler>
315 bool apply(Handler&& handler) const {
316 for (auto& value : *container_) {
317 if (!handler(std::forward<Value>(value))) {
326 * CopiedSource - For producing values from eagerly from a sequence of values
327 * whose storage is owned by this class. Useful for preparing a generator for
328 * use after a source collection will no longer be available, or for when the
329 * values are specified literally with an initializer list.
331 * This type is primarily used through the 'fromCopy' function, like:
333 * auto sourceCopy = fromCopy(makeAVector());
334 * auto sum = sourceCopy | sum;
335 * auto max = sourceCopy | max;
337 * Though it is also used for the initializer_list specialization of from().
339 template<class StorageType,
342 public GenImpl<const StorageType&,
343 CopiedSource<StorageType, Container>> {
345 !std::is_reference<StorageType>::value, "StorageType must be decayed");
347 // Generator objects are often copied during normal construction as they are
348 // encapsulated by downstream generators. It would be bad if this caused
349 // a copy of the entire container each time, and since we're only exposing a
350 // const reference to the value, it's safe to share it between multiple
353 !std::is_reference<Container>::value,
354 "Can't copy into a reference");
355 std::shared_ptr<const Container> copy_;
357 typedef Container ContainerType;
359 template<class SourceContainer>
360 explicit CopiedSource(const SourceContainer& container)
361 : copy_(new Container(begin(container), end(container))) {}
363 explicit CopiedSource(Container&& container) :
364 copy_(new Container(std::move(container))) {}
366 // To enable re-use of cached results.
367 CopiedSource(const CopiedSource<StorageType, Container>& source)
368 : copy_(source.copy_) {}
371 void foreach(Body&& body) const {
372 for (const auto& value : *copy_) {
377 template<class Handler>
378 bool apply(Handler&& handler) const {
379 // The collection may be reused by others, we can't allow it to be changed.
380 for (const auto& value : *copy_) {
381 if (!handler(value)) {
390 * Sequence - For generating values from beginning value, incremented along the
391 * way with the ++ and += operators. Iteration may continue indefinitely by
392 * setting the 'endless' template parameter to true. If set to false, iteration
393 * will stop when value reaches 'end', either inclusively or exclusively,
394 * depending on the template parameter 'endInclusive'. Value type specified
397 * This type is primarily used through the 'seq' and 'range' function, like:
399 * int total = seq(1, 10) | sum;
400 * auto indexes = range(0, 10);
402 template<class Value,
405 class Sequence : public GenImpl<const Value&,
406 Sequence<Value, endless, endInclusive>> {
407 static_assert(!std::is_reference<Value>::value &&
408 !std::is_const<Value>::value, "Value mustn't be const or ref.");
409 Value bounds_[endless ? 1 : 2];
411 explicit Sequence(const Value& begin)
413 static_assert(endless, "Must supply 'end'");
416 explicit Sequence(const Value& begin, const Value& end)
417 : bounds_{begin, end} {}
419 template<class Handler>
420 bool apply(Handler&& handler) const {
421 Value value = bounds_[0];
422 for (;endless || value < bounds_[1]; ++value) {
423 const Value& arg = value;
428 if (endInclusive && value == bounds_[1]) {
429 const Value& arg = value;
438 void foreach(Body&& body) const {
439 Value value = bounds_[0];
440 for (;endless || value < bounds_[1]; ++value) {
441 const Value& arg = value;
444 if (endInclusive && value == bounds_[1]) {
445 const Value& arg = value;
452 * Chain - For concatenating the values produced by two Generators.
454 * This type is primarily used through using '+' to combine generators, like:
456 * auto nums = seq(1, 10) + seq(20, 30);
457 * int total = nums | sum;
459 template<class Value, class First, class Second>
460 class Chain : public GenImpl<Value,
461 Chain<Value, First, Second>> {
465 explicit Chain(First first, Second second)
466 : first_(std::move(first))
467 , second_(std::move(second)) {}
469 template<class Handler>
470 bool apply(Handler&& handler) const {
471 return first_.apply(std::forward<Handler>(handler))
472 && second_.apply(std::forward<Handler>(handler));
476 void foreach(Body&& body) const {
477 first_.foreach(std::forward<Body>(body));
478 second_.foreach(std::forward<Body>(body));
483 * Yield - For producing values from a user-defined generator by way of a
486 template<class Value, class Source>
487 class Yield : public GenImpl<Value, Yield<Value, Source>> {
490 explicit Yield(Source source)
491 : source_(std::move(source)) {
494 template<class Handler>
495 bool apply(Handler&& handler) const {
497 auto body = [&](Value value) {
498 if (!handler(std::forward<Value>(value))) {
511 void foreach(Body&& body) const {
512 source_(std::forward<Body>(body));
522 * Map - For producing a sequence of values by passing each value from a source
523 * collection through a predicate.
525 * This type is usually used through the 'map' or 'mapped' helper function:
527 * auto squares = seq(1, 10) | map(square) | asVector;
529 template<class Predicate>
530 class Map : public Operator<Map<Predicate>> {
531 Predicate predicate_;
533 explicit Map(const Predicate& predicate = Predicate())
534 : predicate_(predicate)
537 template<class Value,
539 class Result = typename ArgumentReference<
540 typename std::result_of<Predicate(Value)>::type
543 public GenImpl<Result, Generator<Value, Source, Result>> {
547 explicit Generator(Source source, const Predicate& pred)
548 : source_(std::move(source)), pred_(pred) {}
551 void foreach(Body&& body) const {
552 source_.foreach([&](Value value) {
553 body(pred_(std::forward<Value>(value)));
557 template<class Handler>
558 bool apply(Handler&& handler) const {
559 return source_.apply([&](Value value) {
560 return handler(pred_(std::forward<Value>(value)));
565 template<class Source,
567 class Gen = Generator<Value, Source>>
568 Gen compose(GenImpl<Value, Source>&& source) const {
569 return Gen(std::move(source.self()), predicate_);
572 template<class Source,
574 class Gen = Generator<Value, Source>>
575 Gen compose(const GenImpl<Value, Source>& source) const {
576 return Gen(source.self(), predicate_);
582 * Filter - For filtering values from a source sequence by a predicate.
584 * This type is usually used through the 'filter' helper function, like:
586 * auto nonEmpty = from(strings)
587 * | filter([](const string& str) -> bool {
588 * return !str.empty();
591 template<class Predicate>
592 class Filter : public Operator<Filter<Predicate>> {
593 Predicate predicate_;
595 explicit Filter(const Predicate& predicate)
596 : predicate_(predicate)
599 template<class Value,
601 class Generator : public GenImpl<Value, Generator<Value, Source>> {
605 explicit Generator(Source source, const Predicate& pred)
606 : source_(std::move(source)), pred_(pred) {}
609 void foreach(Body&& body) const {
610 source_.foreach([&](Value value) {
611 if (pred_(std::forward<Value>(value))) {
612 body(std::forward<Value>(value));
617 template<class Handler>
618 bool apply(Handler&& handler) const {
619 return source_.apply([&](Value value) -> bool {
620 if (pred_(std::forward<Value>(value))) {
621 return handler(std::forward<Value>(value));
628 template<class Source,
630 class Gen = Generator<Value, Source>>
631 Gen compose(GenImpl<Value, Source>&& source) const {
632 return Gen(std::move(source.self()), predicate_);
635 template<class Source,
637 class Gen = Generator<Value, Source>>
638 Gen compose(const GenImpl<Value, Source>& source) const {
639 return Gen(source.self(), predicate_);
644 * Until - For producing values from a source until a predicate is satisfied.
646 * This type is usually used through the 'until' helper function, like:
648 * auto best = from(sortedItems)
649 * | until([](Item& item) { return item.score > 100; })
652 template<class Predicate>
653 class Until : public Operator<Until<Predicate>> {
654 Predicate predicate_;
656 explicit Until(const Predicate& predicate)
657 : predicate_(predicate)
660 template<class Value,
662 class Result = typename std::result_of<Predicate(Value)>::type>
664 public GenImpl<Result, Generator<Value, Source, Result>> {
668 explicit Generator(Source source, const Predicate& pred)
669 : source_(std::move(source)), pred_(pred) {}
671 template<class Handler>
672 bool apply(Handler&& handler) const {
673 return source_.apply([&](Value value) -> bool {
674 return !pred_(std::forward<Value>(value))
675 && handler(std::forward<Value>(value));
680 template<class Source,
682 class Gen = Generator<Value, Source>>
683 Gen compose(GenImpl<Value, Source>&& source) const {
684 return Gen(std::move(source.self()), predicate_);
687 template<class Source,
689 class Gen = Generator<Value, Source>>
690 Gen compose(const GenImpl<Value, Source>& source) const {
691 return Gen(source.self(), predicate_);
696 * Take - For producing up to N values from a source.
698 * This type is usually used through the 'take' helper function, like:
700 * auto best = from(docs)
701 * | orderByDescending(scoreDoc)
704 class Take : public Operator<Take> {
707 explicit Take(size_t count)
710 template<class Value,
713 public GenImpl<Value, Generator<Value, Source>> {
717 explicit Generator(Source source, size_t count)
718 : source_(std::move(source)) , count_(count) {}
720 template<class Handler>
721 bool apply(Handler&& handler) const {
722 if (count_ == 0) { return false; }
724 return source_.apply([&](Value value) -> bool {
725 if (!handler(std::forward<Value>(value))) {
733 template<class Source,
735 class Gen = Generator<Value, Source>>
736 Gen compose(GenImpl<Value, Source>&& source) const {
737 return Gen(std::move(source.self()), count_);
740 template<class Source,
742 class Gen = Generator<Value, Source>>
743 Gen compose(const GenImpl<Value, Source>& source) const {
744 return Gen(source.self(), count_);
749 * Skip - For skipping N items from the beginning of a source generator.
751 * This type is usually used through the 'skip' helper function, like:
753 * auto page = from(results)
754 * | skip(pageSize * startPage)
757 class Skip : public Operator<Skip> {
760 explicit Skip(size_t count)
763 template<class Value,
766 public GenImpl<Value, Generator<Value, Source>> {
770 explicit Generator(Source source, size_t count)
771 : source_(std::move(source)) , count_(count) {}
774 void foreach(Body&& body) const {
776 source_.foreach(body);
780 source_.foreach([&](Value value) {
784 body(std::forward<Value>(value));
789 template<class Handler>
790 bool apply(Handler&& handler) const {
792 return source_.apply(handler);
795 return source_.apply([&](Value value) -> bool {
800 return handler(std::forward<Value>(value));
805 template<class Source,
807 class Gen = Generator<Value, Source>>
808 Gen compose(GenImpl<Value, Source>&& source) const {
809 return Gen(std::move(source.self()), count_);
812 template<class Source,
814 class Gen = Generator<Value, Source>>
815 Gen compose(const GenImpl<Value, Source>& source) const {
816 return Gen(source.self(), count_);
821 * Order - For ordering a sequence of values from a source by key.
822 * The key is extracted by the given selector functor, and this key is then
823 * compared using the specified comparator.
825 * This type is usually used through the 'order' helper function, like:
827 * auto closest = from(places)
828 * | orderBy([](Place& p) {
829 * return -distance(p.location, here);
833 template<class Selector, class Comparer>
834 class Order : public Operator<Order<Selector, Comparer>> {
838 Order(const Selector& selector = Selector(),
839 const Comparer& comparer = Comparer())
840 : selector_(selector) , comparer_(comparer) {}
842 template<class Value,
844 class StorageType = typename std::decay<Value>::type,
845 class Result = typename std::result_of<Selector(Value)>::type>
847 public GenImpl<StorageType&&,
848 Generator<Value, Source, StorageType, Result>> {
853 typedef std::vector<StorageType> VectorType;
855 VectorType asVector() const {
856 auto comparer = [&](const StorageType& a, const StorageType& b) {
857 return comparer_(selector_(a), selector_(b));
859 auto vals = source_ | as<VectorType>();
860 std::sort(vals.begin(), vals.end(), comparer);
861 return std::move(vals);
864 Generator(Source source,
865 const Selector& selector,
866 const Comparer& comparer)
867 : source_(std::move(source)),
869 comparer_(comparer) {}
871 VectorType operator|(const Collect<VectorType>&) const {
875 VectorType operator|(const CollectTemplate<std::vector>&) const {
880 void foreach(Body&& body) const {
881 for (auto& value : asVector()) {
882 body(std::move(value));
886 template<class Handler>
887 bool apply(Handler&& handler) const {
888 auto comparer = [&](const StorageType& a, const StorageType& b) {
889 // swapped for minHeap
890 return comparer_(selector_(b), selector_(a));
892 auto heap = source_ | as<VectorType>();
893 std::make_heap(heap.begin(), heap.end(), comparer);
894 while (!heap.empty()) {
895 std::pop_heap(heap.begin(), heap.end(), comparer);
896 if (!handler(std::move(heap.back()))) {
905 template<class Source,
907 class Gen = Generator<Value, Source>>
908 Gen compose(GenImpl<Value, Source>&& source) const {
909 return Gen(std::move(source.self()), selector_, comparer_);
912 template<class Source,
914 class Gen = Generator<Value, Source>>
915 Gen compose(const GenImpl<Value, Source>& source) const {
916 return Gen(source.self(), selector_, comparer_);
921 * Composed - For building up a pipeline of operations to perform, absent any
922 * particular source generator. Useful for building up custom pipelines.
924 * This type is usually used by just piping two operators together:
926 * auto valuesOf = filter([](Optional<int>& o) { return o.hasValue(); })
927 * | map([](Optional<int>& o) -> int& { return o.value(); });
929 * auto valuesIncluded = from(optionals) | valuesOf | as<vector>();
931 template<class First,
933 class Composed : public Operator<Composed<First, Second>> {
938 Composed(First first, Second second)
939 : first_(std::move(first))
940 , second_(std::move(second)) {}
942 template<class Source,
944 class FirstRet = decltype(std::declval<First>()
945 .compose(std::declval<Source>())),
946 class SecondRet = decltype(std::declval<Second>()
947 .compose(std::declval<FirstRet>()))>
948 SecondRet compose(const GenImpl<Value, Source>& source) const {
949 return second_.compose(first_.compose(source.self()));
952 template<class Source,
954 class FirstRet = decltype(std::declval<First>()
955 .compose(std::declval<Source>())),
956 class SecondRet = decltype(std::declval<Second>()
957 .compose(std::declval<FirstRet>()))>
958 SecondRet compose(GenImpl<Value, Source>&& source) const {
959 return second_.compose(first_.compose(std::move(source.self())));
968 * FoldLeft - Left-associative functional fold. For producing an aggregate value
969 * from a seed and a folder function. Useful for custom aggregators on a
972 * This type is primarily used through the 'foldl' helper method, like:
974 * double movingAverage = from(values)
975 * | foldl(0.0, [](double avg, double sample) {
976 * return sample * 0.1 + avg * 0.9;
981 class FoldLeft : public Operator<FoldLeft<Seed, Fold>> {
985 FoldLeft(const Seed& seed, const Fold& fold)
990 template<class Source,
992 Seed compose(const GenImpl<Value, Source>& source) const {
994 source | [&](Value v) {
995 accum = fold_(std::move(accum), std::forward<Value>(v));
1002 * First - For finding the first value in a sequence.
1004 * This type is primarily used through the 'first' static value, like:
1006 * int firstThreeDigitPrime = seq(100) | filter(isPrime) | first;
1008 class First : public Operator<First> {
1010 template<class Source,
1012 class StorageType = typename std::decay<Value>::type>
1013 StorageType compose(const GenImpl<Value, Source>& source) const {
1014 static_assert(std::is_same<StorageType, int>::value, "wtf");
1015 Optional<StorageType> accum;
1016 source | [&](Value v) -> bool {
1017 accum = std::forward<Value>(v);
1020 if (!accum.hasValue()) {
1021 throw EmptySequence();
1023 return std::move(accum.value());
1029 * Any - For determining whether any values are contained in a sequence.
1031 * This type is primarily used through the 'any' static value, like:
1033 * bool any20xPrimes = seq(200, 210) | filter(isPrime) | any;
1035 class Any : public Operator<Any> {
1037 template<class Source,
1039 bool compose(const GenImpl<Value, Source>& source) const {
1041 source | [&](Value v) -> bool {
1050 * Reduce - Functional reduce, for recursively combining values from a source
1051 * using a reducer function until there is only one item left. Useful for
1052 * combining values when an empty sequence doesn't make sense.
1054 * This type is primarily used through the 'reduce' helper method, like:
1056 * sring longest = from(names)
1057 * | reduce([](string&& best, string& current) {
1058 * return best.size() >= current.size() ? best : current;
1061 template<class Reducer>
1062 class Reduce : public Operator<Reduce<Reducer>> {
1065 Reduce(const Reducer& reducer)
1069 template<class Source,
1071 class StorageType = typename std::decay<Value>::type>
1072 StorageType compose(const GenImpl<Value, Source>& source) const {
1073 Optional<StorageType> accum;
1074 source | [&](Value v) {
1075 if (accum.hasValue()) {
1076 accum = reducer_(std::move(accum.value()), std::forward<Value>(v));
1078 accum = std::forward<Value>(v);
1081 if (!accum.hasValue()) {
1082 throw EmptySequence();
1084 return accum.value();
1089 * Count - for simply counting the items in a collection.
1091 * This type is usually used through its singleton, 'count':
1093 * auto shortPrimes = seq(1, 100) | filter(isPrime) | count;
1095 class Count : public Operator<Count> {
1097 template<class Source,
1099 size_t compose(const GenImpl<Value, Source>& source) const {
1100 return foldl(size_t(0),
1101 [](size_t accum, Value v) {
1108 * Sum - For simply summing up all the values from a source.
1110 * This type is usually used through its singleton, 'sum':
1112 * auto gaussSum = seq(1, 100) | sum;
1114 class Sum : public Operator<Sum> {
1116 template<class Source,
1118 class StorageType = typename std::decay<Value>::type>
1119 StorageType compose(const GenImpl<Value, Source>& source) const {
1120 return foldl(StorageType(0),
1121 [](StorageType&& accum, Value v) {
1122 return std::move(accum) + std::forward<Value>(v);
1128 * Min - For a value which minimizes a key, where the key is determined by a
1129 * given selector, and compared by given comparer.
1131 * This type is usually used through the singletone 'min' or through the helper
1132 * functions 'minBy' and 'maxBy'.
1134 * auto oldest = from(people)
1135 * | minBy([](Person& p) {
1136 * return p.dateOfBirth;
1139 template<class Selector,
1141 class Min : public Operator<Min<Selector, Comparer>> {
1145 Min(const Selector& selector = Selector(),
1146 const Comparer& comparer = Comparer())
1147 : selector_(selector)
1148 , comparer_(comparer)
1151 template<class Value,
1153 class StorageType = typename std::decay<Value>::type,
1154 class Key = typename std::decay<
1155 typename std::result_of<Selector(Value)>::type
1157 StorageType compose(const GenImpl<Value, Source>& source) const {
1158 Optional<StorageType> min;
1159 Optional<Key> minKey;
1160 source | [&](Value v) {
1161 Key key = selector_(std::forward<Value>(v));
1162 if (!minKey.hasValue() || comparer_(key, minKey.value())) {
1164 min = std::forward<Value>(v);
1167 if (!min.hasValue()) {
1168 throw EmptySequence();
1175 * Append - For collecting values from a source into a given output container
1178 * This type is usually used through the helper function 'appendTo', like:
1180 * vector<int64_t> ids;
1181 * from(results) | map([](Person& p) { return p.id })
1184 template<class Collection>
1185 class Append : public Operator<Append<Collection>> {
1186 Collection* collection_;
1188 explicit Append(Collection* collection)
1189 : collection_(collection)
1192 template<class Value,
1194 Collection& compose(const GenImpl<Value, Source>& source) const {
1195 source | [&](Value v) {
1196 collection_->insert(collection_->end(), std::forward<Value>(v));
1198 return *collection_;
1203 * Collect - For collecting values from a source in a collection of the desired
1206 * This type is usually used through the helper function 'as', like:
1208 * std::string upper = from(stringPiece)
1210 * | as<std::string>();
1212 template<class Collection>
1213 class Collect : public Operator<Collect<Collection>> {
1215 template<class Value,
1217 class StorageType = typename std::decay<Value>::type>
1218 Collection compose(const GenImpl<Value, Source>& source) const {
1219 Collection collection;
1220 source | [&](Value v) {
1221 collection.insert(collection.end(), std::forward<Value>(v));
1229 * CollectTemplate - For collecting values from a source in a collection
1230 * constructed using the specified template type. Given the type of values
1231 * produced by the given generator, the collection type will be:
1232 * Container<Value, Allocator<Value>>
1234 * The allocator defaults to std::allocator, so this may be used for the STL
1235 * containers by simply using operators like 'as<set>', 'as<deque>',
1236 * 'as<vector>'. 'as', here is the helper method which is the usual means of
1237 * consturcting this operator.
1241 * set<string> uniqueNames = from(names) | as<set>();
1243 template<template<class, class> class Container,
1244 template<class> class Allocator>
1245 class CollectTemplate : public Operator<CollectTemplate<Container, Allocator>> {
1247 template<class Value,
1249 class StorageType = typename std::decay<Value>::type,
1250 class Collection = Container<StorageType, Allocator<StorageType>>>
1251 Collection compose(const GenImpl<Value, Source>& source) const {
1252 Collection collection;
1253 source | [&](Value v) {
1254 collection.insert(collection.end(), std::forward<Value>(v));
1260 * Concat - For flattening generators of generators.
1262 * This type is usually used through the 'concat' static value, like:
1266 * | map([](Node& x) {
1267 * return from(x.neighbors)
1268 * | map([&](Node& y) {
1269 * return Edge(x, y);
1275 class Concat : public Operator<Concat> {
1277 template<class Inner,
1279 class InnerValue = typename std::decay<Inner>::type::ValueType>
1281 public GenImpl<InnerValue, Generator<Inner, Source, InnerValue>> {
1284 explicit Generator(Source source)
1285 : source_(std::move(source)) {}
1287 template<class Handler>
1288 bool apply(Handler&& handler) const {
1289 return source_.apply([&](Inner inner) -> bool {
1290 return inner.apply(std::forward<Handler>(handler));
1294 template<class Body>
1295 void foreach(Body&& body) const {
1296 source_.foreach([&](Inner inner) {
1297 inner.foreach(std::forward<Body>(body));
1302 template<class Value,
1304 class Gen = Generator<Value, Source>>
1305 Gen compose(GenImpl<Value, Source>&& source) const {
1306 return Gen(std::move(source.self()));
1309 template<class Value,
1311 class Gen = Generator<Value, Source>>
1312 Gen compose(const GenImpl<Value, Source>& source) const {
1313 return Gen(source.self());
1318 * RangeConcat - For flattening generators of iterables.
1320 * This type is usually used through the 'rconcat' static value, like:
1322 * map<int, vector<int>> adjacency;
1329 class RangeConcat : public Operator<RangeConcat> {
1331 template<class Source,
1333 class InnerValue = typename ValueTypeOfRange<Range>::RefType>
1335 : public GenImpl<InnerValue, Generator<Source, Range, InnerValue>> {
1338 explicit Generator(Source source)
1339 : source_(std::move(source)) {}
1341 template<class Body>
1342 void foreach(Body&& body) const {
1343 source_.foreach([&](Range range) {
1344 for (auto& value : range) {
1350 template<class Handler>
1351 bool apply(Handler&& handler) const {
1352 return source_.apply([&](Range range) {
1353 for (auto& value : range) {
1354 if (!handler(value)) {
1363 template<class Value,
1365 class Gen = Generator<Source, Value>>
1366 Gen compose(GenImpl<Value, Source>&& source) const {
1367 return Gen(std::move(source.self()));
1370 template<class Value,
1372 class Gen = Generator<Source, Value>>
1373 Gen compose(const GenImpl<Value, Source>& source) const {
1374 return Gen(source.self());
1381 * VirtualGen<T> - For wrapping template types in simple polymorphic wrapper.
1383 template<class Value>
1384 class VirtualGen : public GenImpl<Value, VirtualGen<Value>> {
1387 virtual ~WrapperBase() {}
1388 virtual bool apply(const std::function<bool(Value)>& handler) const = 0;
1389 virtual void foreach(const std::function<void(Value)>& body) const = 0;
1390 virtual std::unique_ptr<const WrapperBase> clone() const = 0;
1393 template<class Wrapped>
1394 class WrapperImpl : public WrapperBase {
1397 explicit WrapperImpl(Wrapped wrapped)
1398 : wrapped_(std::move(wrapped)) {
1401 virtual bool apply(const std::function<bool(Value)>& handler) const {
1402 return wrapped_.apply(handler);
1405 virtual void foreach(const std::function<void(Value)>& body) const {
1406 wrapped_.foreach(body);
1409 virtual std::unique_ptr<const WrapperBase> clone() const {
1410 return std::unique_ptr<const WrapperBase>(new WrapperImpl(wrapped_));
1414 std::unique_ptr<const WrapperBase> wrapper_;
1417 template<class Self>
1418 /* implicit */ VirtualGen(Self source)
1419 : wrapper_(new WrapperImpl<Self>(std::move(source)))
1422 VirtualGen(VirtualGen&& source)
1423 : wrapper_(std::move(source.wrapper_))
1426 VirtualGen(const VirtualGen& source)
1427 : wrapper_(source.wrapper_->clone())
1430 VirtualGen& operator=(const VirtualGen& source) {
1431 wrapper_.reset(source.wrapper_->clone());
1435 VirtualGen& operator=(VirtualGen&& source) {
1436 wrapper_= std::move(source.wrapper_);
1440 bool apply(const std::function<bool(Value)>& handler) const {
1441 return wrapper_->apply(handler);
1444 void foreach(const std::function<void(Value)>& body) const {
1445 wrapper_->foreach(body);
1450 * non-template operators, statically defined to avoid the need for anything but
1453 static const detail::Sum sum;
1455 static const detail::Count count;
1457 static const detail::First first;
1459 static const detail::Any any;
1461 static const detail::Min<Identity, Less> min;
1463 static const detail::Min<Identity, Greater> max;
1465 static const detail::Order<Identity> order;
1467 static const detail::Map<Move> move;
1469 static const detail::Concat concat;
1471 static const detail::RangeConcat rconcat;
1473 inline detail::Take take(size_t count) {
1474 return detail::Take(count);
1477 inline detail::Skip skip(size_t count) {
1478 return detail::Skip(count);
1481 }} //folly::gen::detail