erg-lang / erg

A statically typed language compatible with Python
http://erg-lang.org
Apache License 2.0
2.69k stars 55 forks source link

Add `Enum` #269

Open mtshiba opened 1 year ago

mtshiba commented 1 year ago

Currently, there are the following ways to represent Enums.

A = Class()
B = Class {x = Int; y = Int}
E = Class A or B
x = E.new A.new()
_ = match x:
    a: A -> ...
    b: B -> ...

However, this has the following drawbacks:

So I am thinking to add a built-in function called Enum.

E = Enum {
    # All constructors must be public
    .A = ... # a singleton can be defined with `...`
    .B = (Int, Int)
    .C = {x = Int}
}

# Typeof(x) != Nat
x: E = E.A
E.B: (Int, Int) -> E
_ = match x:
   E.A -> ...
   E.B(1, 2) -> ... # constant pattern
   E.B(a, 2) -> ...
   E.B(a, b) -> ...
   E.C{x} -> ...