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