Skip to content

Instantly share code, notes, and snippets.

@LesleyLai
Last active October 26, 2018 18:00
Show Gist options
  • Save LesleyLai/27b1f588ae402fbeedd364c77d3fe007 to your computer and use it in GitHub Desktop.
Save LesleyLai/27b1f588ae402fbeedd364c77d3fe007 to your computer and use it in GitHub Desktop.
Exceptional Monad in C++ with std::optional
#ifndef AND_THEN_HPP
#define AND_THEN_HPP
#include <optional>
#include <functional>
#include <type_traits>
template<typename T1,
typename Func,
typename Input_Type = typename T1::value_type,
typename T2 = std::invoke_result_t<Func, Input_Type>
>
constexpr T2 operator>>(T1 input, Func f) {
static_assert(
std::is_invocable_v<decltype(f), Input_Type>,
"The function passed in must take type (T1::value_type) as its argument"
);
if (!input) return std::nullopt;
else return std::invoke(f, *input);
}
#endif // AND_THEN_HPP
// Example usage
#include <string>
#include <fstream>
#include <iostream>
#include "bind.hpp"
std::optional<std::string> read_file(const char* filename) {
std::ifstream file {filename};
if (!file.is_open()) {
return {};
}
std::string str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
return {str};
}
std::optional<int> opt_stoi(std::string s) {
try {
return std::stoi(s);
} catch(std::invalid_argument e) {
return {};
} catch (std::out_of_range) {
return {};
}
}
template <typename T>
constexpr void print(std::optional<T> val) {
if (val) {
std::cout << *val << '\n';
} else {
std::cerr << "Error\n";
}
}
int main() {
auto x = read_file("exist.txt")
>> opt_stoi
>> [](int n) { return std::make_optional(n + 100); };
print(x);
return 0;
}
@LesleyLai
Copy link
Author

LesleyLai commented May 28, 2018

This snippet implement monadic bind operation that chain functions together without explicitly checking errors. The whole gist is inspired by Phil Nash's talk at North Denver Metro C++ Meetup C++ meetup.

I use optional here because it is in the standard library, Expected should fit the error handling job better since it stores information about why an error happened. I do not think the implementation of this function will change for Expected.

Please forgive me for (abuse?) operator overloading. I use it to enable cleaner client-side code. You can easily rename the function into, for example, and_then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment