mirror of
https://github.com/Nexoniarz/Finch.git
synced 2026-11-03 16:54:25 +00:00
enums and match (in the compiler written in Finch)
enum Color { Red, Green, Blue } enum Status { Ok = 200, NotFound = 404 }
Color.Red, Color(n) (checked), int(c), == and != only, printed by name, usable as
map keys and struct fields, with methods (fn Color.next()).
match value { Red, Green -> ... Blue -> ... else -> ... } as a statement, or as an
expression that gives a value. Works on enums, whole numbers, chars, text and bools;
a match on an enum has to handle every variant or end with else, and says which are
missing. A bare variant name (Red) is enough inside a match on an enum.
Only the self-hosted compiler has them; tests/new holds their tests, tests/run stays what
the C++ compiler also runs. boot.sh: 31 passed.
This commit is contained in:
parent
a5ba4bc8f0
commit
609ceffe58
15 changed files with 576 additions and 18 deletions
75
tests/new/enums.fch
Normal file
75
tests/new/enums.fch
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
enum Color { Red, Green, Blue }
|
||||
enum Status { Ok = 200, NotFound = 404, Teapot = 418 }
|
||||
|
||||
struct Pixel {
|
||||
Color color
|
||||
int x
|
||||
}
|
||||
|
||||
fn Color.warm() -> bool {
|
||||
return self == Color.Red
|
||||
}
|
||||
|
||||
fn Color.next() -> Color {
|
||||
if self == Color.Red {
|
||||
return Color.Green
|
||||
}
|
||||
if self == Color.Green {
|
||||
return Color.Blue
|
||||
}
|
||||
return Color.Red
|
||||
}
|
||||
|
||||
fn describe(Color c) -> str {
|
||||
return match c {
|
||||
Red -> "red"
|
||||
Green -> "green"
|
||||
Blue -> "blue"
|
||||
}
|
||||
}
|
||||
|
||||
fn code(Status s) -> str {
|
||||
match s {
|
||||
Status.Ok -> return "fine"
|
||||
Status.NotFound, Status.Teapot -> return "odd"
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
c := Color.Green
|
||||
print(c, Color.Blue, int(Color.Blue), int(Status.Teapot))
|
||||
print(c == Color.Green, c != Color.Green)
|
||||
print(describe(Color.Red), describe(c.next()), c.warm(), Color.Red.warm())
|
||||
print(code(Status.Ok), code(Status.NotFound))
|
||||
p := Pixel(color: Color.Blue, x: 3)
|
||||
print(p)
|
||||
[]Color all = [Color.Red, Color.Blue]
|
||||
print(all, all.len)
|
||||
for col in all {
|
||||
match col {
|
||||
Color.Red -> print("a red one")
|
||||
else -> print("something else")
|
||||
}
|
||||
}
|
||||
s := Status(404)
|
||||
print(s, Status(200))
|
||||
n := 5
|
||||
kind := match n {
|
||||
1, 2, 3 -> "small"
|
||||
4, 5 -> "medium"
|
||||
else -> "large"
|
||||
}
|
||||
print(kind)
|
||||
word := "two"
|
||||
match word {
|
||||
"one" -> print(1)
|
||||
"two" -> {
|
||||
print(2)
|
||||
print("two!")
|
||||
}
|
||||
else -> print("many")
|
||||
}
|
||||
counts := [Color.Red: 2, Color.Blue: 5]
|
||||
print(counts[Color.Blue], counts)
|
||||
print(str(Color.Green) + "!")
|
||||
}
|
||||
Loading…
Reference in a new issue