summaryrefslogtreecommitdiff
path: root/Ix/CPP/src/cpplinq/linq.hpp
blob: 6552f79e4e90338dcebccb4bc0db13983ae2cb7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

/// 
/// namespace cpplinq
/// -----------------
///
/// Defines a number of range-based composable operators for enumerating and modifying collections
///
/// The general design philosophy is to 
///   (1) emulate the composable query patterns introduced in C# Linq
///   (2) preserve iterator category and writability where possible
/// For instance, like C# Linq we have a select operator to project one sequence into a new one.
/// Unlike Linq, invoking Select on a random access sequence will yield you a _random_ access sequence.
///
/// The general workflow begins with 'from()' which normally only takes a reference
/// the the collection in question. However, from that point on, all operators function 
/// by value, so that the range can store any necessary state, rather than duplicating it 
/// onto iterator pairs.
/// 
/// In subsequent documentation, "powers" lists which powers that the operator attempts to preserve if
/// available on on the input sequence. Some iterator powers may be skipped - in such a case, round down
/// to the next supported power (e.g. if 'fwd' and 'rnd', an input of 'bidi' will round down to a 'fwd' result). 
/// 
///  
///
/// class linq_query
/// ----------------
/// 
/// from(container&)
/// ================
/// -   Result: Query
/// 
/// Construct a new query, from an lvalue reference to a collection. Does not copy the collection
/// 
/// 
/// 
/// from(iter, iter)
/// ================
/// -   Result: Query
/// 
/// Construct a new query, from an iterator pair.
/// 
/// 
/// 
/// query.select(map)
/// ==========================
/// -   Result: Query 
/// -   Powers: input, forward, bidirectional, random access
/// 
/// For each element `x` in the input sequences, computes `map(x)` for the result sequence.
/// 
/// 
/// 
/// query.where(pred) -> query
/// ==========================
/// -   Result: Query
/// -   Powers: input, forward, bidirectional
/// 
/// Each element `x` in the input appears in the output if `pred(x)` is true.
/// 
/// The expression `pred(x)` is evaluated only when moving iterators (op++, op--). 
/// Dereferencing (op*) does not invoke the predicate.
/// 
/// 
/// 
/// query.groupby(keymap [, keyequal])
/// ====================================
/// Result: Query of groups. Each group has a 'key' field, and is a query of elements from the input.
/// Powers: forward
/// 
/// 
/// 
/// query.any([pred])
/// =================
/// -   Result: bool
/// 
/// (No argument) Returns true if sequence is non-empty. Equivalent to `query.begin()!=query.end()`
/// 
/// (One argument) Returns true if the sequence contains any elements for which `pred(element)` is true.
/// Equivalent to `query.where(pred).any()`.
/// 
/// 
/// 
/// query.all(pred)
/// ===============
/// -   Result: bool
/// 
/// Returns true if `pred` holds for all elements in the sequence. Equivalent to `!query.any(std::not1(pred))`
/// 
/// 
/// 
/// query.take(n)
/// =============
/// -   Result: query
/// -   Powers: input, forward, random access (not bidirectional)
/// 
/// Returns a sequence that contains up to `n` items from the original sequence. 
/// 
/// 
/// 
/// query.skip(n)
/// =============
/// -   Result: query
/// -   Powers: input, forward, random access (not bidirectional)
/// 
/// Returns a sequence that skips the first `n` items from the original sequence, or an empty sequence if 
/// fewer than `n` were available on input.
/// 
/// Note: begin() takes O(n) time when input iteration power is weaker than random access.
/// 
/// 
/// 
/// query.count([pred])
/// ===================
/// -   Result: std::size_t
/// 
/// _TODO: should use inner container's iterator distance type instead._
/// 
/// (Zero-argument) Returns the number of elements in the range. 
/// Equivalent to `std::distance(query.begin(), query.end())`
/// 
/// (One-argument) Returns the number of elements for whicht `pred(element)` is true.
/// Equivalent to `query.where(pred).count()`
/// 
 


#if !defined(CPPLINQ_LINQ_HPP)
#define CPPLINQ_LINQ_HPP
#pragma once

#pragma push_macro("min")
#pragma push_macro("max")
#undef min
#undef max

#include <functional>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <list>
#include <map>
#include <set>
#include <memory>
#include <utility>
#include <type_traits>
#include <vector>
#include <cstddef>



// some configuration macros
#if _MSC_VER > 1600 || __cplusplus > 199711L
#define LINQ_USE_RVALUEREF 1
#endif

#if (defined(_MSC_VER) && _CPPRTTI) || !defined(_MSC_VER)
#define LINQ_USE_RTTI 1
#endif

#if defined(__clang__)
#if __has_feature(cxx_rvalue_references)
#define LINQ_USE_RVALUEREF 1
#endif
#if __has_feature(cxx_rtti)
#define LINQ_USE_RTTI 1
#endif
#endif


// individual features 
#include "util.hpp"
#include "linq_cursor.hpp"
#include "linq_iterators.hpp"
#include "linq_select.hpp"
#include "linq_take.hpp"
#include "linq_skip.hpp"
#include "linq_groupby.hpp"
#include "linq_where.hpp"
#include "linq_last.hpp"
#include "linq_selectmany.hpp"




namespace cpplinq 
{

namespace detail
{
    template<class Pred>
    struct not1_{
        Pred pred;
        not1_(Pred p) : pred(p) 
        {}
        template<class T>
        bool operator()(const T& value)
        {
            return !pred(value);
        }
    };
    // note: VC2010's std::not1 doesn't support lambda expressions. provide our own.
    template<class Pred>
    not1_<Pred> not1(Pred p) { return not1_<Pred>(p); }
}

namespace detail {
    template <class U>
    struct cast_to {
        template <class T>
        U operator()(const T& value) const {
            return static_cast<U>(value);
        }
    };
}

template <class Collection>
class linq_driver
{
    typedef typename Collection::cursor::element_type
        element_type;
    typedef typename Collection::cursor::reference_type
        reference_type;
public:
    typedef cursor_iterator<typename Collection::cursor>
        iterator;

    linq_driver(Collection c) : c(c) {}


    // -------------------- linq core methods --------------------

    template <class KeyFn>
    linq_driver< linq_groupby<Collection, KeyFn> > groupby(KeyFn fn)
    {
        return linq_groupby<Collection, KeyFn>(c, std::move(fn) );
    }

    // TODO: groupby(keyfn, eq)

    // TODO: join...

    template <class Selector>
    linq_driver< linq_select<Collection, Selector> > select(Selector sel) const {
        return linq_select<Collection, Selector>(c, std::move(sel) );
    }

    template <class Fn>
    linq_driver< linq_select_many<Collection, Fn, detail::default_select_many_selector> > 
        select_many(Fn fn) const 
    {
        return linq_select_many<Collection, Fn, detail::default_select_many_selector>(c, fn, detail::default_select_many_selector());
    }

    template <class Fn, class Fn2>
    linq_driver< linq_select_many<Collection, Fn, Fn2> > select_many(Fn fn, Fn2 fn2) const 
    {
        return linq_select_many<Collection, Fn, Fn2>(c, fn, fn2);
    }

    template <class Predicate>
    linq_driver< linq_where<Collection, Predicate> > where(Predicate p) const {
        return linq_where<Collection, Predicate>(c, std::move(p) );
    }
    

    // -------------------- linq peripheral methods --------------------

    template <class Fn>
    element_type aggregate(Fn fn) const
    {
        auto it = begin();
        if (it == end()) {
            return element_type();
        }
        
        reference_type first = *it;
        return std::accumulate(++it, end(), first, fn);
    }

    template <class T, class Fn>
    T aggregate(T initialValue, Fn fn) const
    {
        return std::accumulate(begin(), end(), initialValue, fn);
    }

    bool any() const { auto cur = c.get_cursor(); return !cur.empty(); }

    template <class Predicate>
    bool any(Predicate p) const {
        auto it = std::find_if(begin(), end(), p);
        return it != end();
    }

