Last active
September 21, 2016 10:04
-
-
Save adishavit/cbc150b1b0eb72953c4e9fbc87bfaf15 to your computer and use it in GitHub Desktop.
Run Time C++ Dependent Type Experiment
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 <string> | |
#include <iostream> | |
#include "optional.hpp" | |
using nonstd::optional; // this is like Maybe. For more complex examples could use variant (discriminated union) | |
class proved_non_zero_maybe | |
{ | |
public: | |
static optional<proved_non_zero_maybe> prove(int v) | |
{ | |
if (0 == v) | |
return {}; | |
return proved_non_zero_maybe(v); | |
} | |
const int val; | |
private: | |
explicit proved_non_zero_maybe(int v) : val(v) {} | |
}; | |
int safer_div(int x, proved_non_zero_maybe y) | |
{ | |
return x / y.val; // look ma, no checks for div by zero | |
} | |
int main() | |
{ | |
int runtime_y; | |
std::cin >> runtime_y; | |
auto y = proved_non_zero_maybe::prove(runtime_y); // this is the proof | |
if (y) // checking the proof | |
std::cout << safer_div(10, y.value()) << std::endl; | |
else | |
std::cout << "Input was zero!" << std::endl; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment