4 ms·
Most language type systems can say AND but relatively few can say OR. For example, Java can say a `Point` has an `x` AND a `y`: class Point { public int x;
by garethrowlands 5y ago
Most language type systems can say AND but relatively few can say OR. For example, Java can say a `Point` has an `x` AND a `y`:
class Point { public int x; public int y; }
...but it can't say a `Point` has _either_ `x` and `y` OR `r` and `theta`. You can simulate it with two classes and a base class/interface but that implies there might be _other_ ways of defining a point... which there really aren't. The Haskell point would be:
data Point = Cartesian { x :: Double, y :: Double } |
Polar { r :: Double, theta :: Double }
- azth 5y agoYou can do the same in Java now with sealed types: sealed interface Point {} record Cartesian(double x, double y) implements Point {} record Polar(double r, double theta) implements Point {}
- gavinray 5y agoWith JDK 18 you even get binding patterns in matches, so you can extract + assign "Point.x"/"Point.y" to variables when matching on them!
- Twisol 5y agoType patterns [1] are still unfortunately in preview (and have been since JDK 17), and record (destructuring) patterns [2] haven't even landed as a preview yet. I hope the latter get at least a preview in JDK 19 [3], but it looks like they've barely even begun the process of targeting JEPs to 19 yet. [1]: https://openjdk.java.net/jeps/420 https://openjdk.java.net/jeps/420 [2]: https://openjdk.java.net/jeps/405 https://openjdk.java.net/jeps/405 [3]: https://openjdk.java.net/projects/jdk/19/ https://openjdk.java.net/projects/jdk/19/
- garethrowlands 5y agoGood point, that's an improvement.
- 3a2d29 5y agoSaying most languages can...etc is leaving the door open for people to comment on their favorite languages that can, so forgive me for this, but Zig can! const MyNumberUnion = union { small: u8, medium: u16, large: u32, } The values of MyNumberUnion can have a small, medium, OR large, but only one of those.