2 * Copyright 2017 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.
18 #define FOLLY_GEN_BASE_H_
24 #include <type_traits>
25 #include <unordered_map>
26 #include <unordered_set>
30 #include <folly/Conv.h>
31 #include <folly/Optional.h>
32 #include <folly/Range.h>
33 #include <folly/Utility.h>
34 #include <folly/gen/Core.h>
37 * Generator-based Sequence Comprehensions in C++, akin to C#'s LINQ
38 * @author Tom Jackson <tjackson@fb.com>
40 * This library makes it possible to write declarative comprehensions for
41 * processing sequences of values efficiently in C++. The operators should be
42 * familiar to those with experience in functional programming, and the
43 * performance will be virtually identical to the equivalent, boilerplate C++
46 * Generator objects may be created from either an stl-like container (anything
47 * supporting begin() and end()), from sequences of values, or from another
48 * generator (see below). To create a generator that pulls values from a vector,
49 * for example, one could write:
51 * vector<string> names { "Jack", "Jill", "Sara", "Tom" };
52 * auto gen = from(names);
54 * Generators are composed by building new generators out of old ones through
55 * the use of operators. These are reminicent of shell pipelines, and afford
56 * similar composition. Lambda functions are used liberally to describe how to
57 * handle individual values:
60 * | mapped([](const fbstring& name) { return name.size(); });
62 * Generators are lazy; they don't actually perform any work until they need to.
63 * As an example, the 'lengths' generator (above) won't actually invoke the
64 * provided lambda until values are needed:
66 * auto lengthVector = lengths | as<std::vector>();
67 * auto totalLength = lengths | sum;
69 * 'auto' is useful in here because the actual types of the generators objects
70 * are usually complicated and implementation-sensitive.
72 * If a simpler type is desired (for returning, as an example), VirtualGen<T>
73 * may be used to wrap the generator in a polymorphic wrapper:
75 * VirtualGen<float> powersOfE() {
76 * return seq(1) | mapped(&expf);
79 * To learn more about this library, including the use of infinite generators,
80 * see the examples in the comments, or the docs (coming soon).
88 template <class First, class Second>
89 auto operator()(const First& first, const Second& second) const ->
90 decltype(first < second) {
91 return first < second;
97 template <class First, class Second>
98 auto operator()(const First& first, const Second& second) const ->
99 decltype(first > second) {
100 return first > second;
107 template <class Value>
108 auto operator()(Value&& value) const ->
109 decltype(std::get<n>(std::forward<Value>(value))) {
110 return std::get<n>(std::forward<Value>(value));
114 template <class Class, class Result>
115 class MemberFunction {
117 typedef Result (Class::*MemberPtr)();
121 explicit MemberFunction(MemberPtr member)
125 Result operator()(Class&& x) const {
126 return (x.*member_)();
129 Result operator()(Class& x) const {
130 return (x.*member_)();
133 Result operator()(Class* x) const {
134 return (x->*member_)();
138 template <class Class, class Result>
139 class ConstMemberFunction{
141 typedef Result (Class::*MemberPtr)() const;
145 explicit ConstMemberFunction(MemberPtr member)
149 Result operator()(const Class& x) const {
150 return (x.*member_)();
153 Result operator()(const Class* x) const {
154 return (x->*member_)();
158 template <class Class, class FieldType>
161 typedef FieldType (Class::*FieldPtr);
165 explicit Field(FieldPtr field)
169 const FieldType& operator()(const Class& x) const {
173 const FieldType& operator()(const Class* x) const {
177 FieldType& operator()(Class& x) const {
181 FieldType& operator()(Class* x) const {
185 FieldType&& operator()(Class&& x) const {
186 return std::move(x.*field_);
192 template <class Value>
193 auto operator()(Value&& value) const ->
194 decltype(std::move(std::forward<Value>(value))) {
195 return std::move(std::forward<Value>(value));
200 * Class and helper function for negating a boolean Predicate
202 template <class Predicate>
209 explicit Negate(Predicate pred)
210 : pred_(std::move(pred))
214 bool operator()(Arg&& arg) const {
215 return !pred_(std::forward<Arg>(arg));
218 template <class Predicate>
219 Negate<Predicate> negate(Predicate pred) {
220 return Negate<Predicate>(std::move(pred));
223 template <class Dest>
226 template <class Value>
227 Dest operator()(Value&& value) const {
228 return Dest(std::forward<Value>(value));
232 template <class Dest>
235 template <class Value>
236 Dest operator()(Value&& value) const {
237 return ::folly::to<Dest>(std::forward<Value>(value));
241 // Specialization to allow String->StringPiece conversion
243 class To<StringPiece> {
245 StringPiece operator()(StringPiece src) const {
250 template <class Key, class Value>
255 template <class Self>
261 template <class Container>
262 struct ValueTypeOfRange {
264 using RefType = decltype(*std::begin(std::declval<Container&>()));
265 using StorageType = typename std::decay<RefType>::type;
274 class Value = typename ValueTypeOfRange<Container>::RefType>
275 class ReferencedSource;
279 class Container = std::vector<typename std::decay<Value>::type>>
282 template <class Value, class SequenceImpl>
285 template <class Value>
288 template <class Value, class Distance>
289 class RangeWithStepImpl;
291 template <class Value>
294 template <class Value, class Distance>
295 class SeqWithStepImpl;
297 template <class Value>
300 template <class Value, class Source>
303 template <class Value>
306 template <class Value>
307 class SingleReference;
309 template <class Value>
315 template <class Predicate>
318 template <class Predicate>
321 template <class Predicate>
328 template <class Rand>
333 template <class Visitor>
336 template <class Selector, class Comparer = Less>
339 template <class Selector>
342 template <class Selector>
345 template <class Operators>
348 template <class Expected>
355 template <bool forever>
367 template <class Seed, class Fold>
372 template <bool result>
375 template <class Reducer>
380 template <class Selector, class Comparer>
383 template <class Container>
387 template <class, class> class Collection = std::vector,
388 template <class> class Allocator = std::allocator>
389 class CollectTemplate;
391 template <class Collection>
394 template <class Value>
395 struct GeneratorBuilder;
397 template <class Needle>
400 template <class Exception, class ErrorHandler>
411 * Polymorphic wrapper
413 template <class Value>
421 class From = detail::ReferencedSource<const Container>>
422 From fromConst(const Container& source) {
423 return From(&source);
426 template <class Container, class From = detail::ReferencedSource<Container>>
427 From from(Container& source) {
428 return From(&source);
433 class Value = typename detail::ValueTypeOfRange<Container>::StorageType,
434 class CopyOf = detail::CopiedSource<Value>>
435 CopyOf fromCopy(Container&& source) {
436 return CopyOf(std::forward<Container>(source));
439 template <class Value, class From = detail::CopiedSource<Value>>
440 From from(std::initializer_list<Value> source) {
447 detail::CopiedSource<typename Container::value_type, Container>>
448 From from(Container&& source) {
449 return From(std::move(source));
454 class Impl = detail::RangeImpl<Value>,
455 class Gen = detail::Sequence<Value, Impl>>
456 Gen range(Value begin, Value end) {
457 return Gen{std::move(begin), Impl{std::move(end)}};
463 class Impl = detail::RangeWithStepImpl<Value, Distance>,
464 class Gen = detail::Sequence<Value, Impl>>
465 Gen range(Value begin, Value end, Distance step) {
466 return Gen{std::move(begin), Impl{std::move(end), std::move(step)}};
471 class Impl = detail::SeqImpl<Value>,
472 class Gen = detail::Sequence<Value, Impl>>
473 Gen seq(Value first, Value last) {
474 return Gen{std::move(first), Impl{std::move(last)}};
480 class Impl = detail::SeqWithStepImpl<Value, Distance>,
481 class Gen = detail::Sequence<Value, Impl>>
482 Gen seq(Value first, Value last, Distance step) {
483 return Gen{std::move(first), Impl{std::move(last), std::move(step)}};
488 class Impl = detail::InfiniteImpl<Value>,
489 class Gen = detail::Sequence<Value, Impl>>
490 Gen seq(Value first) {
491 return Gen{std::move(first), Impl{}};
494 template <class Value, class Source, class Yield = detail::Yield<Value, Source>>
495 Yield generator(Source&& source) {
496 return Yield(std::forward<Source>(source));
500 * Create inline generator, used like:
502 * auto gen = GENERATOR(int) { yield(1); yield(2); };
504 #define GENERATOR(TYPE) \
505 ::folly::gen::detail::GeneratorBuilder<TYPE>() + \
506 [=](const std::function<void(TYPE)>& yield)
509 * empty() - for producing empty sequences.
511 template <class Value>
512 detail::Empty<Value> empty() {
518 class Just = typename std::conditional<
519 std::is_reference<Value>::value,
520 detail::SingleReference<typename std::remove_reference<Value>::type>,
521 detail::SingleCopy<Value>>::type>
522 Just just(Value&& value) {
523 return Just(std::forward<Value>(value));
529 template <class Predicate, class Map = detail::Map<Predicate>>
530 Map mapped(Predicate pred = Predicate()) {
531 return Map(std::move(pred));
534 template <class Predicate, class Map = detail::Map<Predicate>>
535 Map map(Predicate pred = Predicate()) {
536 return Map(std::move(pred));
540 * mapOp - Given a generator of generators, maps the application of the given
541 * operator on to each inner gen. Especially useful in aggregating nested data
544 * chunked(samples, 256)
545 * | mapOp(filter(sampleTest) | count)
548 template <class Operator, class Map = detail::Map<detail::Composer<Operator>>>
549 Map mapOp(Operator op) {
550 return Map(detail::Composer<Operator>(std::move(op)));
554 * member(...) - For extracting a member from each value.
556 * vector<string> strings = ...;
557 * auto sizes = from(strings) | member(&string::size);
559 * If a member is const overridden (like 'front()'), pass template parameter
560 * 'Const' to select the const version, or 'Mutable' to select the non-const
563 * auto heads = from(strings) | member<Const>(&string::front);
571 * These exist because MSVC has problems with expression SFINAE in templates
572 * assignment and comparisons don't work properly without being pulled out
573 * of the template declaration
575 template <MemberType Constness>
578 value = Constness == Const
582 template <MemberType Constness>
583 struct ExprIsMutable {
585 value = Constness == Mutable
590 MemberType Constness = Const,
593 class Mem = ConstMemberFunction<Class, Return>,
594 class Map = detail::Map<Mem>>
595 typename std::enable_if<ExprIsConst<Constness>::value, Map>::type
596 member(Return (Class::*member)() const) {
597 return Map(Mem(member));
601 MemberType Constness = Mutable,
604 class Mem = MemberFunction<Class, Return>,
605 class Map = detail::Map<Mem>>
606 typename std::enable_if<ExprIsMutable<Constness>::value, Map>::type
607 member(Return (Class::*member)()) {
608 return Map(Mem(member));
612 * field(...) - For extracting a field from each value.
614 * vector<Item> items = ...;
615 * auto names = from(items) | field(&Item::name);
617 * Note that if the values of the generator are rvalues, any non-reference
618 * fields will be rvalues as well. As an example, the code below does not copy
619 * any strings, only moves them:
621 * auto namesVector = from(items)
623 * | field(&Item::name)
629 class Field = Field<Class, FieldType>,
630 class Map = detail::Map<Field>>
631 Map field(FieldType Class::*field) {
632 return Map(Field(field));
635 template <class Predicate = Identity, class Filter = detail::Filter<Predicate>>
636 Filter filter(Predicate pred = Predicate()) {
637 return Filter(std::move(pred));
640 template <class Visitor = Ignore, class Visit = detail::Visit<Visitor>>
641 Visit visit(Visitor visitor = Visitor()) {
642 return Visit(std::move(visitor));
645 template <class Predicate, class Until = detail::Until<Predicate>>
646 Until until(Predicate pred = Predicate()) {
647 return Until(std::move(pred));
651 class Selector = Identity,
652 class Comparer = Less,
653 class Order = detail::Order<Selector, Comparer>>
654 Order orderBy(Selector selector = Selector(),
655 Comparer comparer = Comparer()) {
656 return Order(std::move(selector),
657 std::move(comparer));
661 class Selector = Identity,
662 class Order = detail::Order<Selector, Greater>>
663 Order orderByDescending(Selector selector = Selector()) {
664 return Order(std::move(selector));
667 template <class Selector = Identity, class GroupBy = detail::GroupBy<Selector>>
668 GroupBy groupBy(Selector selector = Selector()) {
669 return GroupBy(std::move(selector));
673 class Selector = Identity,
674 class Distinct = detail::Distinct<Selector>>
675 Distinct distinctBy(Selector selector = Selector()) {
676 return Distinct(std::move(selector));
679 template <int n, class Get = detail::Map<Get<n>>>
684 // construct Dest from each value
685 template <class Dest, class Cast = detail::Map<Cast<Dest>>>
690 // call folly::to on each value
691 template <class Dest, class To = detail::Map<To<Dest>>>
696 template <class Value>
697 detail::TypeAssertion<Value> assert_type() {
706 * any() - For determining if any value in a sequence satisfies a predicate.
708 * The following is an example for checking if any computer is broken:
710 * bool schrepIsMad = from(computers) | any(isBroken);
712 * (because everyone knows Schrep hates broken computers).
714 * Note that if no predicate is provided, 'any()' checks if any of the values
715 * are true when cased to bool. To check if any of the scores are nonZero:
717 * bool somebodyScored = from(scores) | any();
719 * Note: Passing an empty sequence through 'any()' will always return false. In
720 * fact, 'any()' is equivilent to the composition of 'filter()' and 'notEmpty'.
722 * from(source) | any(pred) == from(source) | filter(pred) | notEmpty
726 class Predicate = Identity,
727 class Filter = detail::Filter<Predicate>,
728 class NotEmpty = detail::IsEmpty<false>,
729 class Composed = detail::Composed<Filter, NotEmpty>>
730 Composed any(Predicate pred = Predicate()) {
731 return Composed(Filter(std::move(pred)), NotEmpty());
735 * all() - For determining whether all values in a sequence satisfy a predicate.
737 * The following is an example for checking if all members of a team are cool:
739 * bool isAwesomeTeam = from(team) | all(isCool);
741 * Note that if no predicate is provided, 'all()'' checks if all of the values
742 * are true when cased to bool.
743 * The following makes sure none of 'pointers' are nullptr:
745 * bool allNonNull = from(pointers) | all();
747 * Note: Passing an empty sequence through 'all()' will always return true. In
748 * fact, 'all()' is equivilent to the composition of 'filter()' with the
749 * reversed predicate and 'isEmpty'.
751 * from(source) | all(pred) == from(source) | filter(negate(pred)) | isEmpty
754 class Predicate = Identity,
755 class Filter = detail::Filter<Negate<Predicate>>,
756 class IsEmpty = detail::IsEmpty<true>,
757 class Composed = detail::Composed<Filter, IsEmpty>>
758 Composed all(Predicate pred = Predicate()) {
759 return Composed(Filter(std::move(negate(pred))), IsEmpty());
762 template <class Seed, class Fold, class FoldLeft = detail::FoldLeft<Seed, Fold>>
763 FoldLeft foldl(Seed seed = Seed(),
764 Fold fold = Fold()) {
765 return FoldLeft(std::move(seed),
769 template <class Reducer, class Reduce = detail::Reduce<Reducer>>
770 Reduce reduce(Reducer reducer = Reducer()) {
771 return Reduce(std::move(reducer));
774 template <class Selector = Identity, class Min = detail::Min<Selector, Less>>
775 Min minBy(Selector selector = Selector()) {
776 return Min(std::move(selector));
779 template <class Selector, class MaxBy = detail::Min<Selector, Greater>>
780 MaxBy maxBy(Selector selector = Selector()) {
781 return MaxBy(std::move(selector));
784 template <class Collection, class Collect = detail::Collect<Collection>>
790 template <class, class> class Container = std::vector,
791 template <class> class Allocator = std::allocator,
792 class Collect = detail::CollectTemplate<Container, Allocator>>
797 template <class Collection, class Append = detail::Append<Collection>>
798 Append appendTo(Collection& collection) {
799 return Append(&collection);
804 class Contains = detail::Contains<typename std::decay<Needle>::type>>
805 Contains contains(Needle&& needle) {
806 return Contains(std::forward<Needle>(needle));
813 detail::GuardImpl<Exception, typename std::decay<ErrorHandler>::type>>
814 GuardImpl guard(ErrorHandler&& handler) {
815 return GuardImpl(std::forward<ErrorHandler>(handler));
820 class UnwrapOr = detail::UnwrapOr<typename std::decay<Fallback>::type>>
821 UnwrapOr unwrapOr(Fallback&& fallback) {
822 return UnwrapOr(std::forward<Fallback>(fallback));
828 #include <folly/gen/Base-inl.h>