    template <class Predicate>
    bool all(Predicate p) const {
        auto it = std::find_if(begin(), end(), detail::not1(p));
        return it == end();
    }

    // TODO: average

#if !defined(__clang__)
    // Clang complains that linq_driver is not complete until the closing brace 
    // so (linq_driver*)->select() cannot be resolved.
    template <class U>
    auto cast() 
    -> decltype(static_cast<linq_driver*>(0)->select(detail::cast_to<U>())) 
    {
        return this->select(detail::cast_to<U>());
    }
#endif

    // TODO: concat

    bool contains(const typename Collection::cursor::element_type& value) const {
        return std::find(begin(), end(), value) != end();
    }

    typename std::iterator_traits<iterator>::difference_type count() const {
        return std::distance(begin(), end());
    }

    template <class Predicate>
    typename std::iterator_traits<iterator>::difference_type count(Predicate p) const {
        auto filtered = this->where(p);
        return std::distance(begin(filtered), end(filtered));
    }

    // TODO: default_if_empty
    
    // TODO: distinct()
    // TODO: distinct(cmp)

    reference_type element_at(std::size_t ix) const {
        auto cur = c.get_cursor();
        while(ix && !cur.empty()) {
            cur.inc();
            --ix;
        }
        if (cur.empty()) { throw std::logic_error("index out of bounds"); }
        else             { return cur.get(); }
    }

    element_type element_at_or_default(std::size_t ix) const {
        auto cur = c.get_cursor();
        while(ix && !cur.empty()) {
            cur.inc();
            -- ix;
        }
        if (cur.empty()) { return element_type(); }
        else             { return cur.get(); }
    }

    bool empty() const {
        return !this->any();
    }

    // TODO: except(second)
    // TODO: except(second, eq)

    reference_type first() const {
        auto cur = c.get_cursor();
        if (cur.empty()) { throw std::logic_error("index out of bounds"); }
        else             { return cur.get(); }
    }

    template <class Predicate>
    reference_type first(Predicate pred) const {
        auto cur = c.get_cursor();
        while (!cur.empty() && !pred(cur.get())) {
            cur.inc();
        }
        if (cur.empty()) { throw std::logic_error("index out of bounds"); }
        else             { return cur.get(); }
    }

    element_type first_or_default() const {
        auto cur = c.get_cursor();
        if (cur.empty()) { return element_type(); }
        else             { return cur.get(); }
    }

    template <class Predicate>
    element_type first_or_default(Predicate pred) const {
        auto cur = c.get_cursor();
        while (!cur.empty() && !pred(cur.get())) {
            cur.inc();
        }
        if (cur.empty()) { return element_type(); }
        else             { return cur.get(); }
    }
    
    // TODO: intersect(second)
    // TODO: intersect(second, eq)

    // note: forward cursors and beyond can provide a clone, so we can refer to the element directly
    typename std::conditional< 
        std::is_convertible<
            typename Collection::cursor::cursor_category,
            forward_cursor_tag>::value,
        reference_type,
        element_type>::type
    last() const 
    {
        return linq_last_(c.get_cursor(), typename Collection::cursor::cursor_category());
    }

    template <class Predicate>
    reference_type last(Predicate pred) const 
    {
        auto cur = c.where(pred).get_cursor();
        return linq_last_(cur, typename decltype(cur)::cursor_category());
    }

    element_type last_or_default() const 
    {
        return linq_last_or_default_(c.get_cursor(), typename Collection::cursor::cursor_category());
    }

    template <class Predicate>
    element_type last_or_default(Predicate pred) const 
    {
        auto cur = c.where(pred).get_cursor();
        return linq_last_or_default_(cur, typename decltype(cur)::cursor_category());
    }

    reference_type max() const
    {
        return max(std::less<element_type>());
    }

    template <class Compare>
    reference_type max(Compare less) const
    {
        auto it = std::max_element(begin(), end(), less);
        if (it == end()) 
            throw std::logic_error("max performed on empty range");

        return *it;
    }

    reference_type min() const
    {
        return min(std::less<element_type>());
    }

