Types and Sets - Cardinality of Custom type

Hey folks,

I’m learning Elm and trying to understand why do custom types have “Addition” cardinality (instead of multiplication) - as written in the Guide: https://guide.elm-lang.org/appendix/types_as_sets.html.

Let’s say we have Color type defined like this:

type Color
= Red
| White
| Blue

and the Guide claims this:

Cardinality( Result Bool Color ) = cardinality( Bool ) + cardinality( Color ) = 2 + 3 = 5

But to me the cardinality of this type looks to be 6 (multiplication), because I can have 6 possible values:

r1 = Result True Red
r2 = Result True White
r3 = Result True Blue
r4 = Result False Red
r5 = Result False White
r6 = Result False Blue

So I’m surely not getting something here :slight_smile:. I would appreciate your help here. Thanks!

1 Like

The cardinality has to do with values!

Result True Red and the others r{n} you provided don’t have any meaning.

Result is a type constructor (which accepts two concrete types), and Bool and Color are both concrete types. It is defined as such:

Result e a
    = Err e
    | Ok a

Which means it can have Cardinality(e) values possible for the Err value constructor to accept and Cardinality(a) values possible in the case of the Ok value constructor.

Bool has two values : True and False. Same with Color who has three values: Red, White and Blue.

Therefore, Result Bool Color can only have 5 values:

v1 = Err True
v2 = Err False
v3 = Ok Red
v4 = Ok White
v5 = Ok Blue

Hope that makes sens :slight_smile:

4 Likes

Ooh @Punie, now I think I understand (seeing Err and Ok in your example helped me). You (and the Guide) are actually reffering to core Elm package type Result which is defined like this:

type Result error value
    = Ok value
    | Err error

But I was thinking about Result type defined like this:

type Result = Result Bool Color

(which is wrong) :slight_smile:

Thanks again!

1 Like

Oh I see what you mean.

It is not wrong per se to define this type:

type Result = Result Bool Color

but it is isomorphic (ie. equivalent) to a tuple (Bool, Color) and in that case, it is a product type and you are correct in declaring that the cardinality of such a type is Cardinality(Bool) * Cardinality(Color) == 6

3 Likes

Thanks man for clarifying this for me.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.