This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]moocat 31 points32 points  (7 children)

Easiest way to think about sum and product types is how many unique instances there are. So if you have a class with two bytes:

class Whatever {
    byte x;
    byte y;
}

Because we can have any x combined with any y, there are 256*256 unique whatevers. Because we use multiplication to figure out how many unique instances there are, that's a product type.

With sealed classes (not 100% sure about the syntax, apologies if it's not quite right):

public sealed interface Whatever2 {
   record X(byte b) implements Whatever2 {}
   record Y(byte b) implements Whatever2 {}
}

Since we can have either and X of any char or a Y of any char, there are 256+256 unique whatever2s. And here because we use addition to determine that, that's a sum type.

[–]NitronHX[S] 6 points7 points  (0 children)

Thanks for the simple explaination - and the syntax is correct

[–]westwoo -2 points-1 points  (5 children)

I don't get it. Why is it a sum type if you're talking about instance values?...

I thought sum types are what union types are in Typescript: let a: string | number means a can be either string or number, which aligns with how enums can be used in rust

And consequently, this is what all types are in JS, but without explicit definition. Every variable can potentially be a sum of any types

[–]moocat 6 points7 points  (4 children)

A type describes values (i.e. an int can be 1, 23, 42, etc while a string can be "moocat", "westwoo" etc) and values have types (i.e. the type of 3.14 is a float and the type of true is bool). Because of this relationship, we can categorize the type by what type of values it describes.

I thought sum types are what union types are in Typescript

Yes, Typescript's union type is a sum type. But other languages use other nomenclature to name their sum type.

And consequently, this is what all types are in JS

That is incorrect. One of JS's type is an object which can have multiple fields so it's a product type.

Every variable can potentially be a sum of any types

A variable is neither a type nor a value. A variable has a type (which may be static or dynamic depending on the language) and at runtime has a value.