Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is idiomatic modern C++ for algebraic data types?

Suppose, for example, you want to implement a spreadsheet Cell in C++. A cell can be either a string, a number, or perhaps empty. Ignore other cases, like it being a formula.

In Haskell, you might do something like:

data Cell = CellStr String | CellDbl Double | None 

What is considered the current "best practice" for doing it in C++? Use a union in a structure with a type indicator, or something else?

like image 817
blippy Avatar asked Mar 29 '16 11:03

blippy


People also ask

Does C# have algebraic datatypes?

Pattern matching extensions for C# enable many of the benefits of algebraic data types and pattern matching from functional languages, but in a way that smoothly integrates with the feel of the underlying language. Elements of this approach are inspired by related features in the programming languages F# and Scala.

What is algebraic data type in Java?

In programming languages, it carries a similar meaning. An algebraic data type is a composite containing variables. a composite can further contain other types as variables as well. A recursive type can contain another instance of itself as a variable.

What is algebraic data type in Haskell?

This is a type where we specify the shape of each of the elements. Wikipedia has a thorough discussion. "Algebraic" refers to the property that an Algebraic Data Type is created by "algebraic" operations. The "algebra" here is "sums" and "products": "sum" is alternation ( A | B , meaning A or B but not both)

Does rust have algebraic data types?

Rust's enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell.


1 Answers

struct empty_type {}; using cell_type = boost::variant<std::string, double, empty_type>; 

Then you would do something with the cell with:

boost::apply_visitor(some_visitor(), cell); 
like image 195
Richard Hodges Avatar answered Sep 25 '22 22:09

Richard Hodges