Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++ is a Dynamic, Pure, Functional Programming Language
#include <iostream>
template <typename T>
struct Print {
static void print() {
std::cout << T::val;
}
};
template <int N>
struct Int {
typedef int type;
static const type val = N;
};
//int main() {
// Print<Int<5> >::print();
//}
template <typename A, typename B>
struct Plus {
typedef typename A::type type;
static const type val = A::val + B::val;
};
//int main() {
// Print<Plus<Int<5>, Int<3> > >::print();
//}
struct Nil {
typedef Nil self;
};
template <typename Head, typename Tail>
struct Cons {
typedef Cons<Head, Tail> self;
};
template <typename List>
struct ListSum : public Int<0> {};
template <typename Head, typename Tail>
struct ListSum<Cons<Head, Tail> > : public
Plus<Head, ListSum<typename Tail::self> > {};
typedef Cons<Int<1>, Nil> l1;
typedef Cons<Int<2>, l1> l2;
typedef Cons<Int<3>, l2> l3;
//int main() {
// Print<ListSum<l3> >::print(); // will print 6
//}
template <typename Func, typename Arg>
struct Apply_ {};
template <typename Func, typename Arg>
struct Apply : public
Apply_<typename Func::self, Arg> {};
struct Inc {
typedef Inc self;
};
template <typename Arg>
struct Apply_<Inc, Arg> : public Plus<Arg, Int<1> > {};
template <typename List, typename Func>
struct Map; // Forward definitino of Map
template <typename List, typename Func>
struct Map_ : public List {};
template <typename Head, typename Tail, typename Func>
struct Map_<Cons<Head, Tail>, Func> : public
Cons<Apply<Func, Head>, Map<Tail, Func> > {};
template <typename List, typename Func>
struct Map : public Map_<List, Func>::self {};
template <typename Val>
struct Inf : public Cons<Val, Inf<Val> > {};
int main() {
Print<ListSum<Map<l3, Inc>::self> >::print();
}
@brosenan

This comment has been minimized.

Copy link
Owner

brosenan commented Sep 8, 2016

This gist was created as support material for this post: https://cloudalion.org/2016/09/08/c-is-a-dynamic-pure-functional-programming-language/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment