plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


plum-examples/control_flow.plum
b7071c9 1
import std/Str
73b5e55 2
import std/Bool
ca5fd6f 3
import std/Number
b7071c9 4
0fe3528 5
fun loopSum(limit: Int) -> Int =
a271f34 6
  total := 0
a271f34 7
  for i := range limit
0e1801a 8
    if i == 3
0e1801a 9
      continue
0e1801a 10
    if i == 8
0e1801a 11
      break
0e1801a 12
    total = total + i
0e1801a 13
  return total
0e1801a 14
0fe3528 15
fun classify(n: Int) -> Str =
0e1801a 16
  if n < 0
0e1801a 17
    return "negative"
0e1801a 18
  else if n == 0
0e1801a 19
    return "zero"
0e1801a 20
  else
0e1801a 21
    return "positive"
0e1801a 22
0fe3528 23
fun countdown(start: Int) -> Int =
a271f34 24
  i := start
0e1801a 25
  while i > 0
0e1801a 26
    i = i - 1
0e1801a 27
  return i
0e1801a 28
0fe3528 29
fun placeholder() =
0e1801a 30
  todo
0e1801a 31
0fe3528 32
fun checkPositive(n: Int) =
0e1801a 33
  assert n > 0
a43f3af 34
a43f3af 35
# ---- tail-expression and assert regression tests ----
a43f3af 36
a43f3af 37
fun bindExample(n: Int) -> Int =
a43f3af 38
  match n
3a2119e 39
    x => x
a43f3af 40
a43f3af 41
fun abs(n: Int) -> Int =
a43f3af 42
  if n < 0
a43f3af 43
    -n
a43f3af 44
  else
a43f3af 45
    n
a43f3af 46
a43f3af 47
fun classifySign(n: Int) -> Int =
a43f3af 48
  match n
3a2119e 49
    0 => 1
a43f3af 50
    x =>
a43f3af 51
      if x < 0
a43f3af 52
        -1
a43f3af 53
      else
a43f3af 54
        2
a43f3af 55
a43f3af 56
fun describeMagnitude(n: Int) -> Int =
a43f3af 57
  match n
a43f3af 58
    0 =>
a43f3af 59
      return 100
3a2119e 60
    x => x * 2
a43f3af 61
a43f3af 62
enum TailOption =
287b97c 63
  | TailSome(Int)
a43f3af 64
  | TailNone
a43f3af 65
a43f3af 66
fun unwrapTailOr(o: TailOption, default: Int) -> Int =
a43f3af 67
  match o
3a2119e 68
    TailSome(v) => v
3a2119e 69
    TailNone => default
a43f3af 70
a43f3af 71
fun checkPositiveAndReturn(n: Int) -> Int =
a43f3af 72
  assert n > 0
a43f3af 73
  n
a43f3af 74
8de13fd 75
test "tail match without return runs correctly"
8de13fd 76
  assert bindExample(5) == 5
8de13fd 77
8de13fd 78
test "tail if without return runs correctly"
8de13fd 79
  assert abs(-7) == 7
8de13fd 80
8de13fd 81
test "tail if nested inside match arm without return runs correctly"
8de13fd 82
  assert classifySign(-5) == -1
8de13fd 83
8de13fd 84
test "tail match mixing return and bare expr arms runs correctly"
8de13fd 85
  assert describeMagnitude(21) == 42
8de13fd 86
8de13fd 87
test "tail enum match without return runs correctly"
8de13fd 88
  assert unwrapTailOr(TailSome(9), 0) == 9
8de13fd 89
a43f3af 90
test "assert passes through on true"
a9a0147 91
  assert checkPositiveAndReturn(5) == 5