-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathoptional.cpp
More file actions
40 lines (32 loc) · 966 Bytes
/
optional.cpp
File metadata and controls
40 lines (32 loc) · 966 Bytes
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
#include <vector>
#include <iostream>
#include <string>
#include <charconv>
#include <optional>
#include <ranges>
using namespace std;
using namespace literals;
template <typename T>
using vector_ex = vector<optional<T>>;
auto to_int(const string_view s) -> optional<int>
{
if (int r; from_chars(s.data(), s.data()+s.size(), r).ec == errc{})
return r;
return nullopt;
}
int main(int argc, char* argv[])
{
vector_ex<string> v = { "1234", "15 foo", "bar", "42", "5000", " 5" };
// NOTICE
// transform == fmap (map)
// and_then == bind (flatmap)
auto filter = [](auto&& o) { // optional<string>,
return o.and_then(to_int) // bind (or flatmap) from str to int
.transform([](auto n) { return n + 1; })
.transform([](auto n) { return to_string(n); })
.or_else ([] { return optional("null"s); });
};
for (auto&& x : v | views::transform(filter))
cout << *x << '\n';
return 0;
}