Primefactor

Primefactor

  • Blog
  • Email
  • Feed
  • Log in

Recent Posts

  • Sum and Product Types
  • Getting LLVM clang working...

Archive

  • August 2024
  • March 2019

August 2024

  • Sum and Product...

    In this post we will discuss sum and product types. Consider the struct X, defined as struct X { A a; B b; }; Here, A and B are also types, but it does not matter what their declarations are. What kind of values can an instance of type X take on? To instantiate an object of type X, we need to supply an instance of type A and an instance of type B. If the total number of different values that A can take on is denoted by \(|A|\), and the total number of different values that B can take on is denoted by \(|B|\), then the total number of values that X can take on is \(|X| = |A| \cdot |B|\). Consider Y defined as using Y = std::variant<A, B>; What kind of values can an instance of type Y take on? To instantiate an object of type Y, we need to supply an instance of type A or an instance of type B. If the total number of different values that A can take on is denoted by \(|A|\), and the total number of different values that B can take on is denoted by \(|B|\), then the total number of values that Y can take on is \(|Y| = |A| + |B|\). Because the total number of different values that X can take on is a product of its fields, we call X a product type. In contrast, we call Y a sum type, because it can only take on as many values as the sum of its constituent types.

    Permanent link to “Sum and Product Types”
Archive of 2019
  • Blog
  • Email
  • Feed
  • Archive
  • Log in
  • Menu