2 * Copyright 2015 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 #ifndef FOLLY_GEN_BASE_H
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/gen/Core.h>
36 * Generator-based Sequence Comprehensions in C++, akin to C#'s LINQ
37 * @author Tom Jackson <tjackson@fb.com>
39 * This library makes it possible to write declarative comprehensions for
40 * processing sequences of values efficiently in C++. The operators should be
41 * familiar to those with experience in functional programming, and the
42 * performance will be virtually identical to the equivalent, boilerplate C++
45 * Generator objects may be created from either an stl-like container (anything
46 * supporting begin() and end()), from sequences of values, or from another
47 * generator (see below). To create a generator that pulls values from a vector,
48 * for example, one could write:
50 * vector<string> names { "Jack", "Jill", "Sara", "Tom" };
51 * auto gen = from(names);
53 * Generators are composed by building new generators out of old ones through
54 * the use of operators. These are reminicent of shell pipelines, and afford
55 * similar composition. Lambda functions are used liberally to describe how to
56 * handle individual values:
59 * | mapped([](const fbstring& name) { return name.size(); });
61 * Generators are lazy; they don't actually perform any work until they need to.
62 * As an example, the 'lengths' generator (above) won't actually invoke the
63 * provided lambda until values are needed:
65 * auto lengthVector = lengths | as<std::vector>();
66 * auto totalLength = lengths | sum;
68 * 'auto' is useful in here because the actual types of the generators objects
69 * are usually complicated and implementation-sensitive.
71 * If a simpler type is desired (for returning, as an example), VirtualGen<T>
72 * may be used to wrap the generator in a polymorphic wrapper:
74 * VirtualGen<float> powersOfE() {
75 * return seq(1) | mapped(&expf);
78 * To learn more about this library, including the use of infinite generators,
79 * see the examples in the comments, or the docs (coming soon).
82 namespace folly { namespace gen {
84 class EmptySequence : public std::exception {
86 virtual const char* what() const noexcept {
87 return "This operation cannot be called on an empty sequence";
95 auto operator()(const First& first, const Second& second) const ->
96 decltype(first < second) {
97 return first < second;
103 template<class First,
105 auto operator()(const First& first, const Second& second) const ->
106 decltype(first > second) {
107 return first > second;
114 template<class Value>
115 auto operator()(Value&& value) const ->
116 decltype(std::get<n>(std::forward<Value>(value))) {
117 return std::get<n>(std::forward<Value>(value));
121 template<class Class,
123 class MemberFunction {
125 typedef Result (Class::*MemberPtr)();
129 explicit MemberFunction(MemberPtr member)
133 Result operator()(Class&& x) const {
134 return (x.*member_)();
137 Result operator()(Class& x) const {
138 return (x.*member_)();
141 Result operator()(Class* x) const {
142 return (x->*member_)();
146 template<class Class,
148 class ConstMemberFunction{
150 typedef Result (Class::*MemberPtr)() const;
154 explicit ConstMemberFunction(MemberPtr member)
158 Result operator()(const Class& x) const {
159 return (x.*member_)();
162 Result operator()(const Class* x) const {
163 return (x->*member_)();
167 template<class Class,
171 typedef FieldType (Class::*FieldPtr);
175 explicit Field(FieldPtr field)
179 const FieldType& operator()(const Class& x) const {
183 const FieldType& operator()(const Class* x) const {
187 FieldType& operator()(Class& x) const {
191 FieldType& operator()(Class* x) const {
195 FieldType&& operator()(Class&& x) const {
196 return std::move(x.*field_);
202 template<class Value>
203 auto operator()(Value&& value) const ->
204 decltype(std::move(std::forward<Value>(value))) {
205 return std::move(std::forward<Value>(value));
211 template<class Value>
212 auto operator()(Value&& value) const ->
213 decltype(std::forward<Value>(value)) {
214 return std::forward<Value>(value);
219 * Class and helper function for negating a boolean Predicate
221 template <class Predicate>
228 explicit Negate(Predicate pred)
229 : pred_(std::move(pred))
233 bool operator()(Arg&& arg) const {
234 return !pred_(std::forward<Arg>(arg));
237 template <class Predicate>
238 Negate<Predicate> negate(Predicate pred) {
239 return Negate<Predicate>(std::move(pred));
242 template <class Dest>
245 template <class Value>
246 Dest operator()(Value&& value) const {
247 return Dest(std::forward<Value>(value));
251 template <class Dest>
254 template <class Value>
255 Dest operator()(Value&& value) const {
256 return ::folly::to<Dest>(std::forward<Value>(value));
260 // Specialization to allow String->StringPiece conversion
262 class To<StringPiece> {
264 StringPiece operator()(StringPiece src) const {
269 template<class Key, class Value>
280 template<class Container>
281 struct ValueTypeOfRange {
283 static Container container_;
285 typedef decltype(*std::begin(container_))
287 typedef typename std::decay<decltype(*std::begin(container_))>::type
295 template<class Container,
296 class Value = typename ValueTypeOfRange<Container>::RefType>
297 class ReferencedSource;
299 template<class Value,
300 class Container = std::vector<typename std::decay<Value>::type>>
303 template<class Value, class SequenceImpl>
306 template <class Value>
309 template <class Value, class Distance>
310 class RangeWithStepImpl;
312 template <class Value>
315 template <class Value, class Distance>
316 class SeqWithStepImpl;
318 template <class Value>
321 template<class Value, class Source>
324 template<class Value>
327 template<class Value>
328 class SingleReference;
330 template<class Value>
336 template<class Predicate>
339 template<class Predicate>
342 template<class Predicate>
354 template<class Selector, class Comparer = Less>
357 template<class Selector>
360 template<class Selector>
363 template<class Operators>
366 template<class Expected>
373 template <bool forever>
391 template <bool result>
394 template<class Reducer>
399 template<class Selector,
403 template<class Container>
406 template<template<class, class> class Collection = std::vector,
407 template<class> class Allocator = std::allocator>
408 class CollectTemplate;
410 template<class Collection>
413 template<class Value>
414 struct GeneratorBuilder;
416 template<class Needle>
419 template<class Exception,
426 * Polymorphic wrapper
428 template<class Value>
434 template<class Container,
435 class From = detail::ReferencedSource<const Container>>
436 From fromConst(const Container& source) {
437 return From(&source);
440 template<class Container,
441 class From = detail::ReferencedSource<Container>>
442 From from(Container& source) {
443 return From(&source);
446 template<class Container,
448 typename detail::ValueTypeOfRange<Container>::StorageType,
449 class CopyOf = detail::CopiedSource<Value>>
450 CopyOf fromCopy(Container&& source) {
451 return CopyOf(std::forward<Container>(source));
454 template<class Value,
455 class From = detail::CopiedSource<Value>>
456 From from(std::initializer_list<Value> source) {
460 template<class Container,
461 class From = detail::CopiedSource<typename Container::value_type,
463 From from(Container&& source) {
464 return From(std::move(source));
467 template<class Value, class Impl = detail::RangeImpl<Value>,
468 class Gen = detail::Sequence<Value, Impl>>
469 Gen range(Value begin, Value end) {
470 return Gen{std::move(begin), Impl{std::move(end)}};
473 template<class Value, class Distance,
474 class Impl = detail::RangeWithStepImpl<Value, Distance>,
475 class Gen = detail::Sequence<Value, Impl>>
476 Gen range(Value begin, Value end, Distance step) {
477 return Gen{std::move(begin), Impl{std::move(end), std::move(step)}};
480 template<class Value, class Impl = detail::SeqImpl<Value>,
481 class Gen = detail::Sequence<Value, Impl>>
482 Gen seq(Value first, Value last) {
483 return Gen{std::move(first), Impl{std::move(last)}};
486 template<class Value, class Distance,
487 class Impl = detail::SeqWithStepImpl<Value, Distance>,
488 class Gen = detail::Sequence<Value, Impl>>
489 Gen seq(Value first, Value last, Distance step) {
490 return Gen{std::move(first), Impl{std::move(last), std::move(step)}};
493 template<class Value, class Impl = detail::InfiniteImpl<Value>,
494 class Gen = detail::Sequence<Value, Impl>>
495 Gen seq(Value first) {
496 return Gen{std::move(first), Impl{}};
499 template<class Value,
501 class Yield = detail::Yield<Value, Source>>
502 Yield generator(Source&& source) {
503 return Yield(std::forward<Source>(source));
507 * Create inline generator, used like:
509 * auto gen = GENERATOR(int) { yield(1); yield(2); };
511 #define GENERATOR(TYPE) \
512 ::folly::gen::detail::GeneratorBuilder<TYPE>() + \
513 [=](const std::function<void(TYPE)>& yield)
516 * empty() - for producing empty sequences.
518 template <class Value>
519 detail::Empty<Value> empty() {
525 class Just = typename std::conditional<
526 std::is_reference<Value>::value,
527 detail::SingleReference<typename std::remove_reference<Value>::type>,
528 detail::SingleCopy<Value>>::type>
529 Just just(Value&& value) {
530 return Just(std::forward<Value>(value));
536 template<class Predicate,
537 class Map = detail::Map<Predicate>>
538 Map mapped(Predicate pred = Predicate()) {
539 return Map(std::move(pred));
542 template<class Predicate,
543 class Map = detail::Map<Predicate>>
544 Map map(Predicate pred = Predicate()) {
545 return Map(std::move(pred));
549 * mapOp - Given a generator of generators, maps the application of the given
550 * operator on to each inner gen. Especially useful in aggregating nested data
553 * chunked(samples, 256)
554 * | mapOp(filter(sampleTest) | count)
557 template<class Operator,
558 class Map = detail::Map<detail::Composer<Operator>>>
559 Map mapOp(Operator op) {
560 return Map(detail::Composer<Operator>(std::move(op)));
564 * member(...) - For extracting a member from each value.
566 * vector<string> strings = ...;
567 * auto sizes = from(strings) | member(&string::size);
569 * If a member is const overridden (like 'front()'), pass template parameter
570 * 'Const' to select the const version, or 'Mutable' to select the non-const
573 * auto heads = from(strings) | member<Const>(&string::front);
581 * These exist because MSVC has problems with expression SFINAE in templates
582 * assignment and comparisons don't work properly without being pulled out
583 * of the template declaration
585 template <MemberType Constness> struct ExprIsConst {
587 value = Constness == Const
591 template <MemberType Constness> struct ExprIsMutable {
593 value = Constness == Mutable
597 template<MemberType Constness = Const,
600 class Mem = ConstMemberFunction<Class, Return>,
601 class Map = detail::Map<Mem>>
602 typename std::enable_if<ExprIsConst<Constness>::value, Map>::type
603 member(Return (Class::*member)() const) {
604 return Map(Mem(member));
607 template<MemberType Constness = Mutable,
610 class Mem = MemberFunction<Class, Return>,
611 class Map = detail::Map<Mem>>
612 typename std::enable_if<ExprIsMutable<Constness>::value, Map>::type
613 member(Return (Class::*member)()) {
614 return Map(Mem(member));
618 * field(...) - For extracting a field from each value.
620 * vector<Item> items = ...;
621 * auto names = from(items) | field(&Item::name);
623 * Note that if the values of the generator are rvalues, any non-reference
624 * fields will be rvalues as well. As an example, the code below does not copy
625 * any strings, only moves them:
627 * auto namesVector = from(items)
629 * | field(&Item::name)
632 template<class Class,
634 class Field = Field<Class, FieldType>,
635 class Map = detail::Map<Field>>
636 Map field(FieldType Class::*field) {
637 return Map(Field(field));
640 template <class Predicate = Identity,
641 class Filter = detail::Filter<Predicate>>
642 Filter filter(Predicate pred = Predicate()) {
643 return Filter(std::move(pred));
646 template<class Predicate,
647 class Until = detail::Until<Predicate>>
648 Until until(Predicate pred = Predicate()) {
649 return Until(std::move(pred));
652 template<class Selector = Identity,
653 class Comparer = Less,
654 class Order = detail::Order<Selector, Comparer>>
655 Order orderBy(Selector selector = Selector(),
656 Comparer comparer = Comparer()) {
657 return Order(std::move(selector),
658 std::move(comparer));
661 template<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,
668 class GroupBy = detail::GroupBy<Selector>>
669 GroupBy groupBy(Selector selector = Selector()) {
670 return GroupBy(std::move(selector));
673 template<class Selector = Identity,
674 class Distinct = detail::Distinct<Selector>>
675 Distinct distinctBy(Selector selector = Selector()) {
676 return Distinct(std::move(selector));
680 class Get = detail::Map<Get<n>>>
685 // construct Dest from each value
686 template <class Dest,
687 class Cast = detail::Map<Cast<Dest>>>
692 // call folly::to on each value
693 template <class Dest,
694 class To = detail::Map<To<Dest>>>
699 template<class Value>
700 detail::TypeAssertion<Value> assert_type() {
709 * any() - For determining if any value in a sequence satisfies a predicate.
711 * The following is an example for checking if any computer is broken:
713 * bool schrepIsMad = from(computers) | any(isBroken);
715 * (because everyone knows Schrep hates broken computers).
717 * Note that if no predicate is provided, 'any()' checks if any of the values
718 * are true when cased to bool. To check if any of the scores are nonZero:
720 * bool somebodyScored = from(scores) | any();
722 * Note: Passing an empty sequence through 'any()' will always return false. In
723 * fact, 'any()' is equivilent to the composition of 'filter()' and 'notEmpty'.
725 * from(source) | any(pred) == from(source) | filter(pred) | notEmpty
728 template <class Predicate = Identity,
729 class Filter = detail::Filter<Predicate>,
730 class NotEmpty = detail::IsEmpty<false>,
731 class Composed = detail::Composed<Filter, NotEmpty>>
732 Composed any(Predicate pred = Predicate()) {
733 return Composed(Filter(std::move(pred)), NotEmpty());
737 * all() - For determining whether all values in a sequence satisfy a predicate.
739 * The following is an example for checking if all members of a team are cool:
741 * bool isAwesomeTeam = from(team) | all(isCool);
743 * Note that if no predicate is provided, 'all()'' checks if all of the values
744 * are true when cased to bool.
745 * The following makes sure none of 'pointers' are nullptr:
747 * bool allNonNull = from(pointers) | all();
749 * Note: Passing an empty sequence through 'all()' will always return true. In
750 * fact, 'all()' is equivilent to the composition of 'filter()' with the
751 * reversed predicate and 'isEmpty'.
753 * from(source) | all(pred) == from(source) | filter(negate(pred)) | isEmpty
756 template <class Predicate = Identity,
757 class Filter = detail::Filter<Negate<Predicate>>,
758 class IsEmpty = detail::IsEmpty<true>,
759 class Composed = detail::Composed<Filter, IsEmpty>>
760 Composed all(Predicate pred = Predicate()) {
761 return Composed(Filter(std::move(negate(pred))), IsEmpty());
766 class FoldLeft = detail::FoldLeft<Seed, Fold>>
767 FoldLeft foldl(Seed seed = Seed(),
768 Fold fold = Fold()) {
769 return FoldLeft(std::move(seed),
773 template<class Reducer,
774 class Reduce = detail::Reduce<Reducer>>
775 Reduce reduce(Reducer reducer = Reducer()) {
776 return Reduce(std::move(reducer));
779 template<class Selector = Identity,
780 class Min = detail::Min<Selector, Less>>
781 Min minBy(Selector selector = Selector()) {
782 return Min(std::move(selector));
785 template<class Selector,
786 class MaxBy = detail::Min<Selector, Greater>>
787 MaxBy maxBy(Selector selector = Selector()) {
788 return MaxBy(std::move(selector));
791 template<class Collection,
792 class Collect = detail::Collect<Collection>>
797 template<template<class, class> class Container = std::vector,
798 template<class> class Allocator = std::allocator,
799 class Collect = detail::CollectTemplate<Container, Allocator>>
804 template<class Collection,
805 class Append = detail::Append<Collection>>
806 Append appendTo(Collection& collection) {
807 return Append(&collection);
810 template<class Needle,
811 class Contains = detail::Contains<typename std::decay<Needle>::type>>
812 Contains contains(Needle&& needle) {
813 return Contains(std::forward<Needle>(needle));
816 template<class Exception,
821 typename std::decay<ErrorHandler>::type>>
822 GuardImpl guard(ErrorHandler&& handler) {
823 return GuardImpl(std::forward<ErrorHandler>(handler));
828 #include <folly/gen/Base-inl.h>
830 #endif // FOLLY_GEN_BASE_H