Skip to content

Instantly share code, notes, and snippets.

@graninas
Last active January 26, 2019 11:22
Show Gist options
  • Save graninas/ebc6d27c4dcded7d0898005f9a8e59b3 to your computer and use it in GitHub Desktop.
Save graninas/ebc6d27c4dcded7d0898005f9a8e59b3 to your computer and use it in GitHub Desktop.
C++ constexpr functional programming
#include <iostream>

constexpr int sum (int a, int b)
{
	return a + b;
}

constexpr int ediv (int a, int b)
{
    return b == 0 
        ? 
        : a / b;
}

enum class ResultTag
{
    NoError,
    DivError,
    OtherError
};

struct Expected
{
    ResultTag tag;
    int value;
};

constexpr Expected pure(int value)
{
    return Expected { ResultTag::NoError, value };
}

constexpr Expected otherError()
{
    return Expected { ResultTag::OtherError, 0 };
}

constexpr Expected safeSum(Expected v1, Expected v2)
{
    return (v1.tag == ResultTag::NoError 
                && v2.tag == ResultTag::NoError)
        ? (pure(v1.value + v2.value))
        : otherError();
}

constexpr Expected divError()
{
    return Expected {ResultTag::DivError, 0};
}

constexpr Expected safeDiv(Expected v1, Expected v2)
{
    return v1.tag != ResultTag::NoError
            ? v1
            : v2.tag != ResultTag::NoError
                ? v2
                : v2.value == 0
                    ? divError()
                    : pure(v1.value / v2.value);
}

int main()
{
    constexpr auto a = sum(1,2);
    constexpr auto b = ediv(1,0);

    constexpr auto r1 = safeSum(pure(1), pure(2));
    constexpr auto r2 = safeDiv(r1, pure(0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment