Solved: 46 - Expected
This commit is contained in:
@@ -1,20 +1,34 @@
|
||||
#include "expected.hpp"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace cpp23 {
|
||||
|
||||
auto parse_int(const std::string& text) -> std::expected<int, ParseError> {
|
||||
(void)text;
|
||||
if (text.empty()) {
|
||||
return std::unexpected(ParseError::EmptyInput);
|
||||
}
|
||||
try {
|
||||
const auto i = std::stoi(text);
|
||||
return i;
|
||||
}
|
||||
catch (const std::invalid_argument&) {
|
||||
return std::unexpected(ParseError::InvalidNumber);
|
||||
}
|
||||
catch (const std::out_of_range&) {
|
||||
return std::unexpected(ParseError::InvalidNumber);
|
||||
}
|
||||
}
|
||||
|
||||
auto safe_sqrt(int value) -> std::expected<double, std::string> {
|
||||
(void)value;
|
||||
auto safe_sqrt(const int value) -> std::expected<double, std::string> {
|
||||
if (value < 0) {
|
||||
return std::unexpected(std::string{"negative"});
|
||||
}
|
||||
return std::sqrt(value);
|
||||
}
|
||||
|
||||
auto chain_parse_and_double(const std::string& text) -> std::expected<int, ParseError> {
|
||||
(void)text;
|
||||
return std::unexpected(ParseError::InvalidNumber);
|
||||
return parse_int(text).transform([](const auto i) { return i * 2; });
|
||||
}
|
||||
|
||||
} // namespace cpp23
|
||||
|
||||
Reference in New Issue
Block a user