Created
September 8, 2016 07:21
-
-
Save brosenan/6c62975c53725b1253cc868522337913 to your computer and use it in GitHub Desktop.
C++ is a Dynamic, Pure, Functional Programming Language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This gist was created as support material for this post: https://cloudalion.org/2016/09/08/c-is-a-dynamic-pure-functional-programming-language/