joews / peach

A functional programming language
MIT License
3 stars 0 forks source link

Match expression and function match shorthand #40

Open joews opened 7 years ago

joews commented 7 years ago

Issue to capture ideas about a new match pattern matching expression, and a shorthand for defining a function that matches over all of its arguments.

Right now functions can have several clauses, with pattern matching arguments:

fib =
  0 => 1
  1 => 1
  x => (+ (fib (- x 1)) (fib (- x 2)))

(map fib [0 1 2 3 4 5 6 7 8 9 10])

Sketch for match expression:

// matches don't have to consume all of the parameters
// (although they can't define more clauses than the `match` arguments
match (x, y, z) { 
    (1) -> 2
    (2) -> 3
    (_) -> {
      y = x + 1
      f(y, x - 1)
    }
}

A function could have a match expression body:

f = (x, a, p) -> {      // <- function args
  match (x, a, p) {     // <- match inputs
    (1) -> 2
    (2) -> 3
    (x) -> {
      y = x + 1
      f(y, x - 1)
    }
  }
}

There's a lot of redundancy and it's common for functions to match on all of their arguments, so we could define a shorthand. Some sketches:

f = (x, a, p) -> {
  (1) -> 2
  (2) -> 3
  (x) -> {
    y = x + 1
    f(y, x - 1)
  }
}
// shorter, more like current syntax
f = {
  (1) -> 2
  (2) -> 3
  (x) -> {
    y = x + 1
    f(y, x - 1)
  }
}```

// this is no good because match is an expression. This syntax would apply // matching against local x, a, p rather than defining a new matching function. f = match (x, a, p) { // <-- inputs and args! 1 -> 2 2 -> 3 x -> { y = x + 1 f(y, x - 1) } }