Created
November 22, 2014 15:12
-
-
Save TerrorJack/a61e9515a0320e7d4a4b to your computer and use it in GitHub Desktop.
FP-style list in C++11
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 <memory> | |
#include <iostream> | |
template <typename T> | |
struct _list; | |
template <typename T> | |
using list = std::shared_ptr<_list<T>>; | |
template <typename T> | |
struct _list { | |
T car; | |
list<T> cdr; | |
_list(T _car, list<T> _cdr) : car(_car), cdr(_cdr) {} | |
}; | |
template <typename T> | |
list<T> list_cons(T _car, list<T> _cdr) { | |
return std::make_shared<_list<T>>(_list<T>(_car, _cdr)); | |
} | |
template <typename T> | |
list<T> list_add(list<T> a, list<T> b) { | |
if (a) return list_cons<T>(a->car, list_add(a->cdr, b)); | |
return b; | |
} | |
list<char> make_str(const char *s) { | |
if (*s) return list_cons<char>(*s, make_str(s + 1)); | |
return nullptr; | |
} | |
void print_str(list<char> s) { | |
if (s) { | |
std::cout << (s->car); | |
print_str(s->cdr); | |
} | |
} | |
int main() { print_str(list_add(make_str("foo"), make_str("bar"))); } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment