myst-lang / myst

A structured, dynamic, general-purpose language.
http://myst-lang.org
MIT License
119 stars 17 forks source link

Closes #96. Implement `match` expressions #172

Closed faultyserver closed 6 years ago

faultyserver commented 6 years ago

Match expressions are the pattern-matching-oriented answer to case/switch statements in other languages. Most similar to the cond construct from Elixir, these expressions allow users to provide one or more arguments followed by a series of clauses to match the arguments with to conditional execute behavior.

In terms of implementation, match expressions are just syntax sugar for the creation and immediate invocation of an anonymous function with the given arguments.

For example, a match expression such as

match x, y
  ->(true) { }
  ->(false) { }
  ->(*_) { }
end

is simply re-written as

(fn
  ->(true) { }
  ->(false) { }
  ->(*_) { }
end)(x, y)

Match expressions act as a complement to many existing aspects of the language, including when chains, normal functions, anonymous functions, and block parameters. In particular, matches fit into the space where pattern matching is desirable, but the functionality does not warrant a full fledged function definition, and does not need to be movable like a normal anonymous function.

A good example is where a cond from Elixir or case from Ruby would be used: when the same value needs to be checked against multiple patterns to determine the appropriate branch to interpret next.