#970 'with sentence' proposal

jsendra Wed 10 Feb 2010

Working with dynamic type (alternatives based on run-time type) seems cumbersone. I propose a new sentence called with that defines several alternatives and execute a statement sequence depending on the result of a type test.

with (<expr>) 
{
  of <type1>:
    <block1>
  of <type2>:
    <block2>
  ...
  else:
    <defaultBlock>
}

If T3, T2 and T1 are extensions of T0, and we define v as an instance of T0, the statement

with (v) { 
  of T1: S1 
  of T2: S2 
  else:  S3 
}

has the following meaning: if the dynamic type of v is T1, then the statement sequence S1 is executed where v is regarded as if it had the static type T1; else if the dynamic type of v is T2, then S2 is executed where v is regarded as if it had the static type T2; else S3 is executed. If no alternative is satisfied and an else clause is missing the program is aborted.

Example.- Assume Point as a pair x,y and ColorPoint as an extension of Point that adds field c. We define ColorPoint::equals method

actual code

override Bool equals(Obj? p) {
  if (p is Point) {
    pt:=(Point)p
    return x==pt.x && y==pt.y
  }
  else if (p is ColorPoint) {
    pt:=(ColorPoint)p
    return x==pt.x && y==pt.y && c==pt.c
  }
  else	
    return false
}

proposal

override Bool equals(Obj? p) {
  with (p) {
    of Point:      return x==p.x && y==p.y
    of ColorPoint: return x==p.x && y==p.y && c==p.c
    else:          return false
  }
}

I think compiler can easily translate with sentence to actual code, and new proposal is simpler and more secure (ej.- no explicit cast, no new variables) and enhances readability

ivan Wed 10 Feb 2010

I can't see any difference with this code:

switch(p.typeof)
{
  ColorPoint#: //do something
  Point#: //do something
  default: 
}

andy Wed 10 Feb 2010

I can't see any difference with this code

That code won't trap decedent classes. Though this just doesn't come up enough for me to warrant a special syntax over a few if-else statements. A better solution I think is to allow expressions inside the case statements:

switch (p)
{
  case p is ColorPoint:
  case p is Point:
  default:
}

Haven't thought thru the implementation there (and this is probably the pattern-matching stuff) - just floating the idea.

jsendra Wed 10 Feb 2010

It's my fault. I must real all documentation and example code (Definitively, I need more spare time)

helium Wed 10 Feb 2010

What is your fault? You just proposed a typecase statement. I don't see anything wrong with that.

brian Wed 10 Feb 2010

I do want to enhance switch (or another construct) to be more powerful eventually. Not sure we really want to full blown pattern matching (but you never know). But at least for 1.0, I want to keep simple switch as it today.

Login or Signup to reply.