www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - C++ to D - recursion with std.variant

reply "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
Hi,
Is it possible to write on D recursion using std.variant?

-----
#include <boost/variant.hpp>
#include <iostream>

struct Nil {};
auto nil = Nil{};

template <typename T>
struct Cons;

template <typename T>
using List = boost::variant<Nil,
boost::recursive_wrapper<Cons<T>>>;

template <typename T>
struct Cons {
	Cons(T val, List<T> list) : head(val), tail(list) {}

	T head;
	List<T> tail;
};

template <typename T>
class length_visitor : public boost::static_visitor<size_t> {
public:
	int operator()(Nil) const {
		return 0;
	}

	int operator()(const Cons<T>& c) const {
		return 1 + length(c.tail);
	}
};

template <typename T>
auto cons(T head, List<T> tail) {
	return List<T>(Cons<T>(head, tail));
}

template <typename T>
auto cons(T head, Nil) {
	return List<T>(Cons<T>(head, List<T>(Nil{})));
}

template <typename T>
size_t length(const List<T>& list) {
	return boost::apply_visitor(length_visitor<T>(), list);
}

int main() {

	auto l = cons(3, cons(2, cons(1, nil)));
	std::cout << length(l) << std::endl; // prints 3

	return 0;
}
-----
http://ideone.com/qBuOvJ
Apr 03 2015
parent reply "thedeemon" <dlang thedeemon.com> writes:
On Friday, 3 April 2015 at 16:46:08 UTC, Dennis Ritchie wrote:
 Hi,
 Is it possible to write on D recursion using std.variant?
Using Algebraic from std.variant and some additional templates: http://dpaste.dzfl.pl/65afd3a7ce52 (taken from this thread: http://forum.dlang.org/thread/yidovyrczgdiveqbaljw forum.dlang.org?page=1 )
Apr 05 2015
parent "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
On Sunday, 5 April 2015 at 09:48:01 UTC, thedeemon wrote:
 On Friday, 3 April 2015 at 16:46:08 UTC, Dennis Ritchie wrote:
 Hi,
 Is it possible to write on D recursion using std.variant?
Using Algebraic from std.variant and some additional templates: http://dpaste.dzfl.pl/65afd3a7ce52 (taken from this thread: http://forum.dlang.org/thread/yidovyrczgdiveqbaljw forum.dlang.org?page=1 )
Thanks.
Apr 05 2015