Skip to content

Instantly share code, notes, and snippets.

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

njlr njlr

🌏
F# ing
View GitHub Profile
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...
// 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) {
// 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)
void* x = createInstance();
int* y = new int();
foo.bar(y);
struct Widget {
 Widget() { cout << "Widget created" << endl; }
  ~Widget() { cout << "Widget destroyed" << endl; }
};
unique_ptr<Widget> createWindow() {
 return make_unique<Widget>();
}
int main() {
struct Texture {
  Texture(string const& path) { cout << "Texture loaded from " << path << endl; }
 ~Texture() { cout<< "Texture destroyed" << endl; }
 
  static shared_ptr<Texture> load(string const& path) {
  return make_shared<Texture>(path)
  }
};
int doSomethingWithTexture(shared_ptr<Texture> const tex);
struct Node {
string name;
weak_ptr<Node> parent;
vector<shared_ptr<Node>> children;
bool hasParent() {
return parent.expired();
}
shared_ptr<Node> getParent() {
struct Tree {
string const name;
value_ptr<Tree> left;
value_ptr<Tree> right;
Tree(
string const& name,
value_ptr<Tree> const& left = value_ptr<Tree>{},
value_ptr<Tree> const& right = value_ptr<Tree>{})
: name{name}
struct Foo {
int bar() {
return ptr->bar();
}
Foo(int x);
// Thanks to value_ptr we get value semantics for free
Foo(Foo const&) = default;
Foo& operator=(Foo const&) = default;
struct Foo::Pimpl {
int x;
int bar() { return ++x; }
};
Foo::Foo(int x)
: ptr{Foo::Pimpl{x}}
{}