Created
November 16, 2018 11:49
-
-
Save nikhedonia/affe439469edc1232b3aac01b38db9ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <optional> | |
struct Unit{}; | |
struct Entry { | |
auto operator()(){ | |
return std::optional<Unit>{}; | |
} | |
}; | |
auto entry = Entry{}; | |
template<class F = decltype(entry)> | |
struct Maybe { | |
F f; | |
template<class G> | |
static auto create(G g){ | |
return Maybe<G>{g}; | |
} | |
template<class G> | |
auto map(G g) { | |
using U = decltype(g(value.value())); | |
auto next = [=]{ | |
auto value = f(); | |
if (value) { | |
return std::optional<U>{g(value.value())}; | |
} else { | |
return std::optional<U>{}; | |
} | |
}; | |
using N = decltype(next); | |
return Maybe<N>{next}; | |
} | |
template<class G> | |
auto flatMap(G g) { | |
using U = decltype(g(value.value())); | |
auto next = [=]{ | |
auto value = f(); | |
if (value) { | |
return g(value.value()); | |
} else { | |
return U{}; | |
} | |
}; | |
using N = decltype(next); | |
return Maybe<N>{next}; | |
} | |
auto run() { | |
return f(); | |
} | |
}; | |
int main() { | |
auto maybe = Maybe<>{}; | |
auto pipeline = maybe.create([]{ | |
return std::optional<int>{1}; | |
}).map([](auto x) { | |
return x+1; | |
}).flatMap([](auto x) { | |
return std::optional<int>(x); | |
}); | |
auto result = pipeline.run(); | |
std::cout << result.value() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment