Skip to content

Instantly share code, notes, and snippets.

@dolphin8
Created September 28, 2017 08:01
Show Gist options
  • Save dolphin8/e41bd38a413b8d10b37c80c60a89d1f1 to your computer and use it in GitHub Desktop.
Save dolphin8/e41bd38a413b8d10b37c80c60a89d1f1 to your computer and use it in GitHub Desktop.
list processing in modern c++
#include <utility>
namespace demo {
template <typename Hd, typename Tl>
using cons_t = std::pair<Hd, Tl>;
constexpr auto nil = nullptr;
constexpr auto cons(auto hd, auto tl) {
return std::make_pair(hd, tl);
}
template <typename Hd, typename Tl>
constexpr auto car(const cons_t<Hd, Tl>& c) {
return c.first;
}
template <typename Hd, typename Tl>
constexpr auto cdr(const cons_t<Hd, Tl>& c) {
return c.second;
}
constexpr size_t length(nullptr_t) {
return 0;
}
template <typename Hd, typename Tl>
constexpr size_t length(const cons_t<Hd, Tl>& c) {
return 1 + length(cdr(c));
}
constexpr auto reverse(nullptr_t, const auto& c) {
return c;
}
template <typename Hd, typename Tl, typename R = nullptr_t>
constexpr auto reverse(const cons_t<Hd, Tl>& c, const R& r = nullptr) {
return reverse(c.second, cons(c.first, r));
}
}
using namespace demo;
int main(void) {
constexpr auto a = cons(3.343434, cons("hello", cons(1, nil)));
constexpr auto a_length = length(a);
constexpr auto b = reverse(a);
constexpr auto b_length = length(a);
constexpr auto b_0 = car(b);
return 0;
}
@dolphin8
Copy link
Author

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