-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRange.h
57 lines (51 loc) · 1.61 KB
/
Range.h
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
#ifndef SFL_RANGE_H
#define SFL_RANGE_H
#include <algorithm>
#include "sfl/Maybe.h"
/** Note the terminology 'range' refers to a genericcontainer. Requirements vary,
* but it must have a begin() and end() iterators, and many times a push_back() function.
* std::vector and std::string are good examples for a range.
*/
namespace sfl
{
/**
* elem is the list membership predicate, usually written in infix form, e.g., x `elem` xs.
*/
template<typename A, typename R>
bool elem(const A &elem, const R &range)
{
auto it = std::find(range.begin(),range.end(),elem);
if (it == range.end()) {
return false;
}
return true;
}
/**
* The elemIndex function returns the index of the first element in the given range
* which is equal (by operator==) to the query element, or Nothing if there is no such element.
*/
template<typename A,typename R>
Maybe<size_t> elemIndex(const A &elem, const R &range)
{
auto it = std::find(range.begin(),range.end(),elem);
if (it == range.end()) {
return Nothing();
}
return std::distance(range.begin(),it);
}
/*
* Removes one item from a sorted range.
*/
template<typename R,typename T>
R sortedMinusOne(const R &range, const T &element)
{
auto it = std::lower_bound(range.begin(),range.end(),element);
if (it != range.end() && *it == element) {
auto cr = range;
cr.erase(cr.begin() + std::distance(range.begin(),it));
return std::move(cr);
}
return range;
}
}
#endif