Skip to content

switch / case / match semantics #1286

Closed

Description

@max-sixty

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 <= foo as a valid expression — does everything become a UnOp?
    • Representing a full condition is possible but inelegant ("OK we care about true"??)
      switch true [
        score <= 10 -> "low",
        status == "exempt" -> "exempt",
      ]
      
      ...since status == "exempt" is compared to true.

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 <= 10 as 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.

Naming

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.

Activity

  1. added
    language-design
    on Dec 17, 2022
  2. aljazerzen commented on Dec 18, 2022

    @aljazerzen
    Member

    From the proposed syntaxes I like switch on: the most.

    An alternative would be a separate match statement:

    match x [
       ...
    ]
    

    Regarding the parsing problem: we can get around that by using patterns:

    match x [
        1 -> 'one'
        2..5 -> 'a few',
        5.. -> 'many'
    ]
    

    We'd have to support ranges for characters, numbers and maybe strings.

  3. max-sixty commented on Dec 18, 2022

    @max-sixty
    MemberAuthor

    Regarding the parsing problem: we can get around that by using patterns:

    match x [
        1 -> 'one'
        2..5 -> 'a few',
        5.. -> 'many'
    ]
    

    We'd have to support ranges for characters, numbers and maybe strings.

    Yes interesting, that does work for lots of cases (similar to rust I guess). What would the semantics be here? "Use x | in y where x is the matched value and y is 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 x at the beginning of the expression", like:

    match x [
        == 1 -> 'one'
        | in 2..5 -> 'a few',
        | in 5..10 -> 'many'
        != null -> 'out of bounds'
        == null -> 'null'
    ]

    though we could have guards so we get something similar with the slicker syntax of the original suggestion:

    match x [
        1 -> 'one'
        2..5 -> 'a few',
        5..10 -> 'many'
        _ if x != null -> 'out of bounds'
        null -> 'null'
    ]

    (Something I just found with rust — if x is itself a range 2..5, then matching on it won't work, because 2..5 matches against a range of ints, I guess at the language level, not against the value of x)


    Possibly the "closest" option is to allow switch on:x, do the == 1 -> 'one' option, and then later add a match statement. (but no strong view at all — all of these have tradeoffs)

  4. aljazerzen commented on Dec 20, 2022

    @aljazerzen
    Member

    Yes, the semantics of:

    match x [
      cond1 -> val1
      .. -> val2
    ]
    

    would be the same as of:

    switch [
       x | in cond1 -> val1
       true -> val2
    ]
    

    I don't like the guard too much, because it's heavy in additional syntax while it could be rewritten into:

    match x [
        1 -> 'one'
        2..5 -> 'a few',
        5..10 -> 'many',
        _ -> switch [
            x != null -> 'out of bounds',
            true -> 'null',
        ]
    ]
    

    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.

  5. snth commented on Dec 20, 2022

    @snth
    Member

    I'm in favour of keeping the current switch using 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 match statement for the common case where you want to compare a single column/expression against multiple values/conditions.

    (Putting thoughts/ideas on match syntax in a separate reply so you can easily downvote/comment on that.)

  6. snth commented on Dec 20, 2022

    @snth
    Member

    Would it be possible to extend the match syntax so that it's not just for the in function but any function?

    match x [
      in range1 -> val1
      func2 -> val2
      .. -> val3
    ]

    would be the same as:

    switch [
       x | in range1 -> val1
       x | func2 -> val2
       true -> val3
    ]

    Then if any match condition involving _ could be rewritten into a lambda, e.g.
    _ > 5 becomes func _lambda1 _ -> _ > 5 then you could write

    match x [
      _ > 5 -> val2
      .. -> val3
    ]

    would become

    switch [
       x | (func _lambda1 _ -> _ > 5`) -> val2
       true -> val3
    ]

    Of course there's not much gained over simply using switch when your match expression is simply x but when you're matching instead on something like (temp_fahrenheit - 32) / 1.8 or more complicated then that is quite a saving.

    Of course this goes against "not introducing too many features into the language".

  7. snth commented on Dec 20, 2022

    @snth
    Member

    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

    match col1 [
      _ > col2 -> val2,
      ... -> val3
    ]

    since that would become

    switch [
       col1 | (func _lambda1 _ -> _ > col2`) -> val2
       true -> val3
    ]

    Better just to rewrite the expression involving the _ if you were to go that route.

  8. aljazerzen commented on Dec 21, 2022

    @aljazerzen
    Member

    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:

    match x [
      in foo -> val1,
      eq bar -> val2,
      func2 -> val3,
      default -> val4,
    ]
    # ... is equivalent to:
    switch [
      (x | in foo) -> val1,
      (x | eq bar) -> val2,
      (x | func2) -> val3,
      (x | default) -> val4,
    ]
    
    # ... where default is defined as:
    func default x -> true
    func eq a b -> a == b

    For this to be ergonomic, we'd need a special impl for std.in:

    func in pattern val -> {
       # internal compiler implementation
       if low..high = pattern {
         `val BETWEEN low and HIGH`
       } else if low.. = pattern {
         `val >= low`
       } else if ..high = pattern {
         `val <= high`
       } else if .. = pattern {
         `true`
       } else if list = pattern {
         `val IN (list)`
       } else {
          raise error
       }
    }
    

    Original example could be rewritten as:

    match score [
      in ..10 -> "low",
      in ..30 -> "medium",
      in ..70 -> "high",
      eq null -> "missing",
      default -> "very high",
    ]
  9. snth commented on Dec 21, 2022

    @snth
    Member

    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 default function. 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:

    • other
    • catch_all
    • true
      (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_else and and_then type combinators. Would go with another one called and_false which always returns false.)

    If we're going to go with eq then 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 Python operator module, Bash Comparison operators, HTML Character Escape Codes.


    Actually, from looking at your std.in implementation, I see you're already catering for a in .. case mapping to true, so with three extra cases you could probably get the whole thing done with the in function:

       } else if low<.. = pattern {
         `val > low`
       } else if ..<high = pattern {
         `val < high`
       } else if value = pattern {
         `val == value 
       }

    and then the example would be:

    match score [
      in null -> "missing",
      in ..<0 -> "negative",
      in ..10 -> "low",
      in ..30 -> "medium",
      in ..70 -> "high",
      in 100<.. -> "very high",
      in .. -> "NaN",
    ]

    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:

    match score [
      _==null -> "missing",
      _<0 -> "negative",
      _<=10 -> "low",
      _<=30 -> "medium",
      _<=70 -> "high",
      100<_ -> "very high",
      or_true -> "NaN",
    ]

    Actually the previous case with just the in functions looks pretty neat. in null is 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.

    match score [
      in [null] -> "missing",
      in ..<0 -> "negative",
      ...
      in .. -> "NaN",
    ]
  10. snth commented on Dec 21, 2022

    @snth
    Member

    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

    derive [
      compensation_factor = match date [
        is_workday -> 1,
        is_saturday -> 1.5,
        is_public_holiday -> 2,
        in .. -> null,
        ]
      ]
  11. aljazerzen commented on Dec 22, 2022

    @aljazerzen
    Member

    I have some reservations about the naming of the default function.

    I see. We can hold off from defining default and use in .. as you suggested.


    If we're going to go with eq then we might as well go with all the other standard comparison operators as well

    Sure, I doubt there is any cost to this (unlikely column/table names).


       ...
       else if value = pattern {
         `val == value 
       }
    

    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.

  12. max-sixty commented on Dec 24, 2022

    @max-sixty
    MemberAuthor

    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 write eq rather 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.

  13. aljazerzen commented on Dec 24, 2022

    @aljazerzen
    Member

    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´

  14. max-sixty commented on Dec 25, 2022

    @max-sixty
    MemberAuthor

    Maybe we could have the special rule "if the condition is not a function, just use equals comparison".

    Yes this sounds reasonable!

    Is there an ambiguity when we want to say "is equal to the result of this function"?

    match x [
      5 -> "five"
      add 3 3 -> "six"  # tries to do `add 3 3 x` and fails
    ]

    ...but possibly that's no big deal, this wouldn't be allowed, instead functions need to be pre-computed in a derive.

    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´

    Agree, this is completely fine for the lt etc. neq is an inconvenience but survivable.


    I don't like having == without left expr, because it's not convenient to parse and introduces new sytnax.

    This is fair, though one thing to note — == is already a unary operator from join [==id]. But != & >= & friends would indeed need parsing changes.


    Something I realized while thinking about this is that Rust also has a small ambiguity:

        let x = 0..5;
        match x {
            0..5 => true,   # doesn't match based on equality of `0..5 == 0..5` like any other match
            _ => false
        }

    ...fails because ranges are special.


    Not to expand the scope of this needlessly — but worth raising that these plans commit us to having in as a function, rather than an infix operator like and and or. Do we want that?

    Whether things like in or as are infix or functions has no Correct answer — it's the usual tradeoff between convenience and consistency.

    It's possible to have in like x in 5..10. This ingrains in in 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 in becomes 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.

  15. aljazerzen commented on Dec 26, 2022

    @aljazerzen
    Member

    This is fair, though one thing to note — == is already a unary operator from join [==id].

    This is actually a conflict between the two meanings. If use ==column in match, it this a unary operator or the binary with first arg omitted?


    Something I realized while thinking about this is that Rust also has a small ambiguity:

    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.


    these plans commit us to having in as a function

    This is true and I don't like its current function signature. The fact that these two are idiomatic is not too appealing:

    (x | in 1..5)
    in 1..5 x
    

    Another idea is to make all binary operations just normal functions (and maybe unary also).

    Like have something like:

    func binary in left right -> <built-in>
    func binary + left right -> <built-in>
    
    x in y
    a + b
    

    This is a major breaking change, because it then requires much more parenthesis:

    derive 5 + 6
    # would be parsed as:
    FuncCall
    - function: derive
    - args: [5, +, 6]
    
    derive (5 + 6)
    # would be parsed as:
    FuncCall:
      function: derive
      args:
      - FuncCall:
          function: +
          args: [5, 6]
    

    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:

    • define normal functions for each of the operators and use currying,
    • syntax for constructing lambda functions as _ == 4,
    • (only in match conditions) allow omitting the leading operand in binary ops.
  16. 20 remaining items

  17. max-sixty commented on Jan 24, 2023

    @max-sixty
    MemberAuthor

    I think personal aesthetics are important and are ok to discuss. Where the danger lies, and why often it's a good idea to avoid them, is when I try to convince you that my aesthetics are better than yours. Another danger would be to argue for something with technical reasons when it's really motivated by personal aesthetics and that's being hidden. I think that goes with @max-sixty 's point about trust.

    I tried to be very transparent in my description to differentiate where I saw technical merits and what I were aesthetical motivations for that reason. In a way I tried to make it easy to shoot down my arguments because I know in technical communities like ours there's not always a lot of weight placed on aesthetics.

    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.

  18. max-sixty commented on Jan 24, 2023

    @max-sixty
    MemberAuthor

    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!

  19. aljazerzen commented on Jan 24, 2023

    @aljazerzen
    Member

    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.

  20. max-sixty commented on Jan 24, 2023

    @max-sixty
    MemberAuthor

    It is decided...
    image

  21. snth commented on Jan 24, 2023

    @snth
    Member

    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
    => : match

    Elixir

    -> : functions
    => : key-value pairs (dictionaries)

    image
    image

    Julia

    -> : functions
    => : key-value pairs (dictionaries)

    image

  22. richb-hanover commented on Feb 24, 2023

    @richb-hanover
    Contributor

    @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...

  23. aljazerzen commented on Feb 25, 2023

    @aljazerzen
    Member

    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.

  24. richb-hanover commented on Feb 25, 2023

    @richb-hanover
    Contributor

    Oh. I definitely did not intend to re-open a "decided issue." Is this closed, with a plan to use the current switch syntax? I will note:

    Thanks, and sorry...

  25. aljazerzen commented on Feb 25, 2023

    @aljazerzen
    Member

    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.

  26. richb-hanover commented on Feb 25, 2023

    @richb-hanover
    Contributor

    You were absolutely not dismissive. I'm just trying to understand the decision...

    I will note that it still appears that the switch statement currently uses ->. For example, this works in the 0.5.2 playground:

    from foo
    select [
      c = switch [
      a < b -> 1,
      a >= b -> 2,
     ]
    ]
    
  27. max-sixty commented on Feb 25, 2023

    @max-sixty
    MemberAuthor

    @max-sixty have we forgot to re-apply a revert?

    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

  28. vanillajonathan commented on Jul 3, 2023

    @vanillajonathan
    Collaborator

    Can you match an integer between 3 and 8?
    Can you match a letter between a and f?
    Can you match character between 0–9 and a to f?

  29. max-sixty commented on Jul 22, 2023

    @max-sixty
    MemberAuthor

    Can you match an integer between 3 and 8? Can you match a letter between a and f? Can you match character between 0–9 and a to f?

    Any expression! Because it's a case rather than a match, it's just running a normal expression for each arm:

    from employees
    derive foo = case {
      (size | in 2..10) => x,
    }
  30. max-sixty commented on Jul 22, 2023

    @max-sixty
    MemberAuthor

    I think this is in a good place now, so closing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    language-design

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions