4 ms·
> Ok, so far we have three flags which means we have 23 = 8 possible combinations of flags, but do we really have eight separate legal states? No! It’s a good
by aranchelk 4y ago
> Ok, so far we have three flags which means we have 23 = 8 possible combinations of flags, but do we really have eight separate legal states? No!
It’s a good argument for a custom sum type in place of the booleans.
- gentleman11 4y agoCould you elaborate?
- aranchelk 4y agoSum types let you define a type with a set of fixed possible values (a.k.a. inhabitants). You can define Boolean as a sum type: data Boolean = True | False The pipe character would be read as “or”. Boolean has two inhabitants. True being one, False being another one. 1 + 1 Alternatively, when you have a data structure like the example suggested by the author, it’s a product type with 3 fields, with Booleans inhabiting each (isDynamic, isVisible, and isEnabled), 2 * 2 * 2, 8 inhabitants. The argued criticism of this encoding is that when isEnabled is false, no valid values exist for isDynamic or isVisible. They have no meaning for a disabled object. My earlier definition for Boolean looks like an enum in some languages, but sum types can be more powerful if you’re allowed to define inhabitants with different shapes (curly braces denoting a record with named fields, “::” read as “has type”): data GameObjectStatus = Disabled | EnabledWith {isVisible :: Boolean, isDynamic :: Boolean} Now instead of having 8 inhabitants, you have 5 (a sum of 1 and 4) and they each have a valid conceptual meaning. Languages with algebraic data types (sums and products) like Haskell (and IMO even better PureScript) let you easily define types that have only valid states.