Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern matching #73

Open
liquidev opened this issue Jun 7, 2022 · 0 comments
Open

Pattern matching #73

liquidev opened this issue Jun 7, 2022 · 0 comments
Labels
enhancement New feature or request language feature

Comments

@liquidev
Copy link
Member

liquidev commented Jun 7, 2022

Having a way of matching against a set of destructuring patterns would make the language quite a bit more expressive.

Patterns

The following pattern types should be supported:

  • _ - wildcard pattern. _ becomes a keyword and is used for discarding values in patterns.
  • nil, true, 1, "abc" - literal patterns. For now only constant literals shall be supported
  • abc - variable binding pattern. The variable name can be prefixed with mut to make the variable mutable (see Deep immutability #68)
  • 1 or 2 - or-pattern, matches the left-hand side or the right-hand side

Additional patterns can be added as the language's feature set is expanded with tuples, lists, and dicts.

I also think constraints should be moved over to patterns, as that will allow for easier error checking in a lot of cases.

Assignment

Assignment shall use a pattern instead of an identifier on the left-hand side. If matching fails, a runtime error is produced.

1 = 1  # ok
a = 1  # ok
2 = nil  # error: pattern doesn't match
2 + 1 = 3  # error: invalid pattern - only literals, variables, and or is supported

Failing assignment does not always have to terminate execution, though. To allow for greater expressiveness, in the future we could make a special case for if and while where if the expression is an assignment, failure is considered falsy.

Because assignment is now a "match pattern or fail" operator, having it return a value wouldn't make much sense, so that functionality shall be dropped and nil should be produced instead of the old value stored in a variable.

match expression

A match expression should be introduced as a control flow construct to accompany if. match is comprised of a list of arms, with each arm being pattern -> expression. Arms are newline-separated.

x match
  p1 -> e1
  p2 -> e2
  p3 -> do
    x = 1  # do stuff
    e3
  end
  p4 -> e4
end

We use an infix match to better enable chaining multiple matches together.

@liquidev liquidev added enhancement New feature or request language feature labels Jun 7, 2022
@liquidev liquidev mentioned this issue Jun 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request language feature
Projects
None yet
Development

No branches or pull requests

1 participant