Repository navigation
Closed
Labels
language-designChanges to PRQL-the-language
Description
As discussed on Discord, we have a fully functioning switch statement from #1278 thanks to @aljazerzen, and there are a couple of options on how this is done:
Conditions
switch [
score <= 10 -> "low",
score <= 30 -> "medium",
score <= 70 -> "high",
true -> "very high",
]- Advantage — anything is representable in a reasonable way
- This is the current approach in
main
Compare against a value
switch score [
<= 10 -> "low",
<= 30 -> "medium",
<= 70 -> "high",
_ -> "very high",
]- Advantage — visually simpler and more concise (personally I really like the thinking process of "OK we care about
foo, no need to learn that on each subsequent line")- Comparing a single expression to multiple possible values in a very common use of a logic branch like this
- Disadvantages:
- We probably need to adjust our parser to allow
<= fooas a valid expression — does everything become aUnOp? - Representing a full condition is possible but inelegant ("OK we care about
true"??)...sinceswitch true [ score <= 10 -> "low", status == "exempt" -> "exempt", ]status == "exempt"is compared totrue.
- We probably need to adjust our parser to allow
Allow an optional condition
Allow either of these. This seems quite compelling, and there's a track-record from other languages. But there are some tradeoffs:
- We'd need to use a named parameter
switch on:score [ <= 10 -> "low", <= 30 -> "medium", <= 70 -> "high", _ -> "very high", ]
- We still pay the costs of adjusting the parser to alow for
<= 10as a valid expression.- ...or allow for optional positional parameters (which we don't currently do). I'm not entirely opposed to this at some point, though it does make our parameter logic more complicated. Allowing "optional positional parameters with a default of
null" doesn't complicate the language much, but isn't sufficient here, since the optional parameter would come first, meaning we'd need something like multiple dispatch. Type-checking and autocomplete could become much more difficult.
- ...or allow for optional positional parameters (which we don't currently do). I'm not entirely opposed to this at some point, though it does make our parameter logic more complicated. Allowing "optional positional parameters with a default of
Naming
- Most languages call this
switch, e.g. C / Java / etc - Python calls this
match, though also does some level of pattern matching - Kotlin calls this
when
SQL calls this case...when...then, quite the coalition...
Defaults
I rather like the approach of defaulting to null (which is what the current implementation does). We can't have exhaustive pattern matching anyway, so I'm not sure there's much cost.
Metadata
Metadata
Assignees
Labels
language-designChanges to PRQL-the-language
Activity
aljazerzen commentedon Dec 18, 2022
From the proposed syntaxes I like
switch on:the most.An alternative would be a separate
matchstatement:Regarding the parsing problem: we can get around that by using patterns:
We'd have to support ranges for characters, numbers and maybe strings.
max-sixty commentedon Dec 18, 2022
Yes interesting, that does work for lots of cases (similar to rust I guess). What would the semantics be here? "Use
x | in ywherexis the matched value andyis the value on the left side of the match branch"?Because we can't do proper pattern matching, we don't give as much up by having semantics of "just put
xat the beginning of the expression", like:though we could have guards so we get something similar with the slicker syntax of the original suggestion:
(Something I just found with rust — if
xis itself a range2..5, then matching on it won't work, because2..5matches against a range of ints, I guess at the language level, not against the value ofx)Possibly the "closest" option is to allow
switch on:x, do the== 1 -> 'one'option, and then later add amatchstatement. (but no strong view at all — all of these have tradeoffs)aljazerzen commentedon Dec 20, 2022
Yes, the semantics of:
would be the same as of:
I don't like the guard too much, because it's heavy in additional syntax while it could be rewritten into:
Yes, this is not as clear as the "match with if guard", but for now, I think it's enough. I'm not keen on adding too much features that would bloat the language.
snth commentedon Dec 20, 2022
I'm in favour of keeping the current
switchusing conditions because conditions can reference different variables/columns as you fall through the ladder which can be useful (and is allowed by the underlying SQL).I also support introducing a separate
matchstatement for the common case where you want to compare a single column/expression against multiple values/conditions.(Putting thoughts/ideas on
matchsyntax in a separate reply so you can easily downvote/comment on that.)snth commentedon Dec 20, 2022
Would it be possible to extend the match syntax so that it's not just for the
infunction but any function?would be the same as:
Then if any
matchcondition involving_could be rewritten into a lambda, e.g._ > 5becomesfunc _lambda1 _ -> _ > 5then you could writewould become
Of course there's not much gained over simply using
switchwhen yourmatchexpression is simplyxbut when you're matching instead on something like(temp_fahrenheit - 32) / 1.8or more complicated then that is quite a saving.Of course this goes against "not introducing too many features into the language".
snth commentedon Dec 20, 2022
Actually, given that we don't have late binding for functions, I guess my lambda acrobatics above wouldn't work for the common case of
since that would become
Better just to rewrite the expression involving the
_if you were to go that route.aljazerzen commentedon Dec 21, 2022
Interesting "pattern is a function" idea. I really like the functional aspect of it.
Rewriting
_into lambda can be a separate feature that can work in general (and it would be useful in pipelines).We can start with this:
For this to be ergonomic, we'd need a special impl for std.in:
Original example could be rewritten as:
snth commentedon Dec 21, 2022
Cool. The
_lambda syntax is inspired / taken from this fn.py python package.I've used it before and find it a pretty convenient way to write lambdas.
I have some reservations about the naming of the
defaultfunction. I know it's standard to have the catch all clause in switch statements called "default" but given that this would be a globally available function, I worry that it might lead to unforeseen problems elsewhere. (For example I recall another discussion about aggregate functions returning default / identity elements when given of empty lists which would be a conflicting meaning of default.)Some ideas for alternative names:
othercatch_alltrue(if you can have a function and constant with the same name that the compiler disambiguates based on type signature)
or_true(inspired by the Rust
or_elseandand_thentype combinators. Would go with another one calledand_falsewhich always returns false.)If we're going to go with
eqthen we might as well go with all the other standard comparison operators as well (ne,gt,ge,lt,le) which I think are relatively well known from Pythonoperatormodule, Bash Comparison operators, HTML Character Escape Codes.Actually, from looking at your
std.inimplementation, I see you're already catering for ain ..case mapping totrue, so with three extra cases you could probably get the whole thing done with theinfunction:and then the example would be:
I don't know if that would really be my preferred approach from a readability perspective, just saying you're almost there already with what you sketched out.
For comparison the lambda example would look something like the following:
Actually the previous case with just the
infunctions looks pretty neat.in nullis probably the most awkward of the bunch and you could get rid of that by removing the equality case and just forcing people to use a single element list, i.e.snth commentedon Dec 21, 2022
The previous examples don't really showcase the benefits of the functional approach since they are mostly all just range matches which can be done easily with standard comparison operators. However if you had more complicated functions then the approach of matching against function evaluations might really make things more readable, for example something like
aljazerzen commentedon Dec 22, 2022
I see. We can hold off from defining default and use
in ..as you suggested.Sure, I doubt there is any cost to this (unlikely column/table names).
I initially wanted to do this, but it doesn't make much sense to say "match x in null". So I prefer
match x eq null.max-sixty commentedon Dec 24, 2022
Thanks a lot for #1332.
I really like the approach of passing the arg into an implicit function!
I'm trying to think if we can keep the syntax of the simple & most common case of "equal to this value" to be simple. I'm not a great fan of the functional form of the infix operators like
eq— I'm imagining explaining to someone when they have to writeeqrather than==and it being confusing.Maybe there's a rule like "if the line starts with an infix operators such as
==, then the argument is on its left. Otherwise it's passed into an implicit function".I'm reminded of Swift's approach of minimizing syntax where possible and unambiguous — the first half of https://docs.swift.org/swift-book/LanguageGuide/Closures.html
Let me think more over the weekend.
aljazerzen commentedon Dec 24, 2022
That's a valid concern: eq, lte, lt, ... are not ideal.
I don't like having == without left expr, because it's not convenient to parse and introduces new sytnax. Current approach is great on this side: new syntactic constructs are high-level and are composed from normal existing exprs.
Maybe we could have the special rule "if the condition is not a function, just use equals comparison".
With this we'd cover only eq and leave out lt, lte, gt, gte and neq. But eq is most common by far and most of them can be expressed by ´in range´
max-sixty commentedon Dec 25, 2022
Yes this sounds reasonable!
Is there an ambiguity when we want to say "is equal to the result of this function"?
...but possibly that's no big deal, this wouldn't be allowed, instead functions need to be pre-computed in a
derive.Agree, this is completely fine for the
ltetc.neqis an inconvenience but survivable.This is fair, though one thing to note —
==is already a unary operator fromjoin [==id]. But!=&>=& friends would indeed need parsing changes.Something I realized while thinking about this is that Rust also has a small ambiguity:
...fails because ranges are special.
Not to expand the scope of this needlessly — but worth raising that these plans commit us to having
inas a function, rather than an infix operator likeandandor. Do we want that?Whether things like
inorasare infix or functions has no Correct answer — it's the usual tradeoff between convenience and consistency.It's possible to have
inlikex in 5..10. This ingrainsinin the language — it's not possible for standard functions to be infix — but we're already doing that.[Speculative, need to think more]
So maaaybe there's a synthesis of this where
inbecomes infix, and match statements need to start with an infix operator. And either we disallow functions for consistency, force a pipe symbol at the start, or add a pipe symbol implicitly for convenience.aljazerzen commentedon Dec 26, 2022
This is actually a conflict between the two meanings. If use
==columnin match, it this a unary operator or the binary with first arg omitted?If go for "value in match implies equality operator" semantics, we will also have a clash like this: you wouldn't be able to compare functions. But this doesn't make sense anyway, so it's not a problem.
This is true and I don't like its current function signature. The fact that these two are idiomatic is not too appealing:
Another idea is to make all binary operations just normal functions (and maybe unary also).
Like have something like:
This is a major breaking change, because it then requires much more parenthesis:
This is a major inconvenience and also has some problems with resolving, so it more of an example of what we want to stay away from.
Essentially, binary operators are a more convenient, built-in way of calling functions. Their "names" are hardcoded into the parser and usually non-alphabetic symbols (
+,%,<=) but not always (and,or).Our problem right now is "how to call these operators with an implicit argument". And proposed solutions were:
_ == 4,20 remaining items
max-sixty commentedon Jan 24, 2023
Just to respond to this since it's small at the object level but I think bigger at the meta level:
I totally agree, and I very much trust your intentions. I hope my message on how I think we should do voting came across as intended — as an attempt to set some principles.
max-sixty commentedon Jan 24, 2023
So I guess we're down to two options:
->for functions,=>for switch/match=>for both functions and switch/match@aljazerzen the balance may lie with you!
aljazerzen commentedon Jan 24, 2023
I was split between the two options, but in the end I think we should go with "
->for functions,=>for switch/match".I say that because the only downside of more syntax complexity is a negated by the fact that functions will mostly be used by advanced users who won't mind.
max-sixty commentedon Jan 24, 2023
It is decided...

snth commentedon Jan 24, 2023
Some more examples that I've fund recently which I believe support the decision that has been reached.
Similar conventions in other languages
Rust
->: functions=>: matchElixir
->: functions=>: key-value pairs (dictionaries)Julia
->: functions=>: key-value pairs (dictionaries)richb-hanover commentedon Feb 24, 2023
@max-sixty @aljazerzen @snth In the recent Dev Call, I asked about the potential change to the switch / case / match statement syntax/semantics and was met with a collective "gulp!" and a request to discuss it in the next Dev Call.
I have reviewed the discussion in #1286. I have also used the current implementation and think that it's fine allowing arbitrary expressions to the left of the "->" or "=>" (except for the long line problem.)
Are there any substantive issues with syntax/semantics beyond what I read as a mild preference for "fat arrow" (=>) over "skinny arrow" (->) ? Thanks for indulging a newcomer...
aljazerzen commentedon Feb 25, 2023
Collective gulp was there because we didn't want to reopen a discussion that was just closed on something that has just been decided and was based mostly on personal visual preference.
Best case for having fat arrows is this comment, but as with most syntactic decisions, this a subject of personal preference.
richb-hanover commentedon Feb 25, 2023
Oh. I definitely did not intend to re-open a "decided issue." Is this closed, with a plan to use the current
switchsyntax? I will note:Thanks, and sorry...
aljazerzen commentedon Feb 25, 2023
I hope i didn't come across as too dismissive! I'm saying that the matter is very dependent on personal preference and there is no objective "best solution", so these discussions can go on a very long time.
And I don't know why this is still open - the new syntax has been implemented in #1581, which means it should have been released in 0.5. @max-sixty have we forgot to re-apply a revert?
And yes, we can remove experimental note now, unless #1795 yields to any more changes.
richb-hanover commentedon Feb 25, 2023
You were absolutely not dismissive. I'm just trying to understand the decision...
I will note that it still appears that the
switchstatement currently uses->. For example, this works in the 0.5.2 playground:max-sixty commentedon Feb 25, 2023
Erm, yes.
I'm happy to do that now — part of the case for reverts is that we can re-revert quickly..
I'm also happy to resolve #1795 first.
I don't think we should remove experimental until #1795 is resolved
vanillajonathan commentedon Jul 3, 2023
Can you match an integer between 3 and 8?
Can you match a letter between
aandf?Can you match character between 0–9 and
atof?max-sixty commentedon Jul 22, 2023
Any expression! Because it's a
caserather than amatch, it's just running a normal expression for each arm:max-sixty commentedon Jul 22, 2023
I think this is in a good place now, so closing