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?
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.
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.
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)
Rust's enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With