// why is the numbers example a good demonstration of pattern matching? interface Number { boolean equals(Number other); } class Integer implements Number { int x; Integer(int y) { x=y; } public String toString() { return ""+x; } public boolean equals(Number other) { return switch (other) { case Integer n -> x==n.x; case Rational r -> x*r.d == r.n; case Real r -> (double)x==r.r; case Complex c -> c.i==0 && (double)x==c.r; default -> false; }; } } class Rational implements Number { int n; int d; Rational(int a, int b) {n=a;d=b;} public String toString() { return n+"/"+d; } public boolean equals(Number other) { return switch (other) { case Rational R -> n*R.d == d*R.n; case Real R -> n==d*R.r; case Complex C -> C.i==0 && C.r*d==n; default -> other.equals(this); }; } } class Real implements Number { double r; Real(double x) {r=x;} public String toString() { return ""+r; } public boolean equals(Number other) { if (other instanceof Real) { return r==((Real)other).r; } else if (other instanceof Complex) { return ((Complex)other).i==0 && ((Complex)other).r==r; } else return other.equals(this); } } class Complex implements Number { double r; double i; Complex(double a, double b) {r=a; i=b;} public String toString() { return r+"+"+i+"i"; } public boolean equals(Number other) { if (other instanceof Complex C) { return r==C.r && i==C.i; } else return other.equals(this); } } public class numbersattempt { static boolean equals(Integer A, Integer B) { return A.x==B.x; } static boolean equals(Integer A, Rational R) { return A.x*R.d == R.n; } static boolean equals(Integer A, Real R) { return A.x==R.r; } static boolean equals(Integer A, Complex C) { return C.i==0 && A.x==C.r; } static boolean equals(Rational A, Rational B) { return A.n*B.d == A.d*B.n; } // static boolean equals(Number a, Number b) { return equals(b,a); } public static void main(String[] args) { Number[] N = { new Integer(2), new Rational(6,3), new Real(2.5)}; //System.out.println( equals(N[0],N[1]) ); System.out.println(N[2].equals(N[0])); } }