alan icon indicating copy to clipboard operation
alan copied to clipboard

Class Syntactic Sugar

Open depombo opened this issue 4 years ago • 0 comments

Building on the interface change in #13 there could be a class syntactic sugar:

export class Foo {
  fieldA: string
  fieldB: int64

  fn doStuff(): string {
    return this.fieldA * this.fieldB
  }
  fn merge(other: Foo): Foo {
    return new Foo {
      fieldA: this.fieldA + other.fieldA
      fieldB: this.fieldB * other.fieldB
    }
  }
  infix associative 2 & merge
}

This could be syntactic sugar for:

export type foo {
  fieldA: string
  fieldB: int64
}

export fn doStuff(this: Foo): string {
  return this.fieldA * this.fieldB
}

export fn merge(this: Foo, other: Foo): Foo {
  return new Foo {
    fieldA: this.fieldA + other.fieldA
    fieldB: this.fieldB * other.fieldB
  }
}
export infix associative 2 & merge

export interface Foo {
  fieldA: string
  fieldB: int64
  fn doStuff(Foo): string
  fn merge(Foo, Foo): Foo
  Foo & Foo
}

For this to work, there would be one more change needed. If trying to call new <interface> it should succeed if and only if the interface matches a single type.

Private fields and functions could be simulated by a second type that is not exported and functions not included in the interface nor exported:

export class Bar {
  foo: Foo
  private blah: int64

  fn getBlah(): int64 {
    return this.blah
  }
  fn somethingElse(): bool {
    return this.foo.fieldB > 5 && this.privateCall()
  }
  private fn privateCall(): bool {
    return this.blah * 2 < 10
  }
}

could become something like

export type bar {
  foo: Foo
  privateFields: privateBar
}
type privateBar {
  blah: int64
}
export fn getBlah(this: Bar): int64 {
  return this.privateFields.blah
}
export fn somethingElse(this: Bar): bool {
  return this.foo.fieldB > 5 && this.privateCall()
}
fn privateCall(this: Bar): bool {
  return this.privateFields.blah * 2 < 10
}
export interface Bar {
  foo: Foo
  fn getBlah(Bar): int64
  fn somethingElse(Bar): bool
}

depombo avatar May 28 '20 00:05 depombo