Pablichjenkov
06/27/2024, 10:51 PMalgebraic data types
?
What's the relationship with algebra?Pablichjenkov
06/28/2024, 12:52 AMFRQDO
06/28/2024, 5:48 AMGoetz Markgraf
06/28/2024, 5:48 AMdata class X(val f1: Int, val f2: Boolean)
you can take all possible values of Int for f1
and multiply it by the possible values if f2
(Boolean = 2).
2. the “sum” types
Kotlin does not really have sum types but the behaviour can be modeled with sealed classes.
Because there can be only one instance of one of the sub classes at a time, the resulting possibilities is not multiplied but added.
Look at the example in Rust (where it is easier to see):
enum SumType {
Unconfirmed(s: String),
Confirmed(s: String),
}
Each value of SumType
can be either Unconfirmed
having a string as payload ‘or’ be Confirmed
also having a string as payload. So the resuling possibilities is not String ‘times’ String but String ‘plus’ String.
Don’t worry, in real life no-one cares about this explanation. It is just that you model different possibilities but with a payload each. Kotlins enum
cannot do that but with sealed class
you can have the same funtionality.
In Languages like Rust, Ocam, F# or Haskell, these types are much easier to describe.Pablichjenkov
06/28/2024, 6:05 AMGoetz Markgraf
06/28/2024, 6:09 AM