2 * Copyright 2014 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
22 #include <type_traits>
27 #include <unordered_set>
29 #include "folly/Range.h"
30 #include "folly/Optional.h"
31 #include "folly/Conv.h"
32 #include "folly/gen/Core.h"
35 * Generator-based Sequence Comprehensions in C++, akin to C#'s LINQ
36 * @author Tom Jackson <tjackson@fb.com>
38 * This library makes it possible to write declarative comprehensions for
39 * processing sequences of values efficiently in C++. The operators should be
40 * familiar to those with experience in functional programming, and the
41 * performance will be virtually identical to the equivalent, boilerplate C++
44 * Generator objects may be created from either an stl-like container (anything
45 * supporting begin() and end()), from sequences of values, or from another
46 * generator (see below). To create a generator that pulls values from a vector,
47 * for example, one could write:
49 * vector<string> names { "Jack", "Jill", "Sara", "Tom" };
50 * auto gen = from(names);
52 * Generators are composed by building new generators out of old ones through
53 * the use of operators. These are reminicent of shell pipelines, and afford
54 * similar composition. Lambda functions are used liberally to describe how to
55 * handle individual values:
58 * | mapped([](const fbstring& name) { return name.size(); });
60 * Generators are lazy; they don't actually perform any work until they need to.
61 * As an example, the 'lengths' generator (above) won't actually invoke the
62 * provided lambda until values are needed:
64 * auto lengthVector = lengths | as<std::vector>();
65 * auto totalLength = lengths | sum;
67 * 'auto' is useful in here because the actual types of the generators objects
68 * are usually complicated and implementation-sensitive.
70 * If a simpler type is desired (for returning, as an example), VirtualGen<T>
71 * may be used to wrap the generator in a polymorphic wrapper:
73 * VirtualGen<float> powersOfE() {
74 * return seq(1) | mapped(&expf);
77 * To learn more about this library, including the use of infinite generators,
78 * see the examples in the comments, or the docs (coming soon).
81 namespace folly { namespace gen {
83 class EmptySequence : public std::exception {
85 virtual const char* what() const noexcept {
86 return "This operation cannot be called on an empty sequence";
94 auto operator()(const First& first, const Second& second) const ->
95 decltype(first < second) {
96 return first < second;
102 template<class First,
104 auto operator()(const First& first, const Second& second) const ->
105 decltype(first > second) {
106 return first > second;
113 template<class Value>
114 auto operator()(Value&& value) const ->
115 decltype(std::get<n>(std::forward<Value>(value))) {
116 return std::get<n>(std::forward<Value>(value));
120 template<class Class,
122 class MemberFunction {
124 typedef Result (Class::*MemberPtr)();
128 explicit MemberFunction(MemberPtr member)
132 Result operator()(Class&& x) const {
133 return (x.*member_)();
136 Result operator()(Class& x) const {
137 return (x.*member_)();
140 Result operator()(Class* x) const {
141 return (x->*member_)();
145 template<class Class,
147 class ConstMemberFunction{
149 typedef Result (Class::*MemberPtr)() const;
153 explicit ConstMemberFunction(MemberPtr member)
157 Result operator()(const Class& x) const {
158 return (x.*member_)();
161 Result operator()(const Class* x) const {
162 return (x->*member_)();
166 template<class Class,
170 typedef FieldType (Class::*FieldPtr);
174 explicit Field(FieldPtr field)
178 const FieldType& operator()(const Class& x) const {
182 const FieldType& operator()(const Class* x) const {
186 FieldType& operator()(Class& x) const {
190 FieldType& operator()(Class* x) const {
194 FieldType&& operator()(Class&& x) const {
195 return std::move(x.*field_);
201 template<class Value>
202 auto operator()(Value&& value) const ->
203 decltype(std::move(std::forward<Value>(value))) {
204 return std::move(std::forward<Value>(value));
210 template<class Value>
211 auto operator()(Value&& value) const ->
212 decltype(std::forward<Value>(value)) {
213 return std::forward<Value>(value);
217 template <class Dest>
220 template <class Value>
221 Dest operator()(Value&& value) const {
222 return Dest(std::forward<Value>(value));
226 template <class Dest>
229 template <class Value>
230 Dest operator()(Value&& value) const {
231 return ::folly::to<Dest>(std::forward<Value>(value));
235 // Specialization to allow String->StringPiece conversion
237 class To<StringPiece> {
239 StringPiece operator()(StringPiece src) const {
252 template<class Container>
253 struct ValueTypeOfRange {
255 static Container container_;
257 typedef decltype(*std::begin(container_))
259 typedef typename std::decay<decltype(*std::begin(container_))>::type
267 template<class Container,
268 class Value = typename ValueTypeOfRange<Container>::RefType>
269 class ReferencedSource;
271 template<class Value,
272 class Container = std::vector<typename std::decay<Value>::type>>
275 template<class Value, class SequenceImpl>
278 template <class Value>
281 template <class Value, class Distance>
282 class RangeWithStepImpl;
284 template <class Value>
287 template <class Value, class Distance>
288 class SeqWithStepImpl;
290 template <class Value>
293 template<class Value, class Source>
296 template<class Value>
299 template<class Value>
305 template<class Predicate>
308 template<class Predicate>
311 template<class Predicate>
321 template<class Selector, class Comparer = Less>
324 template<class Selector>
327 template<class Operators>
330 template<class Expected>
354 template<class Predicate>
357 template<class Reducer>
362 template<class Selector,
366 template<class Container>
369 template<template<class, class> class Collection = std::vector,
370 template<class> class Allocator = std::allocator>
371 class CollectTemplate;
373 template<class Collection>
376 template<class Value>
377 struct GeneratorBuilder;
379 template<class Needle>
382 template<class Exception,
389 * Polymorphic wrapper
391 template<class Value>
397 template<class Container,
398 class From = detail::ReferencedSource<const Container>>
399 From fromConst(const Container& source) {
400 return From(&source);
403 template<class Container,
404 class From = detail::ReferencedSource<Container>>
405 From from(Container& source) {
406 return From(&source);
409 template<class Container,
411 typename detail::ValueTypeOfRange<Container>::StorageType,
412 class CopyOf = detail::CopiedSource<Value>>
413 CopyOf fromCopy(Container&& source) {
414 return CopyOf(std::forward<Container>(source));
417 template<class Value,
418 class From = detail::CopiedSource<Value>>
419 From from(std::initializer_list<Value> source) {
423 template<class Container,
424 class From = detail::CopiedSource<typename Container::value_type,
426 From from(Container&& source) {
427 return From(std::move(source));
430 template<class Value, class Impl = detail::RangeImpl<Value>,
431 class Gen = detail::Sequence<Value, Impl>>
432 Gen range(Value begin, Value end) {
433 return Gen{std::move(begin), Impl{std::move(end)}};
436 template<class Value, class Distance,
437 class Impl = detail::RangeWithStepImpl<Value, Distance>,
438 class Gen = detail::Sequence<Value, Impl>>
439 Gen range(Value begin, Value end, Distance step) {
440 return Gen{std::move(begin), Impl{std::move(end), std::move(step)}};
443 template<class Value, class Impl = detail::SeqImpl<Value>,
444 class Gen = detail::Sequence<Value, Impl>>
445 Gen seq(Value first, Value last) {
446 return Gen{std::move(first), Impl{std::move(last)}};
449 template<class Value, class Distance,
450 class Impl = detail::SeqWithStepImpl<Value, Distance>,
451 class Gen = detail::Sequence<Value, Impl>>
452 Gen seq(Value first, Value last, Distance step) {
453 return Gen{std::move(first), Impl{std::move(last), std::move(step)}};
456 template<class Value, class Impl = detail::InfiniteImpl<Value>,
457 class Gen = detail::Sequence<Value, Impl>>
458 Gen seq(Value first) {
459 return Gen{std::move(first), Impl{}};
462 template<class Value,
464 class Yield = detail::Yield<Value, Source>>
465 Yield generator(Source&& source) {
466 return Yield(std::forward<Source>(source));
470 * Create inline generator, used like:
472 * auto gen = GENERATOR(int) { yield(1); yield(2); };
474 #define GENERATOR(TYPE) \
475 ::folly::gen::detail::GeneratorBuilder<TYPE>() + \
476 [=](const std::function<void(TYPE)>& yield)
479 * empty() - for producing empty sequences.
481 template<class Value>
482 detail::Empty<Value> empty() {
486 template<class Value>
487 detail::Just<Value> just(Value value) {
488 return detail::Just<Value>(std::move(value));
494 template<class Predicate,
495 class Map = detail::Map<Predicate>>
496 Map mapped(Predicate pred = Predicate()) {
497 return Map(std::move(pred));
500 template<class Predicate,
501 class Map = detail::Map<Predicate>>
502 Map map(Predicate pred = Predicate()) {
503 return Map(std::move(pred));
507 * mapOp - Given a generator of generators, maps the application of the given
508 * operator on to each inner gen. Especially useful in aggregating nested data
511 * chunked(samples, 256)
512 * | mapOp(filter(sampleTest) | count)
515 template<class Operator,
516 class Map = detail::Map<detail::Composer<Operator>>>
517 Map mapOp(Operator op) {
518 return Map(detail::Composer<Operator>(std::move(op)));
522 * member(...) - For extracting a member from each value.
524 * vector<string> strings = ...;
525 * auto sizes = from(strings) | member(&string::size);
527 * If a member is const overridden (like 'front()'), pass template parameter
528 * 'Const' to select the const version, or 'Mutable' to select the non-const
531 * auto heads = from(strings) | member<Const>(&string::front);
538 template<MemberType Constness = Const,
541 class Mem = ConstMemberFunction<Class, Return>,
542 class Map = detail::Map<Mem>>
543 typename std::enable_if<Constness == Const, Map>::type
544 member(Return (Class::*member)() const) {
545 return Map(Mem(member));
548 template<MemberType Constness = Mutable,
551 class Mem = MemberFunction<Class, Return>,
552 class Map = detail::Map<Mem>>
553 typename std::enable_if<Constness == Mutable, Map>::type
554 member(Return (Class::*member)()) {
555 return Map(Mem(member));
559 * field(...) - For extracting a field from each value.
561 * vector<Item> items = ...;
562 * auto names = from(items) | field(&Item::name);
564 * Note that if the values of the generator are rvalues, any non-reference
565 * fields will be rvalues as well. As an example, the code below does not copy
566 * any strings, only moves them:
568 * auto namesVector = from(items)
570 * | field(&Item::name)
573 template<class Class,
575 class Field = Field<Class, FieldType>,
576 class Map = detail::Map<Field>>
577 Map field(FieldType Class::*field) {
578 return Map(Field(field));
581 template<class Predicate,
582 class Filter = detail::Filter<Predicate>>
583 Filter filter(Predicate pred = Predicate()) {
584 return Filter(std::move(pred));
587 template<class Predicate,
588 class All = detail::All<Predicate>>
589 All all(Predicate pred = Predicate()) {
590 return All(std::move(pred));
593 template<class Predicate,
594 class Until = detail::Until<Predicate>>
595 Until until(Predicate pred = Predicate()) {
596 return Until(std::move(pred));
599 template<class Selector,
600 class Comparer = Less,
601 class Order = detail::Order<Selector, Comparer>>
602 Order orderBy(Selector selector = Identity(),
603 Comparer comparer = Comparer()) {
604 return Order(std::move(selector),
605 std::move(comparer));
608 template<class Selector,
609 class Order = detail::Order<Selector, Greater>>
610 Order orderByDescending(Selector selector = Identity()) {
611 return Order(std::move(selector));
614 template<class Selector,
615 class Distinct = detail::Distinct<Selector>>
616 Distinct distinctBy(Selector selector = Identity()) {
617 return Distinct(std::move(selector));
621 class Get = detail::Map<Get<n>>>
626 // construct Dest from each value
627 template <class Dest,
628 class Cast = detail::Map<Cast<Dest>>>
633 // call folly::to on each value
634 template <class Dest,
635 class To = detail::Map<To<Dest>>>
640 template<class Value>
641 detail::TypeAssertion<Value> assert_type() {
650 class FoldLeft = detail::FoldLeft<Seed, Fold>>
651 FoldLeft foldl(Seed seed = Seed(),
652 Fold fold = Fold()) {
653 return FoldLeft(std::move(seed),
657 template<class Reducer,
658 class Reduce = detail::Reduce<Reducer>>
659 Reduce reduce(Reducer reducer = Reducer()) {
660 return Reduce(std::move(reducer));
663 template<class Selector = Identity,
664 class Min = detail::Min<Selector, Less>>
665 Min minBy(Selector selector = Selector()) {
666 return Min(std::move(selector));
669 template<class Selector,
670 class MaxBy = detail::Min<Selector, Greater>>
671 MaxBy maxBy(Selector selector = Selector()) {
672 return MaxBy(std::move(selector));
675 template<class Collection,
676 class Collect = detail::Collect<Collection>>
681 template<template<class, class> class Container = std::vector,
682 template<class> class Allocator = std::allocator,
683 class Collect = detail::CollectTemplate<Container, Allocator>>
688 template<class Collection,
689 class Append = detail::Append<Collection>>
690 Append appendTo(Collection& collection) {
691 return Append(&collection);
694 template<class Needle,
695 class Contains = detail::Contains<typename std::decay<Needle>::type>>
696 Contains contains(Needle&& needle) {
697 return Contains(std::forward<Needle>(needle));
700 template<class Exception,
705 typename std::decay<ErrorHandler>::type>>
706 GuardImpl guard(ErrorHandler&& handler) {
707 return GuardImpl(std::forward<ErrorHandler>(handler));
712 #include "folly/gen/Base-inl.h"
714 #endif // FOLLY_GEN_BASE_H