Showing posts from September, 2014

Type switch for Algebrical Data Types in C++11

This is a short post to complete the discussion on Algebrical Data Types in C++11.

An important point for the adoption of Algebrical Data Types (ADTs) is the possibility to perform a select operation based on the active type in an ADT variable. While the use of a class with overloaded function members is practical it is not as clean as it should, in particular if compared with languages with native ADTs.

The syntax in Haskell is:

depth :: Tree -> Int depth Empty =0 depth (Leaf n)=1 depth (Node l r)=1+max(depth l)(depth r) In particular we would like to easily express it in C++ as follows:

sumtype<int,std::string> adt(10);std::cout<<[a](int x) return(int)10+a; },[](std::string w) {return(int)20; }); The select function receives a list of lambda expressions and, at run-time invokes the one whose first argument type matches the active type in the ADT. Thanks to the direct use of lambda expressions everything is inlined by the compiler.

The implementation of the a…