Skip to content

Instantly share code, notes, and snippets.

View njlr's full-sized avatar
🌏
F# ing

njlr njlr

🌏
F# ing
View GitHub Profile
// And for the caller, the usage changes from this...
try {
float x = sqrt(-1);
std::cout << "sqrt(x) = " << x << std::endl;
} catch(std::string x) {
std::cout << "error occurred: " << x << std::endl;
}
// ... to this...
std::string msg = sqrt(-1)
// This...
float sqrt(float x) {
if (x < 0) {
throw std::string("x should be >= 0");
}
return computeSqrt(x);
}
// ... can be transformed into this...
Either<std::string, float> sqrt(float x) {
Either<string, int> myEither = left("hello"); // constructs a either containing a leftValue;
int count = myEither
.rightMap([](auto num) { return num + 1; }) // adds 1 if rightValue is present
.leftMap([](auto str) { return str + "world"; }) // appends "world" if leftValue is present
.leftMap([](auto str) { return str.size(); })
.join(); // both sides have now the same type, lets join...
template<class Left, class Right>
struct Either {
union {
Left leftValue;
Right rightValue;
};
bool isLeft;
};
int result = compute1(input);
int result2 = compute2(result);
if (has_errors()) {
std::cout << pop_error_message() << std::endl;
}
const int ERROR = 1;
const int SUCCESS = 0;
int compute(int input, int* output) {
if (cond(input)) {
return ERROR;
} else {
*output = computeOutput(input);
return SUCCESS;
}
int foo() throw(int) {
throw "bar";
return 1;
}
int bar() noexcept {
throw 42;
return 1;
}
int compute(int x) noexcept {
return x;
}
int compute(int x) throw(std::exception) {
return x;
}
#include <iostream>
#include <string>
int divide(int x, int y) {
if (y == 0) {
throw std::string("Divide by zero");
}
return x / y;
}
cxx_test(
name = 'add',
srcs = [
'add.cpp',
],
deps = [
'//mathutils:mathutils',
],
)