在 Chapel 中使用 class 类型作为字段

Use a class type as field in Chapel

我有以下 Chapel 代码,但似乎效率不高。

class Student {
    var name: string;
    proc init(name:string) {this.name = name;}
}

class GoodStudent : Student {
    var likesToDate: BadStudent; 
    proc init(name:string) {super.init(name=name);}
}

class BadStudent : Student {
    proc init(name:string) {super.init(name=name);}
}

var students: [1..0] Student;

students.push_back(new GoodStudent("baby"));
students.push_back(new GoodStudent("some other girl"));
students.push_back(new BadStudent("patrick swayze"));

for s in students {
    for t in students {
        if t:GoodStudent != nil {
            var tt = t:GoodStudent; 
            writeln(tt.name, " :will date?: ", s.name);
            if s:tt.likesToDate.type  != nil {
                writeln(" ... YES!");
            } else {
                writeln(" ... NO!");
            }
        }
    }
}

我正在使用一个空 GoodStudent 来比较潜在日期的类型。我宁愿将 GoodStudent 类型保留为字段变量。正确的句法是什么才能让宝宝约会并远离角落?

与任何其他变量一样,class 字段可以使用 type 关键字代替 var 来声明,以指定它们表示类型而不是值。 类 和 type 字段是通用的 - class 初始化程序可以在实例化 class 时将字段设置为任何类型。 primer example 演示了在泛型 class 中使用类型字段。

由于 GoodStudent 只对她 likesToDate 的学生类型感兴趣,而不是任何特定实例,因此该字段可以替换为类型字段。类型字段在程序执行期间不会像使用 var 声明的版本那样占用任何内存。

class GoodStudent : Student {
  type likesToDate = BadStudent; 
  proc init(name:string) {super.init(name=name);}
}

然后,可以稍微修改主循环以访问类型字段,而不是通过字段的 .type

for s in students {
  for t in students {
    var tt = t:GoodStudent; 
    if tt != nil {
      writeln(tt.name, " :will date?: ", s.name);
      if s:tt.likesToDate  != nil {
        writeln(" ... YES!");
      } else {
        writeln(" ... NO!");
      }
    }
  }
}