digitalmars.D.learn - C++ to D - recursion with std.variant
- Dennis Ritchie (47/47) Apr 03 2015 Hi,
- thedeemon (6/8) Apr 05 2015 Using Algebraic from std.variant and some additional templates:
- Dennis Ritchie (2/10) Apr 05 2015 Thanks.
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
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
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:Thanks.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