-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadvanced.cpp
More file actions
62 lines (56 loc) · 1.94 KB
/
Copy pathadvanced.cpp
File metadata and controls
62 lines (56 loc) · 1.94 KB
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
#include <iostream>
#include <result.hpp>
#include <string>
using Result = cpp_result::Result<int, std::string>;
inline Result Ok(int val) { return Result::Ok(val); }
inline Result Err(std::string err) { return Result::Err(std::move(err)); }
// Parse an int from a string, with error reporting
Result parse_int(const std::string &s) {
try {
return Ok(std::stoi(s));
} catch (...) {
return Err("Invalid integer: " + s);
}
}
// Divide two integers, error if division by zero
Result safe_div(int a, int b) {
if (b == 0)
return Err("Division by zero");
return Ok(a / b);
}
// Compose: parse two strings, divide, and double the result if > 10
Result parse_div_and_double(const std::string &a, const std::string &b) {
int x = TRY(parse_int(a));
int y = TRY(parse_int(b));
return safe_div(x, y)
.and_then([](int v) {
if (v > 10)
return Ok(v * 2);
return Err("Value too small: " + std::to_string(v));
})
.map([y](int v) { return v + y; });
}
cpp_result::Result<int, int> test_ok_err_int(int value) {
if (value < 0)
return cpp_result::Err<int, int>(value);
return cpp_result::Ok<int, int>(value * 2);
}
int main() {
for (auto &&[a, b] : {std::pair{"40", "2"}, std::pair{"18", "2"},
std::pair{"abc", "2"}, std::pair{"10", "0"}}) {
auto res = parse_div_and_double(a, b);
res.inspect([&](int v) {
std::cout << "Result for (" << a << ", " << b << "): " << v << "\n";
})
.inspect_err([&](const std::string &e) {
std::cout << "Error for (" << a << ", " << b << "): " << e << "\n";
});
}
test_ok_err_int(5)
.inspect([](int v) { std::cout << "Ok value: " << v << "\n"; })
.inspect_err([](int e) { std::cout << "Err value: " << e << "\n"; });
test_ok_err_int(-3)
.inspect([](int v) { std::cout << "Ok value: " << v << "\n"; })
.inspect_err([](int e) { std::cout << "Err value: " << e << "\n"; });
return 0;
}