Menu

#42 Pattern Matching

open
nobody
None
5
2005-08-20
2005-08-20
No

my proposed match keyword didn't really click, so I am
trying something similar.
for completeness, here is my proposed syntax for match
(which was originally meant to replace value dispatch):

match(anObject) {
case null: // if the object can have null value
case anotherObject: // checks if they point to the
same object, useful for enumerations
case SomeClass c: // this is an instanceof
checking, c is the same object as an instance of SomeClass
case SomecClass c, c.someProperty() ==
somethingElse: // an even exhaustive check
case _: // the default case
}

I suggested that there could be a tuple syntax for it,
to reduce complicated if-else nestings.

here is an alternative proposition. this one basically
provides a way for an object to have a useful tuple
representation for pattern matching.

in class Complex, for example:
match Complex(double real) {
if(this.imaginary != 0)
throw new PatternMatchFailedException();
return (this.real);
}

match Complex(double real, double imaginary) =
(this.real, this.imaginary);

to be used like this:
double magnitude(Complex c);
magnitude(Complex(double real)) = Math.abs(real);
magnitude(Complex(0, double imaginary) =
Math.abs(imaginary);
magnitude(Complex(double real, double imaginary)) =
Math.sqrt(real*real + imaginary*imaginary);

or
realPart(Complex(double real, _)) = real;

note that matching this way, much of the getXXX()
methods can be omitted by giving the accessed property
a name. the compiler can decide which elements of the
tuple are actually needed and store it in variables for
later use. I think this construct goes very well with
the Nice philosophy in general.

regards (I'm ashamed, but cannot help thinking of ways
to reduce the pains of a Java programmer)
Imam Tashdid ul Alam

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.