    template <class Compare>
    reference_type min(Compare less) const
    {
        auto it = std::min_element(begin(), end(), less);
        if (it == end()) 
            throw std::logic_error("max performed on empty range");

        return *it;
    }

    // TODO: order_by(sel)
    // TODO: order_by(sel, less)
    // TODO: order_by_descending(sel)
    // TODO: order_by_descending(sel, less)

    // TODO: sequence_equal(second)
    // TODO: sequence_equal(second, eq)

    // TODO: single / single_or_default

    linq_driver<linq_skip<Collection>> skip(std::size_t n) const {
        return linq_skip<Collection>(c, n);
    }

    // TODO: skip_while(pred)

    template<typename ITEM = element_type>
    typename std::enable_if<std::is_default_constructible<ITEM>::value, ITEM>::type sum() const {
        ITEM seed{};
        return sum(seed);
    }

    element_type sum(element_type seed) const {
        return std::accumulate(begin(), end(), seed);
    }

    template <typename Selector, typename Result = typename std::result_of<Selector(element_type)>::type>
    typename std::enable_if<std::is_default_constructible<Result>::value, Result>::type sum(Selector sel) const {
        return from(begin(), end()).select(sel).sum();			
    }

    template <typename Selector, typename Result = typename std::result_of<Selector(element_type)>::type>
    Result sum(Selector sel, Result seed) const {
        return from(begin(), end()).select(sel).sum(seed);			
    }

    linq_driver<linq_take<Collection>> take(std::size_t n) const {
        return linq_take<Collection>(c, n);
    }

    // TODO: take_while

    // TODO: then_by / then_by_descending ?

    // TODO: to_...

    // TODO: union(second)
    // TODO: union(eq)

    // TODO: zip
    
    // -------------------- conversion methods --------------------

    std::vector<typename Collection::cursor::element_type> to_vector() const 
    {
        return std::vector<typename Collection::cursor::element_type>(begin(), end());
    }

    std::list<typename Collection::cursor::element_type> to_list() const
    {
        return std::list<typename Collection::cursor::element_type>(begin(), end());
    }

    std::set<typename Collection::cursor::element_type> to_set() const
    {
        return std::set<typename Collection::cursor::element_type>(begin(), end());
    }

    // -------------------- container/range methods --------------------

    iterator begin() const  { auto cur = c.get_cursor(); return !cur.empty() ? iterator(cur) : iterator(); }
    iterator end() const    { return iterator(); }
    linq_driver& operator=(const linq_driver& other) { c = other.c; return *this; }
    template <class TC2> 
    linq_driver& operator=(const linq_driver<TC2>& other) { c = other.c; return *this; }

    typename std::iterator_traits<iterator>::reference
        operator[](std::size_t ix) const {
        return *(begin()+=ix);
    }

    // -------------------- collection methods (leaky abstraction) --------------------

    typedef typename Collection::cursor cursor;
    cursor get_cursor() { return c.get_cursor(); }

    linq_driver< dynamic_collection<typename Collection::cursor::reference_type> >
        late_bind() const
    {
        return dynamic_collection<typename Collection::cursor::reference_type>(c);
    }

private: 
    Collection c;
};
 
// TODO: should probably use reference-wrapper instead? 
template <class TContainer>
linq_driver<iter_cursor<typename util::container_traits<TContainer>::iterator>> from(TContainer& c)
{ 
    auto cur = iter_cursor<typename util::container_traits<TContainer>::iterator>(std::begin(c), std::end(c));
    return cur;
}
template <class T>
const linq_driver<T>& from(const linq_driver<T>& c) 
{ 
    return c; 
}
template <class Iter>
linq_driver<iter_cursor<Iter>> from(Iter start, Iter finish)
{
    return iter_cursor<Iter>(start, finish);
}

template <class TContainer>
linq_driver<TContainer> from_value(const TContainer& c)
{ 
    return linq_driver<TContainer>(c);
}

}

#pragma pop_macro("min")
#pragma pop_macro("max")

#endif // defined(CPPLINQ_LINQ_HPP)