Skip to content

Instantly share code, notes, and snippets.

@kryptt
Last active September 13, 2021 15:54
Show Gist options
  • Save kryptt/82ff63dce6fcd3226f49d7c4108b8cc3 to your computer and use it in GitHub Desktop.
Save kryptt/82ff63dce6fcd3226f49d7c4108b8cc3 to your computer and use it in GitHub Desktop.
fp-in-cpp
#include <tl/expected.hpp>
#include <iostream>
#include <stdexcept>
#include <functional>
#include <variant>
// Logic in modern civilization
template<typename A, typename B>
using And = std::tuple<A, B>;
template<typename A, typename B>
using Or = std::variant<A, B>;
template<typename A, typename B>
using Implies = std::function<B(A)>;
using Raining = int;
using Sunny = float;
using Day = bool;
struct Person {
std::string name;
int age;
};
using Age = int;
Implies<Or<Raining, Sunny>, Day> statement =
[] (std::variant<Raining, Sunny> input) { return false; };
Implies<Person, Age> personHasAge =
[] (Person p) { return p.age; };
struct CypherPair {
int privateKey;
int publicKey;
};
using PrivateKey = int;
using PublicKey = int;
Implies<And<PrivateKey, PublicKey>, CypherPair> cypherPairConsutrctor =
[] (std::tuple<PrivateKey, PublicKey> keys) {
CypherPair r;
r.privateKey = std::get<0>(keys);
r.publicKey = std::get<1>(keys);
return r;
};
template<typename A>
class optional {
public:
bool is_empty;
optional<A> filter(std::function<bool(A)>) {};
optional(bool empty) {
is_empty = empty;
}
};
template<typename A>
class none;
template<typename A>
class some:public optional<A> {
public:
A theValue;
optional<A> filter(std::function<bool(A)> predicate) {
if (predicate(theValue)) return *this;
else return none<A>();
}
some(A value): optional<A>(false), theValue(value) {
}
};
template<typename A>
class none: public optional<A> {
public:
none(): optional<A>(true) {};
optional<A> filter(std::function<bool(A)> predicate) {
return *this;
};
};
optional<int> parse(std::string str) {
try {
return some<int>(std::stoi(str.c_str()));
} catch (std::exception e) {
return none<int>();
}
}
int main() {
/**
string <- parsing
optional<int> <- filtering odd numbers out
optional<int> <- halving
string <- if the number was odd, saying hi oddfellow, otherwise say half your odd fellow is <x> the number.
*/
//auto start = "4";
//auto step1 = parse(start);
//auto step2 = step1.filter([] (int i) { return i % 2 == 1;});
auto res = parse("4")
.filter(funct)
.map(diveByTwo)
.map("say falg your iadd flleow " + a)
.valueOr("hi oodFellow")
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment